Click here to Skip to main content
15,896,207 members
Articles / Multimedia / DirectX

C# Synth Toolkit - Part I

Rate me:
Please Sign up or sign in to vote.
4.89/5 (33 votes)
17 Aug 2007MIT13 min read 239K   6.4K   130  
A toolkit for creating software synthesizers with C# and Managed DirectX.
#region License

/* Copyright (c) 2007 Leslie Sanford
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy 
 * of this software and associated documentation files (the "Software"), to 
 * deal in the Software without restriction, including without limitation the 
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 
 * sell copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in 
 * all copies or substantial portions of the Software. 
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 * THE SOFTWARE.
 */

#endregion

#region Contact

/*
 * Leslie Sanford
 * Email: jabberdabber@hotmail.com
 */

#endregion

using System;
using System.Collections.Generic;
using System.Diagnostics;
using Sanford.Multimedia.Midi;

namespace Sanford.Multimedia.Synth
{
    /// <summary>
    /// Provides functionality for dynamically allocating voices in response
    /// to MIDI note-on and note-off messages.
    /// </summary>
    internal sealed class VoiceAllocator : IProgrammable
    {
        #region VoiceAllocator Members

        public enum ParameterId
        {
            PolyphonyMode
        }

        #region Fields

        // The list of all voices.
        private List<Voice> voices;

        // The list of voices that have been triggered.
        private List<Voice> triggeredVoices;

        // The list of voices that have been released.
        private List<Voice> releasedVoices;

        private Queue<ChannelMessage> messageQueue = new Queue<ChannelMessage>();

        // The list of note-off messages that are being delayed because
        // the sustain pedal is currently depressed.
        private List<ChannelMessage> delayedNoteOffMessages;

        // Indicates whether the sustain pedal has been depressed.
        private bool sustainEnabled = false;

        // For tracking currently playing notes.
        private NoteTracker tracker = new NoteTracker();

        // The type of polyphony to use.
        private PolyMode mode = PolyMode.Polyphonic;        

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes an instance of the VoiceAllocator class with a collection
        /// of voices to use for voice allocation.
        /// </summary>
        /// <param name="voices">
        /// The collection of voices to use.
        /// </param>
        public VoiceAllocator(IEnumerable<Voice> voices)
        {
            this.voices = new List<Voice>(voices);
            this.releasedVoices = new List<Voice>(voices);
            this.triggeredVoices = new List<Voice>();
            this.delayedNoteOffMessages = new List<ChannelMessage>();
        }

        #endregion

        #region Methods

        public void Allocate(ChannelMessage message)
        {
            messageQueue.Enqueue(message);

            ProcessMessages();
        }

        public void AllSoundOff()
        {
            messageQueue.Clear();
            tracker.Clear();
            delayedNoteOffMessages.Clear();

            foreach(Voice voice in triggeredVoices)
            {
                releasedVoices.Add(voice);
            }

            triggeredVoices.Clear();
        }

        private void ProcessMessages()
        {
            while(messageQueue.Count > 0)
            {
                ProcessMessage(messageQueue.Dequeue());
            }
        }

        private void ProcessMessage(ChannelMessage message)
        {
            // If the message is a note-on message.
            if(message.Command == ChannelCommand.NoteOn)
            {
                // If the message is in fact a note-on message.
                if(message.Data2 > 0)
                {
                    ProcessNoteOnMessage(message);
                }
                // Else the message is a note-off message. Note-on messages
                // with a velocity of 0 are really note-off messages.
                else
                {
                    ProcessNoteOffMessage(message);
                }
            }
            // Else if the message is a note-off message.
            else if(message.Command == ChannelCommand.NoteOff)
            {
                ProcessNoteOffMessage(message);
            }
        }

        private void ProcessNoteOnMessage(ChannelMessage message)
        {
            Debug.Assert(message.Command == ChannelCommand.NoteOn && message.Data2 > 0);

            float velocity = (float)message.Data2 / ChannelMessage.DataMaxValue;

            // If there are any voices in the released voice list.
            if(releasedVoices.Count > 0)
            {
                // Get voice that has been released the longest.
                Voice voice = releasedVoices[0];

                // Remove voice from the released voice list.
                releasedVoices.RemoveAt(0);

                // Trigger voice.
                voice.Trigger(tracker.LastNote, message.Data1, velocity);

                // Since the voice has been triggered, add it to the triggered
                // voice list.
                triggeredVoices.Add(voice);
            }
            // Else if there voices in the triggered voice list.
            else if(triggeredVoices.Count > 0)
            {
                // Get voice that has been triggered the longest (we're "stealing" a voice).
                Voice voice = triggeredVoices[0];

                // Remove voice from triggered voice list.
                triggeredVoices.RemoveAt(0);

                // Trigger voice.
                voice.Trigger(tracker.LastNote, message.Data1, velocity);

                // Add voice to the front of the triggered voice list. 
                triggeredVoices.Add(voice);
            }

            // Pass message along to the note tracker.
            tracker.NoteOn(message);
        }

        private void ProcessNoteOffMessage(ChannelMessage message)
        {
            Debug.Assert(message.Command == ChannelCommand.NoteOff ||
                (message.Command == ChannelCommand.NoteOn && message.Data2 == 0));

            float velocity = (float)message.Data2 / ChannelMessage.DataMaxValue;

            // If the sustain pedal has been depressed.
            if(sustainEnabled)
            {
                // Delay processing note-off messages.
                delayedNoteOffMessages.Add(message);
            }
            // Else the sustain pedal has not been depressed.
            else
            {
                // Pass message along to note tracker.
                tracker.NoteOff(message);

                // Find the index into the triggered voice list of the voice
                // that is playing the specified note.
                int index = triggeredVoices.FindIndex(delegate(Voice voice)
                {
                    if(voice.CurrentNote == message.Data1)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                });

                // If a voice was playing the specified note.
                if(index >= 0)
                {
                    // Get the voice that is playing the specified note.
                    Voice voice = triggeredVoices[index];

                    // If mode is polyphonic.
                    if(mode == PolyMode.Polyphonic)
                    {
                        // Release voice.
                        voice.Release(velocity);

                        // Remove voice from triggered voice list since it has 
                        // been released.
                        triggeredVoices.RemoveAt(index);

                        // Add voice to the released voice list since it has
                        // been released.
                        releasedVoices.Add(voice);
                    }
                    // Else mode is monophonic.
                    else
                    {
                        // If a note played previously to the specified note
                        // is still playing.
                        if(tracker.Count > 0)
                        {
                            // Instead of releasing voice, retrigger it with the 
                            // previous playing note. This is done in order to mimic
                            // how a monophonic analog synth behaves.
                            voice.Trigger(voice.CurrentNote, tracker.LastNote, 1);
                        }
                        // Else no other note is playing.
                        else
                        {
                            // Release voice.
                            voice.Release(velocity);

                            // Remove voice from triggered voice list since it has 
                            // been released.
                            triggeredVoices.RemoveAt(index);

                            // Add voice to the released voice list since it has
                            // been released.
                            releasedVoices.Add(voice);
                        }
                    }
                }
            }            
        }

        private void Reset()
        {
            // Release all currently triggered voices.
            foreach(Voice voice in triggeredVoices)
            {
                voice.Release(0);
            }

            //
            // Clear all lists.
            //

            delayedNoteOffMessages.Clear();
            messageQueue.Clear();
            triggeredVoices.Clear();
            releasedVoices.Clear();

            // If mode is polyphonic.
            if(mode == PolyMode.Polyphonic)
            {
                // Place all voices in the released list. As new notes are
                // played, voices will be drawn from this list.
                foreach(Voice voice in voices)
                {
                    releasedVoices.Add(voice);
                }
            }
            // Else mode is monophonic.
            else
            {
                // If there are any voices.
                if(voices.Count > 0)
                {
                    // Add only a single voice to the released list. This 
                    // is the voice that will be used to play monophonically.
                    releasedVoices.Add(voices[0]);
                }
            }
        }

        #endregion

        #region Properties

        public bool SustainEnabled
        {
            set
            {
                #region Guard

                if(value == sustainEnabled)
                {
                    return;
                }

                #endregion

                sustainEnabled = value;

                if(!sustainEnabled)
                {
                    // Place all delayed note-off messages into MIDI queue. 
                    // They can now be processed.
                    foreach(ChannelMessage noteOffMessage in delayedNoteOffMessages)
                    {
                        messageQueue.Enqueue(noteOffMessage);
                    }

                    delayedNoteOffMessages.Clear();

                    ProcessMessages();
                }
            }
        }

        #endregion

        #endregion

        #region IProgrammable Members

        public string GetParameterName(int index)
        {
            #region Require

            if(index < 0 || index >= ParameterCount)
            {
                throw new ArgumentOutOfRangeException("index");
            }

            #endregion

            string result = string.Empty;

            switch((ParameterId)index)
            {
                case ParameterId.PolyphonyMode:
                    result = "Polyphony Mode";
                    break;

                default:
                    Debug.Fail("Unhandled parameter");
                    break;
            }

            return result;
        }

        public string GetParameterLabel(int index)
        {
            #region Require

            if(index < 0 || index >= ParameterCount)
            {
                throw new ArgumentOutOfRangeException("index");
            }

            #endregion

            string result = string.Empty;

            switch((ParameterId)index)
            {
                case ParameterId.PolyphonyMode:
                    result = "Poly/Mono";
                    break;

                default:
                    Debug.Fail("Unhandled parameter");
                    break;
            }

            return result;
        }

        public string GetParameterDisplay(int index)
        {
            #region Require

            if(index < 0 || index >= ParameterCount)
            {
                throw new ArgumentOutOfRangeException("index");
            }

            #endregion

            string result = string.Empty;

            switch((ParameterId)index)
            {
                case ParameterId.PolyphonyMode:
                    result = mode.ToString();
                    break;

                default:
                    Debug.Fail("Unhandled parameter");
                    break;
            }

            return result;
        }

        public float GetParameterValue(int index)
        {
            #region Require

            if(index < 0 || index >= ParameterCount)
            {
                throw new ArgumentOutOfRangeException("index");
            }

            #endregion

            float result = 0;

            switch((ParameterId)index)
            {
                case ParameterId.PolyphonyMode:
                    if(mode == PolyMode.Polyphonic)
                    {
                        result = 0;
                    }
                    else
                    {
                        result = 1;
                    }
                    break;

                default:
                    Debug.Fail("Unhandled parameter");
                    break;
            }

            return result;
        }

        public void SetParameterValue(int index, float value)
        {
            #region Require

            if(index < 0 || index >= ParameterCount)
            {
                throw new ArgumentOutOfRangeException("index");
            }
            else if(value < 0 || value > 1)
            {
                throw new ArgumentOutOfRangeException("value");
            }

            #endregion

            switch((ParameterId)index)
            {
                case ParameterId.PolyphonyMode:
                    mode = (value < 0.5 ? PolyMode.Polyphonic : PolyMode.Monophonic);
                    Reset();
                    break;

                default:
                    Debug.Fail("Unhandled parameter");
                    break;
            }
        }

        public int ParameterCount
        {
            get
            {
                return (int)ParameterId.PolyphonyMode + 1;
            }
        }

        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
United States United States
Aside from dabbling in BASIC on his old Atari 1040ST years ago, Leslie's programming experience didn't really begin until he discovered the Internet in the late 90s. There he found a treasure trove of information about two of his favorite interests: MIDI and sound synthesis.

After spending a good deal of time calculating formulas he found on the Internet for creating new sounds by hand, he decided that an easier way would be to program the computer to do the work for him. This led him to learn C. He discovered that beyond using programming as a tool for synthesizing sound, he loved programming in and of itself.

Eventually he taught himself C++ and C#, and along the way he immersed himself in the ideas of object oriented programming. Like many of us, he gotten bitten by the design patterns bug and a copy of GOF is never far from his hands.

Now his primary interest is in creating a complete MIDI toolkit using the C# language. He hopes to create something that will become an indispensable tool for those wanting to write MIDI applications for the .NET framework.

Besides programming, his other interests are photography and playing his Les Paul guitars.

Comments and Discussions