1 //=========================================================
2 //  MusE
3 //  Linux Music Editor
4 //  $Id: audio.h,v 1.25.2.13 2009/12/20 05:00:35 terminator356 Exp $
5 //
6 //  (C) Copyright 2001 Werner Schweer (ws@seh.de)
7 //  (C) Copyright 2011 Tim E. Real (terminator356 on users dot sourceforge dot net)
8 //
9 //  This program is free software; you can redistribute it and/or
10 //  modify it under the terms of the GNU General Public License
11 //  as published by the Free Software Foundation; version 2 of
12 //  the License, or (at your option) any later version.
13 //
14 //  This program is distributed in the hope that it will be useful,
15 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
16 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 //  GNU General Public License for more details.
18 //
19 //  You should have received a copy of the GNU General Public License
20 //  along with this program; if not, write to the Free Software
21 //  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
22 //
23 //=========================================================
24 
25 #ifndef __AUDIO_H__
26 #define __AUDIO_H__
27 
28 #include <stdint.h>
29 
30 #include "type_defs.h"
31 #include "thread.h"
32 #include "pos.h"
33 #include "route.h"
34 #include "event.h"
35 
36 
37 // Forward declarations:
38 namespace MusECore {
39 class AudioDevice;
40 class AudioTrack;
41 class MidiDevice;
42 class MidiInstrument;
43 class MidiPlayEvent;
44 class MidiPort;
45 class MidiTrack;
46 class Part;
47 class PluginI;
48 class SynthI;
49 class Track;
50 class Undo;
51 class PendingOperationList;
52 class ExtMidiClock;
53 
54 //---------------------------------------------------------
55 //   AudioMsgId
56 //    this are the messages send from the GUI thread to
57 //    the midi thread
58 //---------------------------------------------------------
59 
60 enum {
61       SEQM_REVERT_OPERATION_GROUP, SEQM_EXECUTE_OPERATION_GROUP,
62       SEQM_EXECUTE_PENDING_OPERATIONS,
63       SEQM_RESET_DEVICES, SEQM_INIT_DEVICES, SEQM_PANIC,
64       SEQM_MIDI_LOCAL_OFF,
65       SEQM_PLAY_MIDI_EVENT,
66       SEQM_SET_HW_CTRL_STATE,
67       SEQM_SET_HW_CTRL_STATES,
68       SEQM_SET_TRACK_AUTO_TYPE,
69       SEQM_SET_AUX,
70       SEQM_UPDATE_SOLO_STATES,
71       AUDIO_ROUTEADD, AUDIO_ROUTEREMOVE, AUDIO_REMOVEROUTES,
72       AUDIO_ADDPLUGIN,
73       AUDIO_SET_PREFADER, AUDIO_SET_CHANNELS,
74       AUDIO_SWAP_CONTROLLER_IDX,
75       AUDIO_CLEAR_CONTROLLER_EVENTS,
76       AUDIO_SEEK_PREV_AC_EVENT,
77       AUDIO_SEEK_NEXT_AC_EVENT,
78       AUDIO_ERASE_AC_EVENT,
79       AUDIO_ERASE_RANGE_AC_EVENTS,
80       AUDIO_ADD_AC_EVENT,
81       AUDIO_CHANGE_AC_EVENT,
82       AUDIO_SET_SEND_METRONOME,
83       AUDIO_START_MIDI_LEARN,
84       MS_PROCESS, MS_STOP, MS_SET_RTC, MS_UPDATE_POLL_FD,
85       SEQM_IDLE, SEQM_SEEK,
86       AUDIO_WAIT  // Do nothing. Just wait for an audio cycle to pass.
87       };
88 
89 extern const char* seqMsgList[];  // for debug
90 
91 //---------------------------------------------------------
92 //   Msg
93 //---------------------------------------------------------
94 
95 struct AudioMsg : public ThreadMsg {   // this should be an union
96       int serialNo;
97       //SndFile* downmix; // DELETETHIS this is unused and probably WRONG (all SndFiles have been replaced by SndFileRs)
98       AudioTrack* snode;
99       AudioTrack* dnode;
100       Route sroute, droute;
101       AudioDevice* device;
102       int ival;
103       int iival;
104       double dval;
105       PluginI* plugin;
106       SynthI* synth;
107       Part* spart;
108       Part* dpart;
109       Track* track;
110 
111       const void *p1, *p2, *p3;
112       Event ev1, ev2;
113       char port, channel, ctrl;
114       int a, b, c;
115       Pos pos;
116       Undo* operations;
117       PendingOperationList* pendingOps;
118       };
119 
120 //---------------------------------------------------------
121 //   Audio
122 //---------------------------------------------------------
123 
124 class Audio {
125    public:
126       enum State {STOP, START_PLAY, PLAY, LOOP1, LOOP2, SYNC, PRECOUNT};
127       enum BounceState { BounceOff = 0, BounceStart, BounceOn };
128 
129    private:
130       bool _running;          // audio is active
131       bool recording;         // recording is active
132       bool idle;              // do nothing in idle mode
133       bool _freewheel;
134       BounceState _bounceState;
135       unsigned _loopFrame;     // Startframe of loop if in LOOP mode. Not quite the same as left marker !
136       int _loopCount;         // Number of times we have looped so far
137 
138       Pos _pos;               // current play position
139       unsigned int _curCycleFrames;   // Number of frames in the current process cycle.
140       // Simulated current frame during precount.
141       unsigned int _precountFramePos;
142 
143       unsigned curTickPos;   // pos at start of frame during play/record
144       unsigned nextTickPos;  // pos at start of next frame during play/record
145 
146       // Holds a brief temporary array of sorted FRAMES of clock history, filled from the external clock history fifo.
147       ExtMidiClock *_extClockHistory;
148       // Holds the total capacity of the clock history list.
149       static const int _extClockHistoryCapacity;
150       // Holds the current size of the temporary clock history array.
151       int _extClockHistorySize;
152 
153       // Holds a brief temporary array of sorted FRAMES of clock queue, to be output to midi devices.
154       unsigned int* _clockOutputQueue;
155       // Holds the total capacity of the clock output array.
156       static const unsigned int _clockOutputQueueCapacity;
157       // Holds the current size of the temporary clock output array.
158       unsigned int _clockOutputQueueSize;
159       // Holds a central counter, in ticks, for generating midi clock out events for all device types.
160       unsigned int _clockOutputCounter;
161       // Fractional accumulator for _clockOutputCounter.
162       uint64_t _clockOutputCounterRemainder;
163 
164       //metronome values
165       unsigned midiClick;
166       unsigned audioClick;
167       int clickno;      // precount values
168       int clicksMeasure;
169       // Frames per beat, in precount state.
170       unsigned framesBeat;
171       // Frames per beat fractional divisor part.
172       uint32_t framesBeatDivisor;
173       // Frames per beat fractional remainder part.
174       uint32_t framesBeatRemainder;
175       unsigned precountTotalFrames;
176       unsigned precountMidiClickFrame;
177       // Fractional accumulator for precountMidiClick.
178       uint64_t precountMidiClickFrameRemainder;
179       // Indicates transport went from STOP to START_PLAY.
180       // Used for sync to determine whether to start PRECOUNT mode.
181       bool _syncPlayStarting;
182       // Prevents flood of events during seek.
183       float _antiSeekFloodCounter;
184       // Whether the last call to the sync callback was ready to roll.
185       bool _syncReady;
186 
187       uint64_t syncTimeUS;  // Wall clock at last sync point in microseconds.
188       unsigned syncFrame;    // corresponding frame no. to syncTime
189 
190       State state;
191 
192       AudioMsg* msg;
193       int fromThreadFdw, fromThreadFdr;  // message pipe
194 
195       int sigFd;              // pipe fd for messages to gui
196       int sigFdr;
197 
198       // record values:
199       Pos startRecordPos;
200       Pos endRecordPos;
201       unsigned startExternalRecTick;
202       unsigned endExternalRecTick;
203 
204       long m_Xruns;
205 
206       // Can be called by any thread.
207       void sendLocalOff();
208 
209       bool filterEvent(const MidiPlayEvent* event, int type, bool thru);
210 
211       void startRolling();
212       void abortRolling();
213       void stopRolling();
214 
215       void panic();
216       void processMsg(AudioMsg* msg);
217       void process1(unsigned samplePos, unsigned offset, unsigned samples);
218 
219       void collectEvents(MidiTrack*, unsigned int startTick, unsigned int endTick,
220                          unsigned int frames, unsigned int latency_offset);
221 
222       void seekMidi();
223 
224       // During sync(), starts count-in state if necessary and returns whether
225       //  count-in state has been started. Call from audio thread only.
226       bool startPreCount();
227       // In PRECOUNT state, processes the precount events.
228       // To be called by processMidi() in audio thread only.
229       void processPrecount(unsigned int frames);
230       // Updates the metronome tick. Useful for after seek(), even startRolling() etc.
231       // Call from audio thread only.
232       void updateMidiClick();
233       // Process midi for a number of frames. Call from audio thread only.
234       // Note that nextTickPos (and friends) will already be set before calling.
235       void processMidi(unsigned int frames);
236       void processMidiMetronome(unsigned int frames);
237       void processAudioMetronome(unsigned int frames);
238 
239    public:
240       Audio();
241       virtual ~Audio();
242 
243       // Access to message pipe (like from gui namespace), otherwise audio would need to depend on gui.
getFromThreadFdw()244       int getFromThreadFdw() { return sigFd; }
getFromThreadFdr()245       int getFromThreadFdr() { return sigFdr; }
246 
247       void process(unsigned frames);
248       bool sync(int state, unsigned frame);
249       // Called whenever the audio needs to re-sync, such as after any tempo changes.
250       // To be called from audio thread only.
251       void reSyncAudio();
252       void shutdown();
253       void writeTick();
254 
255       // transport:
256       // To be called from audio thread only.
257       bool start();
258       void stop(bool);
259       void seek(const Pos& pos);
260 
isStarting()261       bool isStarting() const   { return state == START_PLAY; }
isPlaying()262       bool isPlaying() const    { return state == PLAY || state == LOOP1 || state == LOOP2; }
isRecording()263       bool isRecording() const  { return state == PLAY && recording; }
setRunning(bool val)264       void setRunning(bool val) { _running = val; }
isRunning()265       bool isRunning() const    { return _running; }
isIdle()266       bool isIdle() const { return idle; }
267 
268       //-----------------------------------------
269       //   message interface
270       //-----------------------------------------
271 
272       void msgSeek(const Pos&);
273       void msgPlay(bool val);
274       // For starting the transport in external sync mode.
275       // Starts the transport immediately, bypassing waiting for transport sync,
276       //  although sync is still handled.
277       void msgExternalPlay(bool val, bool doRewind = false);
278 
279       void msgExecuteOperationGroup(Undo&); // calls exe1, then calls exe2 in audio context, then calls exe3
280       void msgRevertOperationGroup(Undo&); // similar.
281       // Bypass the Undo system and directly execute the pending operations.
282       // Do a song update with accumulated flags and extra_flags, if doUpdate is true.
283       void msgExecutePendingOperations(PendingOperationList& operations, bool doUpdate = false, SongChangedStruct_t extraFlags = 0);
284 
285       void msgRemoveTracks();
286       void msgUpdateSoloStates();
287       void msgSetAux(AudioTrack*, int, double);
288       void msgPanic();
289       void sendMsg(AudioMsg*);
290       bool sendMessage(AudioMsg* m, bool doUndo);
291       void msgRemoveRoute(Route, Route);
292       void msgRemoveRoute1(Route, Route);
293       void msgAddRoute(Route, Route);
294       void msgAddRoute1(Route, Route);
295       void msgAddPlugin(AudioTrack*, int idx, PluginI* plugin);
296       void msgSetPrefader(AudioTrack*, int);
297       void msgSetChannels(AudioTrack*, int);
298       void msgLocalOff();
299       void msgInitMidiDevices(bool force = true);
300       void msgResetMidiDevices();
301       void msgIdle(bool);
302       void msgAudioWait();
303       void msgBounce();
304       void msgSwapControllerIDX(AudioTrack*, int, int);
305       void msgClearControllerEvents(AudioTrack*, int);
306       void msgSeekPrevACEvent(AudioTrack*, int);
307       void msgSeekNextACEvent(AudioTrack*, int);
308       void msgEraseRangeACEvents(AudioTrack* node, int acid, unsigned int frame1, unsigned int frame2);
309       void msgChangeACEvent(AudioTrack* node, int acid, int frame, int newFrame, double val);
310       void msgSetHwCtrlState(MidiPort*, int, int, int);
311       void msgSetHwCtrlStates(MidiPort*, int, int, int, int);
312       void msgSetTrackAutomationType(Track*, int);
313       void msgSetSendMetronome(AudioTrack*, bool);
314       void msgStartMidiLearn();
315       void msgPlayMidiEvent(const MidiPlayEvent* event);
316       // If instrument is given it will be set, otherwise it won't touch the existing instrument.
317       void msgSetMidiDevice(MidiPort* port, MidiDevice* device, MidiInstrument* instrument = nullptr);
318 
319       void midiPortsChanged();
320 
pos()321       const Pos& pos() const { return _pos; }
322       // Number of frames in the current process cycle.
curCycleFrames()323       unsigned curCycleFrames() const { return _curCycleFrames; }
getStartRecordPos()324       const Pos& getStartRecordPos() const { return startRecordPos; }
getEndRecordPos()325       const Pos& getEndRecordPos() const { return endRecordPos; }
getStartExternalRecTick()326       unsigned getStartExternalRecTick() const { return startExternalRecTick; }
getEndExternalRecTick()327       unsigned getEndExternalRecTick() const { return endExternalRecTick; }
loopCount()328       int loopCount() { return _loopCount; }         // Number of times we have looped so far
loopFrame()329       unsigned loopFrame() { return _loopFrame; }
330 
tickPos()331       unsigned tickPos() const    { return curTickPos; }
nextTick()332       unsigned nextTick() const   { return nextTickPos; }
333       // Extrapolates current play frame on syncTime/syncFrame
334       // Estimated to single-frame resolution.
335       // This is an always-increasing number. Good for timestamps, and
336       //  handling them during process when referenced to syncFrame.
337       // This is meant to be called from threads other than the process thread.
338       unsigned curFrame() const;
339       // Current play position frame. Estimated to single-frame resolution while in play mode.
340       // This can be called from outside process thread.
341       unsigned curFramePos() const;
342       // This is meant to be called from inside process thread only.
343       unsigned framesAtCycleStart() const;
344       // Same as framesAtCycleStart(), but can be called from outside process thread.
curSyncFrame()345       unsigned curSyncFrame() const { return syncFrame; }
346       // This can be called from outside process thread.
347       unsigned framesSinceCycleStart() const;
348       // Convert tick to frame using the external clock history list.
349       // The function takes a tick relative to zero (ie. relative to the first event in a processing batch).
350       // The returned clock frames occurred during the previous audio cycle(s), so you may want to shift
351       //  the frames forward by one audio segment size for scheduling purposes.
352       // CAUTION: There must be at least one valid clock in the history, otherwise it returns zero.
353       //          Don't feed this a tick greater than or equal to the next tick, it will simply return the
354       //           very last frame, which is not very useful since that will just bunch the events
355       //           together at the last frame.
356       unsigned int extClockHistoryTick2Frame(unsigned int tick) const;
357       unsigned int extClockHistoryFrame2Tick(unsigned int frame) const;
358       void recordStop(bool restart = false, Undo* operations = NULL);
freewheel()359       bool freewheel() const       { return _freewheel; }
360       void setFreewheel(bool val);
361       void initDevices(bool force = true);
362 
363       void sendMsgToGui(char c);
bounce()364       bool bounce() const { return _bounceState == BounceStart || _bounceState == BounceOn; }
365 
getXruns()366       long getXruns() { return m_Xruns; }
resetXruns()367       void resetXruns() { m_Xruns = 0; }
incXruns()368       void incXruns() { m_Xruns++; }
369 
370       };
371 
372 extern int processAudio(unsigned long, void*);
373 extern void processAudio1(void*, void*);
374 
375 } // namespace MusECore
376 
377 namespace MusEGlobal {
378 extern MusECore::Audio* audio;
379 extern MusECore::AudioDevice* audioDevice;   // current audio device in use
380 }
381 
382 #endif
383 
384