/[svn]/linuxsampler/trunk/src/engines/common/Event.h
ViewVC logotype

Diff of /linuxsampler/trunk/src/engines/common/Event.h

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 293 by schoenebeck, Mon Oct 25 15:14:27 2004 UTC revision 2935 by schoenebeck, Sun Jul 10 14:24:13 2016 UTC
# Line 3  Line 3 
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
6     *   Copyright (C) 2005 - 2016 Christian Schoenebeck                       *
7   *                                                                         *   *                                                                         *
8   *   This program is free software; you can redistribute it and/or modify  *   *   This program is free software; you can redistribute it and/or modify  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 24  Line 25 
25  #define __LS_EVENT_H__  #define __LS_EVENT_H__
26    
27  #include "../../common/global.h"  #include "../../common/global.h"
28    #include "../../common/RTMath.h"
29    #include "../../common/RTAVLTree.h"
30    #include "../../common/Pool.h"
31    #include "../EngineChannel.h"
32    
33  namespace LinuxSampler {  namespace LinuxSampler {
34    
35      // just symbol prototyping      // just symbol prototyping
36      class Event;      class Event;
37        class SchedulerNode;
38        class ScriptEvent;
39        class ScheduledEvent;
40    
41        /**
42         * Data type used to schedule events sample point accurately both within, as
43         * well as beyond the scope of the current audio fragment cycle. The timing
44         * reflected by this data type is consecutively running for a very long
45         * time. Even with a sample rate of 96 kHz a scheduler time of this data
46         * type will not wrap before 6 million years. So in practice such time
47         * stamps are unique and will not repeat (unless the EventGenerator is
48         * reset).
49         */
50        typedef uint64_t sched_time_t;
51    
52      /**      /**
53       * Generates Event objects and is responsible for resolving the position       * Generates Event objects and is responsible for resolving the position
# Line 39  namespace LinuxSampler { Line 58  namespace LinuxSampler {
58              EventGenerator(uint SampleRate);              EventGenerator(uint SampleRate);
59              void UpdateFragmentTime(uint SamplesToProcess);              void UpdateFragmentTime(uint SamplesToProcess);
60              Event CreateEvent();              Event CreateEvent();
61                Event CreateEvent(int32_t FragmentPos);
62    
63                template<typename T>
64                void scheduleAheadMicroSec(RTAVLTree<T>& queue, T& node, int32_t fragmentPosBase, uint64_t microseconds);
65    
66                RTList<ScheduledEvent>::Iterator popNextScheduledEvent(RTAVLTree<ScheduledEvent>& queue, Pool<ScheduledEvent>& pool, sched_time_t end);
67                RTList<ScriptEvent>::Iterator popNextScheduledScriptEvent(RTAVLTree<ScriptEvent>& queue, Pool<ScriptEvent>& pool, sched_time_t end);
68    
69                /**
70                 * Returns the scheduler time for the first sample point of the next
71                 * audio fragment cycle.
72                 */
73                sched_time_t schedTimeAtCurrentFragmentEnd() const {
74                    return uiTotalSamplesProcessed + uiSamplesProcessed;
75                }
76    
77          protected:          protected:
78              typedef uint32_t time_stamp_t; ///< We read the processor's cycle count register as a reference for the real time. These are of course only abstract values with arbitrary time entity, but that's not a problem as we calculate relatively.              typedef RTMath::time_stamp_t time_stamp_t;
79              inline int32_t ToFragmentPos(time_stamp_t TimeStamp) {              inline int32_t ToFragmentPos(time_stamp_t TimeStamp) {
80                  return int32_t (int32_t(TimeStamp - FragmentTime.begin) * FragmentTime.sample_ratio);                  return int32_t (int32_t(TimeStamp - FragmentTime.begin) * FragmentTime.sample_ratio);
81              }              }
# Line 53  namespace LinuxSampler { Line 88  namespace LinuxSampler {
88                  time_stamp_t end;          ///< Real time stamp of the end of this audio fragment cycle.                  time_stamp_t end;          ///< Real time stamp of the end of this audio fragment cycle.
89                  float        sample_ratio; ///< (Samples per cycle) / (Real time duration of cycle)                  float        sample_ratio; ///< (Samples per cycle) / (Real time duration of cycle)
90              } FragmentTime;              } FragmentTime;
91              time_stamp_t CreateTimeStamp();              sched_time_t uiTotalSamplesProcessed; ///< Total amount of sample points that have been processed since this EventGenerator object has been created. This is used to schedule instrument script events long time ahead in future (that is beyond the scope of the current audio fragment).
92      };      };
93    
94      /**      /**
95         * Unique numeric ID of an event which can be used to retrieve access to
96         * the actual @c Event object. Once the event associated with a certain ID
97         * was released (back to its event pool), this numeric ID becomes invalid
98         * and Pool< Event >::fromID() will detect this circumstance and will
99         * return an invalid Iterator, and thus will prevent you from misusing an
100         * event which no longer "exists".
101         *
102         * Note that an @c Event object usually just "exists" for exactly on audio
103         * fragment cycle: that is it exists right from the beginning of the audio
104         * fragment cycle where it was caused (i.e. where its MIDI data was
105         * received by the respective engine channel) and will disappear
106         * automatically at the end of that audio fragment cycle.
107         */
108        typedef pool_element_id_t event_id_t;
109    
110        /**
111         * Unique numeric ID of a note which can be used to retrieve access to the
112         * actual @c Note object. Once the note associated with a certain ID was
113         * released (back to its note pool), this numeric ID becomes invalid and
114         * Pool< Note >::fromID() will detect this circumstance and will return
115         * an invalid Iterator, and thus will prevent you from misusing a note
116         * which no longer is "alive".
117         *
118         * A @c Note object exists right when the respective MIDI note-on event
119         * was received by the respective engine channel, and remains existent
120         * until the caused note and all its voices were finally freed (which might
121         * even be long time after the respective note-off event was received,
122         * depending on the duration of the voice's release stages etc.).
123         */
124        typedef pool_element_id_t note_id_t;
125    
126        /**
127       * Events are usually caused by a MIDI source or an internal modulation       * Events are usually caused by a MIDI source or an internal modulation
128       * controller like LFO or EG. An event can only be created by an       * controller like LFO or EG. An event should only be created by an
129       * EventGenerator.       * EventGenerator!
130       *       *
131       * @see EventGenerator       * @see EventGenerator, ScriptEvent
132       */       */
133      class Event {      class Event {
134          public:          public:
# Line 73  namespace LinuxSampler { Line 140  namespace LinuxSampler {
140                  type_control_change,                  type_control_change,
141                  type_sysex,           ///< MIDI system exclusive message                  type_sysex,           ///< MIDI system exclusive message
142                  type_cancel_release,  ///< transformed either from a note-on or sustain-pedal-down event                  type_cancel_release,  ///< transformed either from a note-on or sustain-pedal-down event
143                  type_release          ///< transformed either from a note-off or sustain-pedal-up event                  type_release,         ///< transformed either from a note-off or sustain-pedal-up event
144                    type_channel_pressure, ///< a.k.a. aftertouch
145                    type_note_pressure, ///< polyphonic key pressure (aftertouch)
146                    type_note_synth_param, ///< change a note's synthesis parameters (upon real-time instrument script function calls)
147              } Type;              } Type;
148              enum destination_t {              enum synth_param_t {
149                  destination_vca,   ///< Volume level                  synth_param_volume,
150                  destination_vco,   ///< Pitch depth                  synth_param_pitch,
151                  destination_vcfc,  ///< Filter curoff frequency                  synth_param_pan,
152                  destination_vcfr,  ///< Filter resonance                  synth_param_cutoff,
153                  destination_count  ///< Total number of modulation destinations (this has to stay the last element in the enum)                  synth_param_resonance,
154              };              };
155              union {              union {
156                  /// Note-on and note-off event specifics                  /// Note-on and note-off event specifics
157                  struct _Note {                  struct _Note {
158                        uint8_t Channel;     ///< MIDI channel (0..15)
159                      uint8_t Key;         ///< MIDI key number of note-on / note-off event.                      uint8_t Key;         ///< MIDI key number of note-on / note-off event.
160                      uint8_t Velocity;    ///< Trigger or release velocity of note-on / note-off event.                      uint8_t Velocity;    ///< Trigger or release velocity of note-on / note-off event.
161                      int8_t  Layer;       ///< Layer index (usually only used if a note-on event has to be postponed, e.g. due to shortage of free voices).                      int8_t  Layer;       ///< Layer index (usually only used if a note-on event has to be postponed, e.g. due to shortage of free voices).
162                      int8_t  ReleaseTrigger; ///< If new voice should be a release triggered voice (actually boolean field and usually only used if a note-on event has to be postponed, e.g. due to shortage of free voices).                      int8_t  ReleaseTrigger; ///< If new voice should be a release triggered voice (actually boolean field and usually only used if a note-on event has to be postponed, e.g. due to shortage of free voices).
163                        note_id_t ID;        ///< Unique numeric ID of the @c Note object associated with this note (on) event.
164                        note_id_t ParentNoteID; ///< If not zero: Unique numeric ID of the parent @c Note object that shall become parent of resulting new Note object of this Event. So this is used to associate a new note with a previous note, i.e. to release the new note once the parent note was released.
165                        void*   pRegion;     ///< Engine specific pointer to instrument region
166                  } Note;                  } Note;
167                  /// Control change event specifics                  /// Control change event specifics
168                  struct _CC {                  struct _CC {
169                        uint8_t Channel;     ///< MIDI channel (0..15)
170                      uint8_t Controller;  ///< MIDI controller number of control change event.                      uint8_t Controller;  ///< MIDI controller number of control change event.
171                      uint8_t Value;       ///< Controller Value of control change event.                      uint8_t Value;       ///< Controller Value of control change event.
172                  } CC;                  } CC;
173                  /// Pitchbend event specifics                  /// Pitchbend event specifics
174                  struct _Pitch {                  struct _Pitch {
175                        uint8_t Channel;     ///< MIDI channel (0..15)
176                      int16_t Pitch;       ///< Pitch value of pitchbend event.                      int16_t Pitch;       ///< Pitch value of pitchbend event.
177                  } Pitch;                  } Pitch;
178                  /// MIDI system exclusive event specifics                  /// MIDI system exclusive event specifics
179                  struct _Sysex {                  struct _Sysex {
180                      uint Size;           ///< Data length (in bytes) of MIDI system exclusive message.                      uint Size;           ///< Data length (in bytes) of MIDI system exclusive message.
181                  } Sysex;                  } Sysex;
182                    /// Channel Pressure (aftertouch) event specifics
183                    struct _ChannelPressure {
184                        uint8_t Channel; ///< MIDI channel (0..15)
185                        uint8_t Controller; ///< Should always be assigned to CTRL_TABLE_IDX_AFTERTOUCH.
186                        uint8_t Value;   ///< New aftertouch / pressure value for keys on that channel.
187                    } ChannelPressure;
188                    /// Polyphonic Note Pressure (aftertouch) event specifics
189                    struct _NotePressure {
190                        uint8_t Channel; ///< MIDI channel (0..15)
191                        uint8_t Key;     ///< MIDI note number where key pressure (polyphonic aftertouch) changed.
192                        uint8_t Value;   ///< New pressure value for note.
193                    } NotePressure;
194                    ///< Note synthesis parameter change event's specifics (used for real-time instrument script built-in functions which may alter synthesis parameters on note level).
195                    struct _NoteSynthParam {
196                        note_id_t     NoteID;   ///< ID of Note whose voices shall be modified.
197                        synth_param_t Type;     ///< Synthesis parameter which is to be changed.
198                        float         Delta;    ///< The value change that should be applied against the note's current synthesis parameter value.
199                        bool          Relative; ///< Whether @c Delta should be applied relatively against the note's current synthesis parameter value (false means the paramter's current value is simply replaced by Delta).
200                        float         AbsValue; ///< New current absolute value of synthesis parameter (that is after @c Delta being applied).
201                    } NoteSynthParam;
202              } Param;              } Param;
203                EngineChannel* pEngineChannel; ///< Pointer to the EngineChannel where this event occured on, NULL means Engine global event (e.g. SysEx message).
204                MidiInputPort* pMidiInputPort; ///< Pointer to the MIDI input port on which this event occured (NOTE: currently only for global events, that is SysEx messages)
205    
206                inline void Init() {
207                    Param.Note.ID = 0;
208                    Param.Note.ParentNoteID = 0;
209                    Param.NoteSynthParam.NoteID = 0;
210                }
211              inline int32_t FragmentPos() {              inline int32_t FragmentPos() {
212                  if (iFragmentPos >= 0) return iFragmentPos;                  if (iFragmentPos >= 0) return iFragmentPos;
213                  iFragmentPos = pEventGenerator->ToFragmentPos(TimeStamp);                  iFragmentPos = pEventGenerator->ToFragmentPos(TimeStamp);
# Line 114  namespace LinuxSampler { Line 217  namespace LinuxSampler {
217              inline void ResetFragmentPos() {              inline void ResetFragmentPos() {
218                  iFragmentPos = -1;                  iFragmentPos = -1;
219              }              }
220                inline void CopyTimeFrom(const Event& other) {
221                    TimeStamp = other.TimeStamp;
222                    iFragmentPos = other.iFragmentPos;
223                }
224          protected:          protected:
225              typedef EventGenerator::time_stamp_t time_stamp_t;              typedef EventGenerator::time_stamp_t time_stamp_t;
226              Event(EventGenerator* pGenerator, EventGenerator::time_stamp_t Time);              Event(EventGenerator* pGenerator, EventGenerator::time_stamp_t Time);
227                Event(EventGenerator* pGenerator, int32_t FragmentPos);
228              friend class EventGenerator;              friend class EventGenerator;
229          private:          private:
230              EventGenerator* pEventGenerator; ///< Creator of the event.              EventGenerator* pEventGenerator; ///< Creator of the event.
# Line 124  namespace LinuxSampler { Line 232  namespace LinuxSampler {
232              int32_t         iFragmentPos;    ///< Position in the current fragment this event refers to.              int32_t         iFragmentPos;    ///< Position in the current fragment this event refers to.
233      };      };
234    
235        /**
236         * Used to sort timing relevant objects (i.e. events) into timing/scheduler
237         * queue. This class is just intended as base class and should be derived
238         * for its actual purpose (for the precise data type being scheduled).
239         */
240        class SchedulerNode : public RTAVLNode {
241        public:
242            sched_time_t scheduleTime; ///< Time ahead in future (in sample points) when this object shall be processed. This value is compared with EventGenerator's uiTotalSamplesProcessed member variable.
243    
244            /// Required operator implementation for RTAVLTree class.
245            inline bool operator==(const SchedulerNode& other) const {
246                return this->scheduleTime == other.scheduleTime;
247            }
248    
249            /// Required operator implementation for RTAVLTree class.
250            inline bool operator<(const SchedulerNode& other) const {
251                return this->scheduleTime < other.scheduleTime;
252            }
253        };
254    
255        /**
256         * Used to sort delayed MIDI events into a timing/scheduler queue. This
257         * object just contains the timing informations, the actual MIDI event is
258         * pointed by member variable @c itEvent.
259         */
260        class ScheduledEvent : public SchedulerNode {
261        public:
262            Pool<Event>::Iterator itEvent; ///< Points to the actual Event object being scheduled.
263        };
264    
265        class VMEventHandler;
266        class VMExecContext;
267    
268        /** @brief Real-time instrument script event.
269         *
270         * Encapsulates one execution instance of a real-time instrument script for
271         * exactly one script event handler (script event callback).
272         *
273         * This class derives from SchedulerNode for being able to be sorted efficiently
274         * by the script scheduler if the script was either a) calling the wait()
275         * script function or b) the script was auto suspended by the ScriptVM
276         * because the script was executing for too long. In both cases the
277         * scheduler has to sort the ScriptEvents in its execution queue according
278         * to the precise time the respective script execution instance needs to be
279         * resumed.
280         */
281        class ScriptEvent : public SchedulerNode {
282        public:
283            Event cause; ///< Copy of original external @c Event that triggered this script event (i.e. MIDI note on event, MIDI CC event, etc.).
284            pool_element_id_t id; ///< Native representation of built-in script variable $EVENT_ID. For scripts' "note" event handler this will reflect the unique ID of the @c Note object, for all other event handlers the unique ID of the original external @c Event object that triggered this script event.
285            VMEventHandler** handlers; ///< The script's event handlers (callbacks) to be processed (NULL terminated list).
286            VMExecContext* execCtx; ///< Script's current execution state (polyphonic variables and execution stack).
287            int currentHandler; ///< Current index in 'handlers' list above.
288            int executionSlices; ///< Amount of times this script event has been executed by the ScriptVM runner class.
289        };
290    
291        /**
292         * Insert given @a node into the supplied timing @a queue with a scheduled
293         * timing position given by @a fragmentPosBase and @a microseconds, where
294         * @a microseconds reflects the amount of microseconds in future from "now"
295         * where the node shall be scheduled, and @a fragmentPos identifies the
296         * sample point within the current audio fragment cycle which shall be
297         * interpreted by this method to be "now".
298         *
299         * The meaning of @a fragmentPosBase becomes more important the larger
300         * the audio fragment size, and vice versa it bcomes less important the
301         * smaller the audio fragment size.
302         *
303         * @param queue - destination scheduler queue
304         * @param node - node (i.e. event) to be inserted into the queue
305         * @param fragmentPosBase - sample point in current audio fragment to be "now"
306         * @param microseconds - timing of node from "now" (in microseconds)
307         */
308        template<typename T>
309        void EventGenerator::scheduleAheadMicroSec(RTAVLTree<T>& queue, T& node, int32_t fragmentPosBase, uint64_t microseconds) {
310            node.scheduleTime = uiTotalSamplesProcessed + fragmentPosBase + float(uiSampleRate) * (float(microseconds) / 1000000.f);
311            queue.insert(node);
312        }
313    
314  } // namespace LinuxSampler  } // namespace LinuxSampler
315    
316  #endif // __LS_EVENT_H__  #endif // __LS_EVENT_H__

Legend:
Removed from v.293  
changed lines
  Added in v.2935

  ViewVC Help
Powered by ViewVC