1 //=========================================================
2 //  MusE
3 //  Linux Music Editor
4 //  $Id: track.h,v 1.39.2.17 2009/12/20 05:00:35 terminator356 Exp $
5 //
6 //  (C) Copyright 1999-2004 Werner Schweer (ws@seh.de)
7 //  (C) Copyright 2011-2013, 2016 Tim E. Real (terminator356 on sourceforge)
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 __TRACK_H__
26 #define __TRACK_H__
27 
28 #include <QString>
29 #include <QPixmap>
30 #include <QColor>
31 
32 #include <vector>
33 #include <algorithm>
34 
35 #include "wave.h" // for SndFileR
36 #include "part.h"
37 #include "mpevent.h"
38 #include "key.h"
39 #include "audio_fifo.h"
40 #include "route.h"
41 #include "ctrl.h"
42 #include "globaldefs.h"
43 #include "cleftypes.h"
44 #include "controlfifo.h"
45 #include "latency_info.h"
46 #include "transport_obj.h"
47 #include "plugin.h"
48 #include "latency_compensator.h"
49 
50 
51 // Forward declarations:
52 namespace MusECore {
53 class Pipeline;
54 class PluginI;
55 class MidiPort;
56 class Xml;
57 struct DrumMap;
58 class WorkingDrumMapList;
59 class WorkingDrumMapPatchList;
60 class LatencyCompensator;
61 
62 typedef std::vector<double> AuxSendValueList;
63 typedef std::vector<double>::iterator iAuxSendValue;
64 
65 //---------------------------------------------------------
66 //   Track
67 //---------------------------------------------------------
68 
69 class Track {
70    public:
71       enum TrackType {
72          MIDI=0, DRUM, WAVE, AUDIO_OUTPUT, AUDIO_INPUT, AUDIO_GROUP,
73          AUDIO_AUX, AUDIO_SOFTSYNTH
74          };
75       // NOTE: ASSIGN_DUPLICATE_PARTS ASSIGN_COPY_PARTS and ASSIGN_CLONE_PARTS are not allowed together - choose one.
76       // (Safe, but it will choose one action over the other.)
77       enum AssignFlags {
78          ASSIGN_NONE=0,
79          ASSIGN_PROPERTIES=1,
80          ASSIGN_DUPLICATE_PARTS=2, ASSIGN_COPY_PARTS=4, ASSIGN_CLONE_PARTS=8,
81          ASSIGN_PLUGINS=16,
82          ASSIGN_STD_CTRLS=32, ASSIGN_PLUGIN_CTRLS=64,
83          ASSIGN_ROUTES=128, ASSIGN_DEFAULT_ROUTES=256,
84          ASSIGN_DRUMLIST=512 };
85 
86    private:
87       TrackType _type;
88       // Serial number generator.
89       static int _snGen;
90       QString _comment;
91       PartList _parts;
92       QColor m_color;
93 
94       void init(int channels = 0);
95       void internal_assign(const Track&, int flags);
96 
97    protected:
98       static unsigned int _soloRefCnt;
99       static Track* _tmpSoloChainTrack;
100       static bool _tmpSoloChainDoIns;
101       static bool _tmpSoloChainNoDec;
102 
103       // Every time a track is selected, the track's _selectionOrder is set to this value,
104       //  and then this value is incremented. The value is reset to zero occasionally,
105       //  for example whenever Song::selectAllTracks(false) is called.
106       static int _selectionOrderCounter;
107 
108       RouteList _inRoutes;
109       RouteList _outRoutes;
110       bool _nodeTraversed;   // Internal anti circular route traversal flag.
111       int _auxRouteCount;    // Number of aux paths feeding this track.
112 
113       // Serial number.
114       int _sn;
115       QString _name;
116       bool _recordFlag;
117       bool _recMonitor;       // For midi and audio. Whether to pass the input through to output.
118       bool _mute;
119       bool _solo;
120       unsigned int _internalSolo;
121       bool _off;
122       int _channels;          // 1 - mono, 2 - stereo
123 
124       int _activity;
125       int _lastActivity;
126       double _meter[MusECore::MAX_CHANNELS];
127       double _peak[MusECore::MAX_CHANNELS];
128       bool _isClipped[MusECore::MAX_CHANNELS]; //used in audio mixer strip. Persistent.
129 
130       int _y;
131       int _height;            // visual height in arranger
132 
133       bool _locked;
134       bool _selected;
135       // The selection order of this track, compared to other selected tracks.
136       // The selected track with the highest selected order is the most recent selected.
137       int _selectionOrder;
138 
139       // Holds latency computations each cycle.
140       TrackLatencyInfo _latencyInfo;
141 
142       // Holds a special extra 'source': The transport stream.
143       // Tracks or plugins that request/receive transport info use this.
144       TransportSource _transportSource;
145 
newSn()146       int newSn() { return _snGen++; }
147 
148       bool readProperties(Xml& xml, const QString& tag);
149       void writeProperties(int level, Xml& xml) const;
150 
151    public:
152       Track(TrackType, int channels = 0);
153       // Copy constructor.
154       // The various AssignFlags (flags) determine what is copied.
155       // For now, the new track's name is set to the original name.
156       // The caller SHOULD set a proper unique name afterwards,
157       //  otherwise identical track names will appear in the song.
158       // It is possible for us to automatically to choose a unique name
159       //  here, but that may not be wise in some cases (such as modifying a
160       //  track copy and then requesting the operations system switch tracks -
161       //  in that case we want the names to be the same).
162       // Also, it is possible the name choosing routine(s) may fail for
163       //  whatever reason, and we cannot abort creation here.
164       // For that reason, it is best for the caller to try and pick a
165       //  unique name successfully BEFORE calling this constructor.
166       Track(const Track&, int flags);
167       virtual ~Track();
168       virtual void assign(const Track&, int flags);
169 
serial()170       inline int serial() const { return _sn; }
171 
172       static const char* _cname[];
173       static QIcon *trackTypeIcon(TrackType);
174       static QColor trackTypeColor(TrackType);
175       static QColor trackTypeLabelColor(TrackType);
icon()176       QIcon* icon() const { return trackTypeIcon(type()); }
color()177       QColor color() const { return m_color.isValid() ? m_color : trackTypeColor(type()); }
setColor(const QColor c)178       void setColor(const QColor c) { m_color = c; }
resetColor()179       void resetColor() { m_color = QColor(); }
labelColor()180       QColor labelColor() const { return trackTypeLabelColor(type()); }
181 
comment()182       QString comment() const         { return _comment; }
setComment(const QString & s)183       void setComment(const QString& s) { _comment = s; }
184 
185       int y() const;
setY(int n)186       void setY(int n)                { _y = n;         }
187       virtual int height() const = 0;
setHeight(int n)188       void setHeight(int n)           { _height = n;    }
189 
selected()190       bool selected() const           { return _selected; }
191       // Try to always call this instead of setting _selected, because it also sets _selectionOrder.
192       void setSelected(bool f);
193       // The order of selection of this track, compared to other selected tracks.
194       // The selected track with the highest selected order is the most recent selected.
selectionOrder()195       int selectionOrder() const       { return _selectionOrder; }
196       // Resets the static selection counter. Optional. (Range is huge, unlikely would have to call).
197       // Called for example whenever Song::selectAllTracks(false) is called.
clearSelectionOrderCounter()198       static void clearSelectionOrderCounter(){ _selectionOrderCounter = 0; }
199 
locked()200       bool locked() const             { return _locked; }
setLocked(bool b)201       void setLocked(bool b)          { _locked = b; }
202 
203       void clearRecAutomation(bool clearList);
204 
name()205       const QString& name() const     { return _name; }
206       // setName can be overloaded to do other things like setting port names, while setNameText just sets the text.
setName(const QString & s)207       virtual void setName(const QString& s)  { _name = s; }
208       // setNameText just sets the text, while setName can be overloaded to do other things like setting port names.
setNameText(const QString & s)209       void setNameText(const QString& s)  { _name = s; }
210       // Returns a name suitable for display like "1:Track 5" where the number is the track's index in the track list.
211       // This is useful because in the case of importing a midi file we allow duplicate, often blank, names.
212       // This display string will help identify them. Like "1:", "2:" etc.
213       QString displayName() const;
214 
type()215       TrackType type() const          { return _type; }
setType(TrackType t)216       void setType(TrackType t)       { _type = t; }
cname()217       QString cname() const           { int t = type(); return QString(_cname[t]); }
218 
219       // routing
inRoutes()220       RouteList* inRoutes()    { return &_inRoutes; }
outRoutes()221       RouteList* outRoutes()   { return &_outRoutes; }
inRoutes()222       const RouteList* inRoutes() const { return &_inRoutes; }
outRoutes()223       const RouteList* outRoutes() const { return &_outRoutes; }
noInRoute()224       virtual bool noInRoute() const   { return _inRoutes.empty();  }
noOutRoute()225       virtual bool noOutRoute() const  { return _outRoutes.empty(); }
226       void writeRouting(int, Xml&) const;
227       bool isCircularRoute(Track* dst);
auxRefCount()228       int auxRefCount() const { return _auxRouteCount; }  // Number of Aux Tracks with routing paths to this track.
229       void updateAuxRoute(int refInc, Track* dst);  // Internal use.
230       // Number of routable inputs/outputs for each Route::RouteType.
231       virtual RouteCapabilitiesStruct routeCapabilities() const;
232 
parts()233       PartList* parts()               { return &_parts; }
cparts()234       const PartList* cparts() const  { return &_parts; }
235       Part* findPart(unsigned tick);
236       iPart addPart(Part* p);
237 
238       // Select or unselect a range of events. If t0 == t1, ALL events will be affected.
239       // The t0 and t1 can be ticks or frames depending on the type of events. Unused for now.
240       // Returns true if anything changed.
241       bool selectEvents(bool select, unsigned long t0 = 0, unsigned long t1 = 0);
242 
243       virtual void write(int, Xml&) const = 0;
244 
245       virtual Track* clone(int flags) const    = 0;
246       // Returns true if any event in any part was opened. Does not operate on the part's clones, if any.
openAllParts()247       virtual bool openAllParts() { return false; };
248       // Returns true if any event in any part was closed. Does not operate on the part's clones, if any.
closeAllParts()249       virtual bool closeAllParts() { return false; };
250 
251       // Called from gui thread only.
252       virtual bool setRecordFlag1(bool) = 0;
253       // Called from audio thread only.
254       virtual void setRecordFlag2(bool) = 0;
255       // Same as setRecordFlag2 except it can automatically set the monitor flag
256       //  depending on the global config.monitorOnRecord. Called from audio thread only.
257       // Returns whether the monitor was changed.
258       virtual bool setRecordFlag2AndCheckMonitor(bool r) = 0;
259 
260       virtual Part* newPart(Part*p=0, bool clone = false) = 0;
261       void dump() const;
262 
setMute(bool val)263       virtual void setMute(bool val) { _mute = val; }
setOff(bool val)264       virtual void setOff(bool val) { _off = val; }
265       void setInternalSolo(unsigned int val);
266       virtual void setSolo(bool val) = 0;
267 
268       // Returns true if playback ultimately is muted, depending on
269       //  other factors such as soloing.
isMute()270       virtual bool isMute() const {
271         if(_solo || (_internalSolo && !_mute))
272           return false;
273         if(_soloRefCnt)
274           return true;
275         return _mute;
276       }
277       // Returns true if playback ultimately is monitored, depending on
278       //  other factors such as soloing.
isRecMonitored()279       virtual bool isRecMonitored() const {
280         if(_off || !_recMonitor)
281           return false;
282         if(_solo || _internalSolo)
283           return true;
284         return _soloRefCnt == 0;
285       }
286       // Returns true (>= 1) if proxy-soloed.
internalSolo()287       virtual unsigned int internalSolo() const  { return _internalSolo; }
288       // Returns true if proxy-muted.
soloMode()289       virtual bool soloMode() const      { return _soloRefCnt; }
290       // Returns true if soloed.
solo()291       virtual bool solo() const          { return _solo;         }
292       // Returns true if muted.
mute()293       virtual bool mute() const          { return _mute;         }
294       // Returns true if track is off.
off()295       virtual bool off() const           { return _off;          }
296       // Returns true if rec-armed.
recordFlag()297       virtual bool recordFlag() const    { return _recordFlag;   }
298       // Sets monitor.
setRecMonitor(bool b)299       virtual void setRecMonitor(bool b) { if(canRecordMonitor()) _recMonitor = b; }
300       // Returns true if monitored.
recMonitor()301       virtual bool recMonitor() const    { return _recMonitor; }
302 
preProcessAlways()303       virtual void preProcessAlways()    { }
304 
transportSource()305       TransportSource& transportSource() { return _transportSource; }
306 //       // Returns true if the transport source is connected to any of the
307 //       //  track's midi input ports (ex. synth ports not muse midi ports).
308 //       // If midiport is -1, returns true if ANY port is connected.
309 //       virtual bool transportSourceConnected(int /*midiport*/ = -1) const { return false; }
310       // Returns true if the transport source is connected to any of the
311       //  track's midi input ports (ex. synth ports not muse midi ports).
usesTransportSource()312       virtual bool usesTransportSource() const { return false; }
transportAffectsAudioLatency()313       virtual bool transportAffectsAudioLatency() const { return false; }
314 
315       // Initializes this track's latency information in preparation for a latency scan.
316       virtual void prepareLatencyScan();
317       // The contribution to latency from the track's own members (audio effect rack, etc).
selfLatencyAudio(int)318       inline virtual float selfLatencyAudio(int /*channel*/) const { return 0.0f; }
319       // The cached worst latency of all the channels in the track's effect rack plus any synthesizer latency if applicable.
320       virtual float getWorstPluginLatencyAudio();
321       // The cached worst contribution to latency by any ports (for ex. Jack ports of audio input/output tracks).
322       virtual float getWorstPortLatencyAudio();
323       // The cached worst latency of all the contributions from the track's own members (audio effect rack, etc)
324       //  plus any port latency if applicable.
325       virtual float getWorstSelfLatencyAudio();
326       // Whether this track (and the branch it is in) can force other parallel branches to
327       //  increase their latency compensation to match this one.
328       // If false, this branch will NOT disturb other parallel branches' compensation,
329       //  intead only allowing compensation UP TO the worst case in other branches.
330       virtual bool canDominateOutputLatency() const;
331       virtual bool canDominateInputLatency() const;
332       // Whether this track (and the branch it is in) can force other parallel branches to
333       //  increase their latency compensation to match this one - IF this track is an end-point
334       //  and the branch allows domination.
335       // If false, this branch will NOT disturb other parallel branches' compensation,
336       //  intead only allowing compensation UP TO the worst case in other branches.
canDominateEndPointLatency()337       inline virtual bool canDominateEndPointLatency() const { return false; }
338       // Whether this track and its branch can correct for latency, not just compensate.
canCorrectOutputLatency()339       inline virtual bool canCorrectOutputLatency() const { return false; }
340       // Whether the track can pass latency values through, the SAME as if record monitor is
341       //  supported and on BUT does not require record monitor support.
342       // This is for example in the metronome MetronomeSynthI, since it is unique in that it
343       //  can correct its own latency unlike other synths, but it does not 'pass through'
344       //  the latency values to what drives it like other synths.
345       virtual bool canPassThruLatency() const;
346       // Whether any of the connected output routes are effectively connected.
347       // That means track is not off, track is monitored where applicable, etc,
348       //   ie. signal can actually flow.
349       // For Wave Tracks for example, asks whether the track is an end-point from the view of the input side.
350       virtual bool isLatencyInputTerminal() = 0;
351       // Whether any of the connected output routes are effectively connected.
352       // That means track is not off, track is monitored where applicable, etc,
353       //   ie. signal can actually flow.
354       // For Wave Tracks for example, asks whether the track is an end-point from the view of the playback side.
355       virtual bool isLatencyOutputTerminal() = 0;
356 
357       virtual TrackLatencyInfo& getDominanceInfo(bool input) = 0;
358       virtual TrackLatencyInfo& getDominanceLatencyInfo(bool input) = 0;
359       // The finalWorstLatency is the grand final worst-case latency, of any output track or open branch,
360       //  determined in the complete getDominanceLatencyInfo() scan.
361       // The callerBranchLatency is the inherent branch latency of the calling track, or zero if calling from
362       //  the very top outside of the branch heads (outside of output tracks or open branches).
363       // The callerBranchLatency is accumulated as setCorrectionLatencyInfo() is called on each track
364       //  in a branch of the graph.
365       virtual TrackLatencyInfo& setCorrectionLatencyInfo(bool input, float finalWorstLatency, float callerBranchLatency = 0.0f) = 0;
366       // Argument 'input': Whether we want the input side of the track. For example un-monitored wave tracks
367       //  are considered two separate paths with a recording input side and a playback output side.
368       virtual TrackLatencyInfo& getLatencyInfo(bool input) = 0;
369       // Used during latency compensation processing. When analyzing in 'reverse' this mechansim is
370       //  needed only to equalize the timing of all the AudioOutput tracks.
371       // It is applied as a direct offset in the latency delay compensator in getData().
latencyCompWriteOffset()372       virtual unsigned long latencyCompWriteOffset() const { return _latencyInfo._compensatorWriteOffset; }
setLatencyCompWriteOffset(float)373       virtual void setLatencyCompWriteOffset(float /*worstCase*/) { }
374 
375       // Internal use...
376       static void clearSoloRefCounts();
377       void updateSoloState();
378       virtual void updateSoloStates(bool noDec) = 0;
379       virtual void updateInternalSoloStates();
380 
activity()381       int activity()                     { return _activity;     }
setActivity(int v)382       void setActivity(int v)            { _activity = v;        }
lastActivity()383       int lastActivity()                 { return _lastActivity; }
setLastActivity(int v)384       void setLastActivity(int v)        { _lastActivity = v;    }
addActivity(int v)385       void addActivity(int v)            { _activity += v;       }
386       void resetPeaks();
387       static void resetAllMeter();
meter(int ch)388       double meter(int ch) const  { return _meter[ch]; }
peak(int ch)389       double peak(int ch) const   { return _peak[ch]; }
390       void resetMeter();
391 
392       bool readProperty(Xml& xml, const QString& tag);
channels()393       int channels() const                { return _channels; }
394       virtual void setChannels(int n);
isMidiTrack()395       bool isMidiTrack() const       { return type() == MIDI || type() == DRUM; }
isDrumTrack()396       bool isDrumTrack() const       { return type() == DRUM; }
isSynthTrack()397       bool isSynthTrack() const      { return type() == AUDIO_SOFTSYNTH; }
canRecord()398       virtual bool canRecord() const { return false; }
canRecordMonitor()399       virtual bool canRecordMonitor() const { return false; }
400       virtual AutomationType automationType() const    = 0;
401       virtual void setAutomationType(AutomationType t) = 0;
setVisible(bool)402       static void setVisible(bool) { }
403       bool isVisible();
isClipped(int ch)404       inline bool isClipped(int ch) const { if(ch >= MusECore::MAX_CHANNELS) return false; return _isClipped[ch]; }
resetClipper()405       void resetClipper() { for(int ch = 0; ch < MusECore::MAX_CHANNELS; ++ch) _isClipped[ch] = false; }
406       };
407 
408 //---------------------------------------------------------
409 //   MidiTrack
410 //---------------------------------------------------------
411 
412 class MidiTrack : public Track {
413       int _outPort;
414       int _outChannel;
415 
416    private:
417       static bool _isVisible;
418       clefTypes clefType;
419 
420       DrumMap* _drummap; // _drummap[foo].anote is always equal to foo
421 
422       // A list of user-altered drum map items.
423       WorkingDrumMapPatchList* _workingDrumMapPatchList;
424 
425       bool _drummap_ordering_tied_to_patch; //if true, changing patch also changes drummap-ordering
426       int drum_in_map[128];
427       int _curDrumPatchNumber; // Can be CTRL_VAL_UNKNOWN.
428 
429       void init();
430       void internal_assign(const Track&, int flags);
431       void init_drummap(bool write_ordering); // function without argument in public
432       void remove_ourselves_from_drum_ordering();
433 
434       void writeOurDrumSettings(int level, Xml& xml) const;
435       void readOurDrumSettings(Xml& xml);
436 
437    public:
438       EventList events;           // tmp Events during midi import
439       MPEventList mpevents;       // tmp Events druring recording
440       MPEventList stuckLiveNotes; // Live (rec): Currently sounding note-ons that we don't know the note-off time yet. Event times = 0.
441       MPEventList stuckNotes;     // Playback: Currently sounding note-ons contributed by track - not sent directly to device
442 
443       MidiTrack();
444       MidiTrack(const MidiTrack&, int flags);
445       virtual ~MidiTrack();
446 
447       // FIXME This public assign() method doesn't really 'assign' routes -
448       //        if routes are assigned in flags, it does not clear existing routes !
449       virtual void assign(const Track&, int flags);
450       virtual void convertToType(TrackType trackType);
451 
452       virtual AutomationType automationType() const;
453       virtual void setAutomationType(AutomationType);
454 
455       // play parameter
456       int transposition;
457       int velocity;
458       int delay;
459       int len;
460       int compression;
461 
462       // Called from gui thread only.
setRecordFlag1(bool)463       virtual bool setRecordFlag1(bool) { return canRecord(); }
464       // Called from audio thread only.
setRecordFlag2(bool f)465       virtual void setRecordFlag2(bool f) { if(canRecord()) _recordFlag = f; }
466       // Same as setRecordFlag2 except it can automatically set the monitor flag
467       //  depending on the global config.monitorOnRecord. Called from audio thread only.
468       // Returns whether the monitor was changed.
469       virtual bool setRecordFlag2AndCheckMonitor(bool);
470 
471       virtual void read(Xml&);
472       virtual void write(int, Xml&) const;
473 
474       virtual int height() const;
475 
clone(int flags)476       virtual MidiTrack* clone(int flags) const { return new MidiTrack(*this, flags); }
477       virtual Part* newPart(Part*p=0, bool clone=false);
478 
479       // Number of routable inputs/outputs for each Route::RouteType.
480       virtual RouteCapabilitiesStruct routeCapabilities() const;
481 
482       virtual bool canDominateOutputLatency() const;
483       virtual bool canCorrectOutputLatency() const;
484       virtual bool isLatencyInputTerminal();
485       virtual bool isLatencyOutputTerminal();
486 
487       virtual TrackLatencyInfo& getDominanceLatencyInfo(bool input);
488       virtual TrackLatencyInfo& getDominanceInfo(bool input);
489       // The finalWorstLatency is the grand final worst-case latency, of any output track or open branch,
490       //  determined in the complete getDominanceLatencyInfo() scan.
491       // The callerBranchLatency is the inherent branch latency of the calling track, or zero if calling from
492       //  the very top outside of the branch heads (outside of output tracks or open branches).
493       // The callerBranchLatency is accumulated as setCorrectionLatencyInfo() is called on each track
494       //  in a branch of the graph.
495       virtual TrackLatencyInfo& setCorrectionLatencyInfo(bool input, float finalWorstLatency, float callerBranchLatency = 0.0f);
496       virtual TrackLatencyInfo& getLatencyInfo(bool input);
497       // Used during latency compensation processing. When analyzing in 'reverse' this mechansim is
498       //  needed only to equalize the timing of all the AudioOutput tracks.
499       // It is applied as a direct offset in the latency delay compensator in getData().
500       virtual void setLatencyCompWriteOffset(float worstCase);
501 
502       // This enum describes what has changed in the following port/channel methods.
503       enum ChangedType { NothingChanged = 0x0, PortChanged = 0x1, ChannelChanged = 0x2, DrumMapChanged = 0x4 };
504       // OR'd ChangedType flags.
505       typedef int ChangedType_t;
506       // Sets the output port, and for a drum track updates any drum map. Returns true if anything changed.
507       // If doSignal is true, automatically emits SC_DRUM_MAP or sends audio message if audio is running and not idle.
508       ChangedType_t setOutPort(int i, bool doSignal = false);
509       // Sets the output channel, and for a drum track updates any drum map. Returns true if anything changed.
510       // If doSignal is true, automatically emits SC_DRUM_MAP or sends audio message if audio is running and not idle.
511       ChangedType_t setOutChannel(int i, bool doSignal = false);
512       // Same as setOutPort, but also transfers controller data to the new selected port.
513       ChangedType_t setOutPortAndUpdate(int port, bool doSignal = false);
514       // Same as setOutChannel, but also transfers controller data to the new selected channel.
515       ChangedType_t setOutChanAndUpdate(int chan, bool doSignal = false);
516       // Combines both setOutChannel and setOutPort operations, and transfers controller data to the new selected port/channel.
517       ChangedType_t setOutPortAndChannelAndUpdate(int port, int chan, bool doSignal = false);
518 
519       // Backward compatibility: For reading old songs.
520       void setInPortAndChannelMask(unsigned int portmask, int chanmask);
521 
522       // Overridden for special midi output behaviour.
523       virtual bool noOutRoute() const;
524 
outPort()525       int outPort() const             { return _outPort;     }
outChannel()526       int outChannel() const          { return _outChannel;  }
527 
528       // Given ctrl, if ctrl is a drum (per-note) controller, fills the other parameters with the
529       //  mapped track ctrl, port, and channel from the drum map, and returns true.
530       // If ctrl is not a drum controller, port and channel are filled with the track's
531       //  port and channel (same as outPort() and outChannel()), and ctrl is not changed, and returns false.
532       // Port, mport, and channel can be null. Ctrl is the fully qualified number if any (low byte is note)
533       //  and if ctrl is a drum controller ctrl is filled the note mapped to the drum map 'anote'.
534       bool mappedPortChanCtrl(int *ctrl, int *port, MidiPort** mport, int *channel) const;
535 
536       virtual void setSolo(bool val);
537       virtual void updateSoloStates(bool noDec);
538       virtual void updateInternalSoloStates();
539 
540       virtual bool addStuckNote(const MidiPlayEvent& ev);
541       // These are only for 'live' (rec) notes for which we don't have a note-off time yet. Even times = 0.
542       virtual bool addStuckLiveNote(int port, int chan, int note, int vel = 64);
543       virtual bool removeStuckLiveNote(int port, int chan, int note);
544       virtual bool stuckLiveNoteExists(int port, int chan, int note);
545 
canRecord()546       virtual bool canRecord() const  { return true; }
canRecordMonitor()547       virtual bool canRecordMonitor() const { return true; }
setVisible(bool t)548       static void setVisible(bool t) { _isVisible = t; }
visible()549       static bool visible() { return _isVisible; }
550 
551       int getFirstControllerValue(int ctrl, int def=-1);
552       int getControllerChangeAtTick(unsigned tick, int ctrl, int def=-1);
553       unsigned getControllerValueLifetime(unsigned tick, int ctrl); // returns the tick where this CC gets overridden by a new one
554                                                                     // returns UINT_MAX for "never"
555 
setClef(clefTypes i)556       void setClef(clefTypes i) { clefType = i; }
getClef()557       clefTypes getClef() { return clefType; }
558 
drummap()559       DrumMap* drummap() { return _drummap; }
drummap()560       const DrumMap* drummap() const { return _drummap; }
map_drum_in(int enote)561       int map_drum_in(int enote) { return drum_in_map[enote]; }
562       void update_drum_in_map();
563       void init_drum_ordering();
564 
init_drummap()565       void init_drummap() { init_drummap(false); } // function with argument in private
566 
567       // For drum tracks, updates the drum map and returns true if anything changed.
568       // If doSignal is true, automatically emits SC_DRUM_MAP or sends audio message if audio is running and not idle.
569       bool updateDrummap(int doSignal);
570       //void workingDrumMapOperation(int index, bool updateDruminmap, const WorkingDrumMapEntry& item, PendingOperationList& ops);
workingDrumMap()571       WorkingDrumMapPatchList* workingDrumMap() const { return _workingDrumMapPatchList; }
572       void setWorkingDrumMap(WorkingDrumMapPatchList* list, bool isInstrumentMod);
573       void modifyWorkingDrumMap(WorkingDrumMapList& list, bool isReset, bool includeDefault, bool isInstrumentMod, bool doWholeMap);
574       //void modifyWorkingDrumMap(WorkingDrumMapPatchList& list, bool clear, bool isReset, bool isInstrumentMod);
575       // Returns a map item with members filled from either the original or working map item,
576       //  depending on which Field flags are set. The returned map includes any requested
577       //  WorkingDrumMapEntry::OverrideType track or instrument overrides.
578       void getMapItem(int patch, int index, DrumMap& dest_map, int overrideType) const;
579       // Returns a map item with members filled from either the original or working map item,
580       //  depending on which Field flags are set. The returned map includes any requested
581       //  WorkingDrumMapEntry::OverrideType track or instrument overrides.
582       // Same as getMapItem(), but determines patch at supplied tick.
583       void getMapItemAt(int tick, int index, DrumMap& dest_map, int overrideType) const;
584       // Returns OR'd WorkingDrumMapEntry::OverrideType flags indicating whether a map item's members,
585       //  given by 'fields' (OR'd WorkingDrumMapEntry::Fields), are either the original or working map item.
586       // Here in MidiTrack the flags can be NoOverride, InstrumentOverride, and TrackOverride. See corresponding
587       //  function in MidiInstrument. If patch is -1 it uses the track's current patch (midi controller hwCtrlVal).
588       int isWorkingMapItem(int index, int fields, int patch = -1) const;
589 
590       // Ensures there are NO duplicate enote fields in the final drum map array.
591       // Returns true if anything changed.
592       bool normalizeDrumMap();
593       // Ensures there are NO duplicate enote fields in the final drum map array for the given patch.
594       // Returns true if anything changed.
595       bool normalizeDrumMap(int patch);
596 
597       void set_drummap_ordering_tied_to_patch(bool);
drummap_ordering_tied_to_patch()598       bool drummap_ordering_tied_to_patch() { return _drummap_ordering_tied_to_patch; }
599 
600       // Prints a handy debug table of drum map values and overrides etc.
601       void dumpMap();
602       };
603 
604 //---------------------------------------------------------
605 //   AudioTrack
606 //    this track can hold audio automation data and can
607 //    hold tracktypes WAVE, AUDIO_GROUP, AUDIO_OUTPUT,
608 //    AUDIO_INPUT, AUDIO_SOFTSYNTH, AUDIO_AUX
609 //---------------------------------------------------------
610 
611 class AudioTrack : public Track {
612       bool _haveData; // Whether we have data from a previous process call during current cycle.
613 
614       CtrlListList _controller;   // Holds all controllers including internal, plugin and synth.
615       ControlFifo _controlFifo;   // For internal controllers like volume and pan. Plugins/synths have their own.
616       CtrlRecList _recEvents;     // recorded automation events
617 
618       unsigned long _controlPorts;
619       Port* _controls;             // For internal controllers like volume and pan. Plugins/synths have their own.
620 
621       double _curVolume;
622       double _curVol1;
623       double _curVol2;
624 
625       bool _prefader;               // prefader metering
626       AuxSendValueList _auxSend;
627       void readAuxSend(Xml& xml);
628       int recFileNumber;
629 
630       bool _sendMetronome;
631       AutomationType _automationType;
632       double _gain;
633 
634       void initBuffers();
635       void internal_assign(const Track&, int flags);
636       void processTrackCtrls(unsigned pos, int trackChans, unsigned nframes, float** buffer);
637 
638    protected:
639       // Cached audio data for all channels. If prefader is not on, the first two channels
640       //  have volume and pan applied if track is stereo, or the first channel has just
641       //  volume applied if track is mono.
642       float** outBuffers;
643       // Extra cached audio data.
644       float** outBuffersExtraMix;
645       // Just all zeros all the time, so we don't have to clear for silence.
646       float*  audioInSilenceBuf;
647       // Just a place to connect all unused audio outputs.
648       float*  audioOutDummyBuf;
649       // Internal temporary buffers for getData().
650       float** _dataBuffers;
651       // Audio latency compensator.
652       LatencyCompensator* _latencyComp;
653 
654       // These two are not the same as the number of track channels which is always either 1 (mono) or 2 (stereo):
655       // Total number of output channels.
656       int _totalOutChannels;
657       // Total number of input channels.
658       int _totalInChannels;
659 
660       Pipeline* _efxPipe;
661 
662       virtual bool getData(unsigned, int, unsigned, float**);
663 
664       SndFileR _recFile;
665       // Exclusively for the recFile during bounce operations.
666       long int _recFilePos;
667       float _previousLatency;
668 
669       Fifo fifo;                    // fifo -> _recFile
670       bool _processed;
671 
672    public:
673       AudioTrack(TrackType t, int channels = 2);
674 
675       AudioTrack(const AudioTrack&, int flags);
676       virtual ~AudioTrack();
677 
678       // FIXME This public assign() method doesn't really 'assign' routes -
679       //        if routes are assigned in flags, it does not clear existing routes !
680       virtual void assign(const Track&, int flags);
681 
682       virtual AudioTrack* clone(int flags) const = 0;
683       virtual Part* newPart(Part*p=0, bool clone=false);
684 
685       // Called from gui thread only.
686       virtual bool setRecordFlag1(bool);
687       // Called from audio thread only.
688       virtual void setRecordFlag2(bool);
689       bool prepareRecording();
690       // Same as setRecordFlag2 except it can automatically set the monitor flag
691       //  depending on the global config.monitorOnRecord. Called from audio thread only.
692       // Returns whether the monitor was changed.
693       virtual bool setRecordFlag2AndCheckMonitor(bool);
694 
processed()695       bool processed() { return _processed; }
696 
697       void addController(CtrlList*);
698       void removeController(int id);
699       void swapControllerIDX(int idx1, int idx2);
700 
701       bool readProperties(Xml&, const QString&);
702       void writeProperties(int, Xml&) const;
703 
704       void mapRackPluginsToControllers();
705       void showPendingPluginNativeGuis();
706 
recFile()707       SndFileR recFile() const           { return _recFile; }
setRecFile(SndFileR sf)708       void setRecFile(SndFileR sf)       { _recFile = sf; }
709 
controller()710       CtrlListList* controller()         { return &_controller; }
711       // For setting/getting the _controls 'port' values.
parameters()712       unsigned long parameters() const { return _controlPorts; }
713 
714       void setParam(unsigned long i, double val);
715       double param(unsigned long i) const;
716 
717       virtual void setChannels(int n);
718       virtual void setTotalOutChannels(int num);
totalOutChannels()719       virtual int totalOutChannels() const { return _totalOutChannels; }
720       virtual void setTotalInChannels(int num);
totalInChannels()721       virtual int totalInChannels() const { return _totalInChannels; }
722       // Number of routable inputs/outputs for each Route::RouteType.
723       virtual RouteCapabilitiesStruct routeCapabilities() const;
724       // Number of required processing buffers.
totalProcessBuffers()725       virtual int totalProcessBuffers() const { return (channels() == 1) ? 1 : totalOutChannels(); }
726 
727       virtual void setSolo(bool val);
728       virtual void updateSoloStates(bool noDec);
729       virtual void updateInternalSoloStates();
730 
731       // Puts to the recording fifo.
732       // This also performs adjustments for latency compensation before putting to the fifo.
733       // Returns true on success.
734       bool putFifo(int channels, unsigned long n, float** bp);
735       // Transfers the recording fifo to _recFile.
736       void record();
737       // Returns the recording fifo current count.
recordFifoCount()738       int recordFifoCount() { return fifo.getCount(); }
739 
740       virtual void setMute(bool val);
741       virtual void setOff(bool val);
742 
setSendMetronome(bool val)743       void setSendMetronome(bool val) { _sendMetronome = val; }
sendMetronome()744       bool sendMetronome() const { return _sendMetronome; }
745 
746       double volume() const;
747       void setVolume(double val);
748       double pan() const;
749       void setPan(double val);
750       double gain() const;
751       void setGain(double val);
752 
prefader()753       bool prefader() const              { return _prefader; }
754       double auxSend(int idx) const;
755       void setAuxSend(int idx, double v);
756       void addAuxSend(int n);
757 
758       void setPrefader(bool val);
efxPipe()759       Pipeline* efxPipe()                { return _efxPipe;  }
760       void deleteAllEfxGuis();
761       void clearEfxList();
762       // Removes any existing plugin and inserts plugin into effects rack, and calls setupPlugin.
763       void addPlugin(PluginI* plugin, int idx);
764       // Assigns valid ID and track to plugin, and creates controllers for plugin.
765       void setupPlugin(PluginI* plugin, int idx);
766 
767       double pluginCtrlVal(int ctlID) const;
768       void setPluginCtrlVal(int param, double val);
769 
770       void readVolume(Xml& xml);
771 
772       virtual void preProcessAlways();
773 
774       // Gathers this track's audio data and either copies or adds it to a supplied destination buffer.
775       // If the per-channel 'addArray' is supplied, whether to copy or add each channel is given in the array,
776       //  otherwise it is given by the bulk 'add' flag.
777       // The range of buffers in 'dstBuffer' given by 'dstStartChan' and 'availDstChannels' are filled with data.
778       // If 'availDstChannels' is greater than 'requestedDstChannels', the excess buffers are filled with silence.
779       // If 'requestedDstChannels' is greater than 'availDstChannels', copyData() acts AS IF 'requestedDstChannels'
780       //  was the real availDstChannels except it only fills up to 'availDstChannels'. This is to allow copyData()
781       //  to mix properly even when some routes are not available (ex. switching a track from stereo to mono,
782       //  which has an existing one-channel route on the right channel).
783       // The 'srcStartChan' and 'srcChannels' give the range of channels to copy or add from this track.
784       // If 'srcStartChan' is -1 it will be set to zero. If 'srcChannels' is -1`it will be set to this track's output channels.
785       // The 'dstStartChan' can also be -1, but 'requestedDstChannels' and availDstChannels cannot.
786       virtual void copyData(unsigned samplePos,
787                             int dstStartChan, int requestedDstChannels, int availDstChannels,
788                             int srcStartChan, int srcChannels,
789                             unsigned frames, float** dstBuffer,
790                             bool add = false,
791                             const bool* addArray = 0);
792 
hasAuxSend()793       virtual bool hasAuxSend() const { return false; }
794 
795       // Whether to use latency correction/compensation at all.
796       // Simply depends on _latencyComp existence AND global configuration enableLatencyCorrection flag.
797       bool useLatencyCorrection() const;
798       // The contribution to latency by the track's own members (audio effect rack, etc).
799       virtual float selfLatencyAudio(int channel) const;
800       // The cached worst latency of all the channels in the track's effect rack.
801       virtual float getWorstPluginLatencyAudio();
802       // The cached worst latency of all the contributions from the track's own members (audio effect rack, etc)
803       //  plus any port latency if applicable.
804       virtual float getWorstSelfLatencyAudio();
805       virtual TrackLatencyInfo& getDominanceInfo(bool input);
806       // Returns latency computations during each cycle. If the computations have already been done
807       //  this cycle, cached values are returned, otherwise they are computed, cached, then returned.
808       virtual TrackLatencyInfo& getDominanceLatencyInfo(bool input);
809       // The finalWorstLatency is the grand final worst-case latency, of any output track or open branch,
810       //  determined in the complete getDominanceLatencyInfo() scan.
811       // The callerBranchLatency is the inherent branch latency of the calling track, or zero if calling from
812       //  the very top outside of the branch heads (outside of output tracks or open branches).
813       // The callerBranchLatency is accumulated as setCorrectionLatencyInfo() is called on each track
814       //  in a branch of the graph.
815       virtual TrackLatencyInfo& setCorrectionLatencyInfo(bool input, float finalWorstLatency, float callerBranchLatency = 0.0f);
816       virtual TrackLatencyInfo& getLatencyInfo(bool input);
817       // Used during latency compensation processing. When analyzing in 'reverse' this mechansim is
818       //  needed only to equalize the timing of all the AudioOutput tracks.
819       // It is applied as a direct offset in the latency delay compensator in getData().
820       virtual void setLatencyCompWriteOffset(float worstCase);
821       virtual bool isLatencyInputTerminal();
822       virtual bool isLatencyOutputTerminal();
823 
824       // automation
automationType()825       virtual AutomationType automationType() const    { return _automationType; }
826       virtual void setAutomationType(AutomationType t);
recEvents()827       CtrlRecList* recEvents()                         { return &_recEvents; }
828       bool addScheduledControlEvent(int track_ctrl_id, double val, unsigned frame); // return true if event cannot be delivered
829       void enableController(int track_ctrl_id, bool en);
830       bool controllerEnabled(int track_ctrl_id) const;
831       // Enable all track and plugin controllers, and synth controllers if applicable.
832       void enableAllControllers();
833       void recordAutomation(int n, double v);
834       void startAutoRecord(int, double);
835       void stopAutoRecord(int, double);
836       void setControllerMode(int, CtrlList::Mode m);
837       void clearControllerEvents(int);
838       void seekPrevACEvent(int);
839       void seekNextACEvent(int);
840       void eraseACEvent(int, int);
841       void eraseRangeACEvents(int, int, int);
842       void addACEvent(int, int, double);
843       void changeACEvent(int id, int frame, int newframe, double newval);
getAuxSendValueList()844       AuxSendValueList *getAuxSendValueList() { return &_auxSend; }
845       };
846 
847 //---------------------------------------------------------
848 //   AudioInput
849 //---------------------------------------------------------
850 
851 class AudioInput : public AudioTrack {
852       void* jackPorts[MAX_CHANNELS];
853       bool getData(unsigned, int, unsigned, float**);
854       static bool _isVisible;
855       void internal_assign(const Track& t, int flags);
856 
857    public:
858       AudioInput();
859       AudioInput(const AudioInput&, int flags);
860       virtual ~AudioInput();
861 
862       float selfLatencyAudio(int channel) const;
863       // The cached worst contribution to latency by any ports (for ex. Jack ports of audio input/output tracks).
864       float getWorstPortLatencyAudio();
865       // Audio Input tracks have no correction available. They ALWAYS dominate any parallel branches, if they are not 'off'.
866       bool canDominateOutputLatency() const;
867 
868       // FIXME This public assign() method doesn't really 'assign' routes -
869       //        if routes are assigned in flags, it does not clear existing routes !
870       //       For input/output tracks we need to disconnect the routes from Jack.
871       void assign(const Track&, int flags);
clone(int flags)872       AudioInput* clone(int flags) const { return new AudioInput(*this, flags); }
873       void read(Xml&);
874       void write(int, Xml&) const;
875       // Register one or all input ports. If idx = -1 it registers all ports.
876       // Returns true if ANY of the port(s) were successfully registered.
877       bool registerPorts(int idx = -1);
878       void setName(const QString& s);
jackPort(int channel)879       void* jackPort(int channel) { return jackPorts[channel]; }
setJackPort(int channel,void * p)880       void setJackPort(int channel, void*p) { jackPorts[channel] = p; }
hasAuxSend()881       bool hasAuxSend() const { return true; }
882       // Number of routable inputs/outputs for each Route::RouteType.
883       RouteCapabilitiesStruct routeCapabilities() const;
setVisible(bool t)884       static void setVisible(bool t) { _isVisible = t; }
885       int height() const;
visible()886       static bool visible() { return _isVisible; }
887     };
888 
889 //---------------------------------------------------------
890 //   AudioOutput
891 //---------------------------------------------------------
892 
893 class AudioOutput : public AudioTrack {
894       void* jackPorts[MusECore::MAX_CHANNELS];
895       float* buffer[MusECore::MAX_CHANNELS];
896       float* buffer1[MusECore::MAX_CHANNELS];
897       unsigned long _nframes;
898       // Audio latency compensator, for compensating output signals
899       //  according to any differing channel port latencies.
900       LatencyCompensator* _outputLatencyComp;
901 
902       static bool _isVisible;
903       void internal_assign(const Track& t, int flags);
904 
905    public:
906       AudioOutput();
907       AudioOutput(const AudioOutput&, int flags);
908       virtual ~AudioOutput();
909 
910       float selfLatencyAudio(int channel) const;
911       void setChannels(int n);
912       // The cached worst contribution to latency by any ports (for ex. Jack ports of audio input/output tracks).
913       float getWorstPortLatencyAudio();
914       // Audio output tracks can allow a branch to dominate if they are an end-point and the branch can dominate.
canDominateEndPointLatency()915       inline bool canDominateEndPointLatency() const { return true; }
916       // Audio Output is considered a termination point.
917       bool isLatencyInputTerminal();
918       bool isLatencyOutputTerminal();
919       void applyOutputLatencyComp(unsigned nframes);
920 
921       // FIXME This public assign() method doesn't really 'assign' routes -
922       //        if routes are assigned in flags, it does not clear existing routes !
923       //       For input/output tracks we need to disconnect the routes from Jack.
924       void assign(const Track&, int flags);
clone(int flags)925       AudioOutput* clone(int flags) const { return new AudioOutput(*this, flags); }
926       void read(Xml&);
927       void write(int, Xml&) const;
928       // Register one or all output ports. If idx = -1 it registers all ports.
929       // Returns true if ANY of the port(s) were successfully registered.
930       bool registerPorts(int idx = -1);
931       void setName(const QString& s);
jackPort(int channel)932       void* jackPort(int channel) { return jackPorts[channel]; }
setJackPort(int channel,void * p)933       void setJackPort(int channel, void*p) { jackPorts[channel] = p; }
934       // Number of routable inputs/outputs for each Route::RouteType.
935       RouteCapabilitiesStruct routeCapabilities() const;
936       void processInit(unsigned);
937       void process(unsigned pos, unsigned offset, unsigned);
938       void processWrite();
939       void silence(unsigned);
canRecord()940       bool canRecord() const { return true; }
941 
setVisible(bool t)942       static void setVisible(bool t) { _isVisible = t; }
visible()943       static bool visible() { return _isVisible; }
944       int height() const;
945     };
946 
947 //---------------------------------------------------------
948 //   AudioGroup
949 //---------------------------------------------------------
950 
951 class AudioGroup : public AudioTrack {
952       static bool _isVisible;
953    public:
AudioGroup()954       AudioGroup() : AudioTrack(AUDIO_GROUP) {  }
AudioGroup(const AudioGroup & t,int flags)955       AudioGroup(const AudioGroup& t, int flags) : AudioTrack(t, flags) { }
956 
clone(int flags)957       AudioGroup* clone(int flags) const { return new AudioGroup(*this, flags); }
958       virtual void read(Xml&);
959       virtual void write(int, Xml&) const;
hasAuxSend()960       virtual bool hasAuxSend() const { return true; }
setVisible(bool t)961       static  void setVisible(bool t) { _isVisible = t; }
962       virtual int height() const;
visible()963       static bool visible() { return _isVisible; }
964     };
965 
966 //---------------------------------------------------------
967 //   AudioAux
968 //---------------------------------------------------------
969 
970 class AudioAux : public AudioTrack {
971       float* buffer[MusECore::MAX_CHANNELS];
972       static bool _isVisible;
973       int _index;
974    public:
975       AudioAux();
976       AudioAux(const AudioAux& t, int flags);
977 
clone(int flags)978       AudioAux* clone(int flags) const { return new AudioAux(*this, flags); }
979       ~AudioAux();
980       virtual void read(Xml&);
981       virtual void write(int, Xml&) const;
982       virtual bool getData(unsigned, int, unsigned, float**);
983       virtual void setChannels(int n);
984       // Number of routable inputs/outputs for each Route::RouteType.
routeCapabilities()985       virtual RouteCapabilitiesStruct routeCapabilities() const {
986                 RouteCapabilitiesStruct s = AudioTrack::routeCapabilities();
987                 s._trackChannels._inRoutable = false;
988                 s._trackChannels._inChannels = 0;
989                 return s; }
sendBuffer()990       float** sendBuffer() { return buffer; }
setVisible(bool t)991       static  void setVisible(bool t) { _isVisible = t; }
992       virtual int height() const;
visible()993       static bool visible() { return _isVisible; }
index()994       virtual int index() { return _index; }
995     };
996 
997 
998 //---------------------------------------------------------
999 //   WaveTrack
1000 //---------------------------------------------------------
1001 
1002 class WaveTrack : public AudioTrack {
1003       Fifo _prefetchFifo;  // prefetch Fifo
1004       // Each wavetrack has a separate prefetch position stamp
1005       //  so that consumers can retard or advance the stream and
1006       //  the prefetch can pump as much buffers as required while
1007       //  keeping track of the last buffer position stamp.
1008       unsigned _prefetchWritePos;
1009       static bool _isVisible;
1010 
1011       void internal_assign(const Track&, int flags);
1012       // Writes data from connected input routes to the track's latency compensator.
1013       // It uses buffer for temporary storage.
1014       bool getInputData(unsigned pos, int channels, unsigned nframes,
1015                         bool* usedInChannelArray, float** buffer);
1016 
1017       // Return false if no data or error.
1018       bool getPrefetchData(sf_count_t framePos, int dstChannels,
1019         sf_count_t nframe, float** bp, bool do_overwrite);
1020 
1021    public:
1022 
1023       WaveTrack();
1024       WaveTrack(const WaveTrack& wt, int flags);
1025 
1026       // FIXME This public assign() method doesn't really 'assign' routes -
1027       //        if routes are assigned in flags, it does not clear existing routes !
1028       virtual void assign(const Track&, int flags);
1029 
clone(int flags)1030       virtual WaveTrack* clone(int flags) const    { return new WaveTrack(*this, flags); }
1031       virtual Part* newPart(Part*p=0, bool clone=false);
1032       // Returns true if any event in any part was opened. Does not operate on the part's clones, if any.
1033       bool openAllParts();
1034       // Returns true if any event in any part was closed. Does not operate on the part's clones, if any.
1035       bool closeAllParts();
1036 
1037       virtual void read(Xml&);
1038       virtual void write(int, Xml&) const;
1039 
1040       // Called from prefetch thread:
1041       // If overwrite is true, copies the data. If false, adds the data.
1042       virtual void fetchData(unsigned pos, unsigned frames, float** bp, bool doSeek, bool overwrite, int latency_correction = 0);
1043 
1044       virtual void seekData(sf_count_t pos);
1045 
1046       virtual bool getData(unsigned, int ch, unsigned, float** bp);
1047 
1048       // Depending on the Monitor setting, Wave Tracks can have available correction.
1049       // If unmonitored, they will never dominate parallel branches.
1050       bool canDominateOutputLatency() const;
1051       bool canCorrectOutputLatency() const;
1052 
1053       void clearPrefetchFifo();
prefetchFifo()1054       Fifo* prefetchFifo()          { return &_prefetchFifo; }
1055       virtual void prefetchAudio(sf_count_t writePos, sf_count_t frames);
1056 
1057       // For prefetch thread use only.
prefetchWritePos()1058       inline unsigned prefetchWritePos() const { return _prefetchWritePos; }
setPrefetchWritePos(unsigned p)1059       inline void setPrefetchWritePos(unsigned p) { _prefetchWritePos = p; }
1060 
1061       virtual void setChannels(int n);
hasAuxSend()1062       virtual bool hasAuxSend() const { return true; }
1063       bool canEnableRecord() const;
canRecord()1064       virtual bool canRecord() const { return true; }
canRecordMonitor()1065       virtual bool canRecordMonitor() const { return true; }
setVisible(bool t)1066       static void setVisible(bool t) { _isVisible = t; }
1067       virtual int height() const;
visible()1068       static bool visible() { return _isVisible; }
1069     };
1070 
1071 //---------------------------------------------------------
1072 //   TrackList
1073 //---------------------------------------------------------
1074 
1075 template<class T> class tracklist : public std::vector<Track*> {
1076       typedef std::vector<Track*> vlist;
1077 
1078    public:
1079       class iterator : public vlist::iterator {
1080          public:
iterator()1081             iterator() : vlist::iterator() {}
iterator(vlist::iterator i)1082             iterator(vlist::iterator i) : vlist::iterator(i) {}
1083 
1084             T operator*() {
1085                   return (T)(**((vlist::iterator*)this));
1086                   }
1087             iterator operator++(int) {
1088                   return iterator ((*(vlist::iterator*)this).operator++(0));
1089                   }
1090             iterator& operator++() {
1091                   return (iterator&) ((*(vlist::iterator*)this).operator++());
1092                   }
1093             };
1094 
1095       class const_iterator : public vlist::const_iterator {
1096          public:
const_iterator()1097             const_iterator() : vlist::const_iterator() {}
const_iterator(vlist::const_iterator i)1098             const_iterator(vlist::const_iterator i) : vlist::const_iterator(i) {}
const_iterator(vlist::iterator i)1099             const_iterator(vlist::iterator i) : vlist::const_iterator(i) {}
1100 
1101             const T operator*() const {
1102                   return (T)(**((vlist::const_iterator*)this));
1103                   }
1104             };
1105 
1106       class reverse_iterator : public vlist::reverse_iterator {
1107          public:
reverse_iterator()1108             reverse_iterator() : vlist::reverse_iterator() {}
reverse_iterator(vlist::reverse_iterator i)1109             reverse_iterator(vlist::reverse_iterator i) : vlist::reverse_iterator(i) {}
1110 
1111             T operator*() {
1112                   return (T)(**((vlist::reverse_iterator*)this));
1113                   }
1114             };
1115 
tracklist()1116       tracklist() : vlist() {}
~tracklist()1117       virtual ~tracklist() {}
1118 
push_back(T v)1119       void push_back(T v)             { vlist::push_back(v); }
begin()1120       iterator begin()                { return vlist::begin(); }
end()1121       iterator end()                  { return vlist::end(); }
begin()1122       const_iterator begin() const    { return vlist::cbegin(); }
end()1123       const_iterator end() const      { return vlist::cend(); }
cbegin()1124       const_iterator cbegin() const   { return vlist::cbegin(); }
cend()1125       const_iterator cend() const     { return vlist::cend(); }
rbegin()1126       reverse_iterator rbegin()       { return vlist::rbegin(); }
rend()1127       reverse_iterator rend()         { return vlist::rend(); }
back()1128       T& back() const                 { return (T&)(vlist::back()); }
front()1129       T& front() const                { return (T&)(vlist::front()); }
find(const Track * t)1130       iterator find(const Track* t)       {
1131             return std::find(begin(), end(), t);
1132             }
find(const Track * t)1133       const_iterator find(const Track* t) const {
1134             return std::find(cbegin(), cend(), t);
1135             }
contains(const Track * t)1136       bool contains(const Track* t) const {
1137             return std::find(cbegin(), cend(), t) != cend();
1138             }
index(const Track * t)1139       int index(const Track* t) const {
1140             int n = 0;
1141             for (vlist::const_iterator i = cbegin(); i != cend(); ++i, ++n) {
1142                   if (*i == t)
1143                         return n;
1144                   }
1145             return -1;
1146             }
index(int k)1147       T index(int k) const {
1148             if (k < 0 || k >= (int)size())
1149                   return nullptr;
1150             return (*this)[k];
1151             }
findSerial(int sn)1152       T findSerial(int sn) const {
1153             if (sn < 0)
1154                   return nullptr;
1155             for (vlist::const_iterator i = cbegin(); i != cend(); ++i) {
1156                   if ((*i)->serial() == sn) {
1157                         return *i;
1158                         }
1159                   }
1160             return nullptr;
1161             }
indexOfSerial(int sn)1162       int indexOfSerial(int sn) const {
1163             if (sn < 0)
1164                   return -1;
1165             int n = 0;
1166             for (vlist::const_iterator i = cbegin(); i != cend(); ++i, ++n) {
1167                   if ((*i)->serial() == sn) {
1168                         return n;
1169                         }
1170                   }
1171             return -1;
1172             }
index2iterator(int k)1173       iterator index2iterator(int k) {
1174             if (k < 0 || k >= (int)size())
1175                   return end();
1176             return begin() + k;
1177             }
erase(Track * t)1178       void erase(Track* t)           { vlist::erase(find(t)); }
1179 
clearDelete()1180       void clearDelete() {
1181             for (vlist::iterator i = begin(); i != end(); ++i)
1182                   delete *i;
1183             vlist::clear();
1184             }
erase(vlist::const_iterator i)1185       void erase(vlist::const_iterator i) { vlist::erase(i); }
replace(Track * ot,Track * nt)1186       void replace(Track* ot, Track* nt) {
1187             for (vlist::iterator i = begin(); i != end(); ++i) {
1188                   if (*i == ot) {
1189                         *i = nt;
1190                         return;
1191                         }
1192                   }
1193             }
1194       // Returns the number of selected tracks in this list.
countSelected()1195       int countSelected() const {
1196             int c = 0;
1197             for (vlist::const_iterator i = cbegin(); i != cend(); ++i) {
1198                   if ((*i)->selected()) {
1199                         ++c;
1200                         }
1201                   }
1202             return c;
1203             }
1204       // Returns the current (most recent) selected track, or null if none.
1205       // It returns the track with the highest _selectionOrder.
1206       // This helps with multi-selection common-property editing.
currentSelection()1207       T currentSelection() const {
1208             T cur = 0;
1209             int c = 0;
1210             int so;
1211             for (vlist::const_iterator i = cbegin(); i != cend(); ++i) {
1212                   T t = *i;
1213                   so = t->selectionOrder();
1214                   if (t->selected() && so >= c) {
1215                         cur = t;
1216                         c = so;
1217                         }
1218                   }
1219             return cur;
1220             }
1221       // Selects or unselects all tracks in this list.
selectAll(bool select)1222       void selectAll(bool select) {
1223             for (vlist::iterator i = begin(); i != end(); ++i) {
1224                   (*i)->setSelected(select);
1225                   }
1226             }
1227       };
1228 
1229 typedef tracklist<Track*> TrackList;
1230 typedef TrackList::iterator iTrack;
1231 typedef TrackList::const_iterator ciTrack;
1232 
1233 typedef tracklist<MidiTrack*>::iterator iMidiTrack;
1234 typedef tracklist<MidiTrack*>::const_iterator ciMidiTrack;
1235 typedef tracklist<MidiTrack*> MidiTrackList;
1236 
1237 typedef tracklist<WaveTrack*>::iterator iWaveTrack;
1238 typedef tracklist<WaveTrack*>::const_iterator ciWaveTrack;
1239 typedef tracklist<WaveTrack*> WaveTrackList;
1240 
1241 typedef tracklist<AudioInput*>::iterator iAudioInput;
1242 typedef tracklist<AudioInput*>::const_iterator ciAudioInput;
1243 typedef tracklist<AudioInput*> InputList;
1244 
1245 typedef tracklist<AudioOutput*>::iterator iAudioOutput;
1246 typedef tracklist<AudioOutput*>::const_iterator ciAudioOutput;
1247 typedef tracklist<AudioOutput*> OutputList;
1248 
1249 typedef tracklist<AudioGroup*>::iterator iAudioGroup;
1250 typedef tracklist<AudioGroup*>::const_iterator ciAudioGroup;
1251 typedef tracklist<AudioGroup*> GroupList;
1252 
1253 typedef tracklist<AudioAux*>::iterator iAudioAux;
1254 typedef tracklist<AudioAux*>::const_iterator ciAudioAux;
1255 typedef tracklist<AudioAux*> AuxList;
1256 
1257 // NOTE: There is also a tracklist for SynthI* found in synth.h
1258 
1259 
1260 extern void addPortCtrlEvents(MidiTrack* t, bool drum_ctls = true, bool non_drum_ctls = true);
1261 extern void removePortCtrlEvents(MidiTrack* t, bool drum_ctls = true, bool non_drum_ctls = true);
1262 
1263 } // namespace MusECore
1264 
1265 #endif
1266 
1267