extend save-as API to allow for new empty sessions based on current
[ardour.git] / libs / ardour / ardour / session.h
1 /*
2   Copyright (C) 2000 Paul Davis
3
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU General Public License as published by
6   the Free Software Foundation; either version 2 of the License, or
7   (at your option) any later version.
8
9   This program is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   GNU General Public License for more details.
13
14   You should have received a copy of the GNU General Public License
15   along with this program; if not, write to the Free Software
16   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #ifndef __ardour_session_h__
21 #define __ardour_session_h__
22
23 #include "libardour-config.h"
24
25 #include <list>
26 #include <map>
27 #include <set>
28 #include <string>
29 #include <vector>
30 #include <stdint.h>
31
32 #include <boost/dynamic_bitset.hpp>
33 #include <boost/scoped_ptr.hpp>
34 #include <boost/weak_ptr.hpp>
35 #include <boost/utility.hpp>
36
37 #include <glibmm/threads.h>
38
39 #include <ltc.h>
40
41 #include "pbd/error.h"
42 #include "pbd/event_loop.h"
43 #include "pbd/rcu.h"
44 #include "pbd/statefuldestructible.h"
45 #include "pbd/signals.h"
46 #include "pbd/undo.h"
47
48 #include "evoral/types.hpp"
49
50 #include "midi++/types.h"
51 #include "midi++/mmc.h"
52
53 #include "timecode/time.h"
54
55 #include "ardour/ardour.h"
56 #include "ardour/chan_count.h"
57 #include "ardour/delivery.h"
58 #include "ardour/interthread_info.h"
59 #include "ardour/rc_configuration.h"
60 #include "ardour/session_configuration.h"
61 #include "ardour/session_event.h"
62 #include "ardour/location.h"
63 #include "ardour/interpolation.h"
64 #include "ardour/route_graph.h"
65
66
67 class XMLTree;
68 class XMLNode;
69 struct _AEffect;
70 typedef struct _AEffect AEffect;
71
72 namespace MIDI {
73 class Port;
74 class MachineControl;
75 class Parser;
76 }
77
78 namespace PBD {
79 class Controllable;
80 class ControllableDescriptor;
81 }
82
83 namespace Evoral {
84 class Curve;
85 }
86
87 namespace ARDOUR {
88
89 class Amp;
90 class AudioEngine;
91 class AudioFileSource;
92 class AudioRegion;
93 class AudioSource;
94 class AudioTrack;
95 class Auditioner;
96 class AutomationList;
97 class AuxInput;
98 class BufferSet;
99 class Bundle;
100 class Butler;
101 class Click;
102 class Diskstream;
103 class ExportHandler;
104 class ExportStatus;
105 class Graph;
106 class IO;
107 class IOProcessor;
108 class ImportStatus;
109 class MidiClockTicker;
110 class MidiControlUI;
111 class MidiPortManager;
112 class MidiPort;
113 class MidiRegion;
114 class MidiSource;
115 class MidiTrack;
116 class Playlist;
117 class PluginInsert;
118 class PluginInfo;
119 class Port;
120 class PortInsert;
121 class ProcessThread;
122 class Processor;
123 class Region;
124 class Return;
125 class Route;
126 class RouteGroup;
127 class SMFSource;
128 class Send;
129 class SceneChanger;
130 class SessionDirectory;
131 class SessionMetadata;
132 class SessionPlaylists;
133 class Slave;
134 class Source;
135 class Speakers;
136 class TempoMap;
137 class Track;
138 class WindowsVSTPlugin;
139
140 extern void setup_enum_writer ();
141
142 class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::ScopedConnectionList, public SessionEventManager
143 {
144   public:
145         enum RecordState {
146                 Disabled = 0,
147                 Enabled = 1,
148                 Recording = 2
149         };
150
151         /* a new session might have non-empty mix_template, an existing session should always have an empty one.
152            the bus profile can be null if no master out bus is required.
153         */
154
155         Session (AudioEngine&,
156                  const std::string& fullpath,
157                  const std::string& snapshot_name,
158                  BusProfile* bus_profile = 0,
159                  std::string mix_template = "");
160
161         virtual ~Session ();
162
163         static int get_info_from_path (const std::string& xmlpath, float& sample_rate, SampleFormat& data_format);
164
165         std::string path() const { return _path; }
166         std::string name() const { return _name; }
167         std::string snap_name() const { return _current_snapshot_name; }
168         std::string raid_path () const;
169         bool path_is_within_session (const std::string&);
170
171         void set_snap_name ();
172
173         bool writable() const { return _writable; }
174         void set_dirty ();
175         void set_clean ();
176         bool dirty() const { return _state_of_the_state & Dirty; }
177         void set_deletion_in_progress ();
178         void clear_deletion_in_progress ();
179         bool deletion_in_progress() const { return _state_of_the_state & Deletion; }
180         PBD::Signal0<void> DirtyChanged;
181
182         const SessionDirectory& session_directory () const { return *(_session_dir.get()); }
183
184         static PBD::Signal1<void,std::string> Dialog;
185
186         PBD::Signal0<void> BatchUpdateStart;
187         PBD::Signal0<void> BatchUpdateEnd;
188
189         int ensure_subdirs ();
190
191         std::string automation_dir () const;  ///< Automation data
192         std::string analysis_dir () const;    ///< Analysis data
193         std::string plugins_dir () const;     ///< Plugin state
194         std::string externals_dir () const;   ///< Links to external files
195
196         std::string peak_path (std::string) const;
197
198         std::string peak_path_from_audio_path (std::string) const;
199         bool audio_source_name_is_unique (const std::string& name);
200         std::string format_audio_source_name (const std::string& legalized_base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required, uint32_t cnt, bool related_exists);
201         std::string new_audio_source_path_for_embedded (const std::string& existing_path);
202         std::string new_audio_source_path (const std::string&, uint32_t nchans, uint32_t chan, bool destructive, bool take_required);
203         std::string new_midi_source_path (const std::string&);
204         RouteList new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name);
205         std::vector<std::string> get_paths_for_new_sources (bool allow_replacing, const std::string& import_file_path, uint32_t channels);
206
207         int bring_all_sources_into_session (boost::function<void(uint32_t,uint32_t,std::string)> callback);
208
209         void process (pframes_t nframes);
210
211         BufferSet& get_silent_buffers (ChanCount count = ChanCount::ZERO);
212         BufferSet& get_scratch_buffers (ChanCount count = ChanCount::ZERO, bool silence = true );
213         BufferSet& get_route_buffers (ChanCount count = ChanCount::ZERO, bool silence = true);
214         BufferSet& get_mix_buffers (ChanCount count = ChanCount::ZERO);
215
216         bool have_rec_enabled_track () const;
217
218         bool have_captured() const { return _have_captured; }
219
220         void refill_all_track_buffers ();
221         Butler* butler() { return _butler; }
222         void butler_transport_work ();
223
224         void refresh_disk_space ();
225
226         int load_diskstreams_2X (XMLNode const &, int);
227
228         int load_routes (const XMLNode&, int);
229         boost::shared_ptr<RouteList> get_routes() const {
230                 return routes.reader ();
231         }
232
233         boost::shared_ptr<RouteList> get_tracks() const;
234         boost::shared_ptr<RouteList> get_routes_with_internal_returns() const;
235         boost::shared_ptr<RouteList> get_routes_with_regions_at (framepos_t const) const;
236
237         uint32_t nroutes() const { return routes.reader()->size(); }
238         uint32_t ntracks () const;
239         uint32_t nbusses () const;
240
241         boost::shared_ptr<BundleList> bundles () {
242                 return _bundles.reader ();
243         }
244
245         struct LIBARDOUR_API RoutePublicOrderSorter {
246                 bool operator() (boost::shared_ptr<Route>, boost::shared_ptr<Route> b);
247         };
248
249         void set_order_hint (int32_t order_hint) {_order_hint = order_hint;};
250         void notify_remote_id_change ();
251         void sync_order_keys ();
252
253         template<class T> void foreach_route (T *obj, void (T::*func)(Route&), bool sort = true);
254         template<class T> void foreach_route (T *obj, void (T::*func)(boost::shared_ptr<Route>), bool sort = true);
255         template<class T, class A> void foreach_route (T *obj, void (T::*func)(Route&, A), A arg, bool sort = true);
256
257         static char session_name_is_legal (const std::string&);
258         bool io_name_is_legal (const std::string&);
259         boost::shared_ptr<Route> route_by_name (std::string);
260         boost::shared_ptr<Route> route_by_id (PBD::ID);
261         boost::shared_ptr<Route> route_by_remote_id (uint32_t id);
262         boost::shared_ptr<Track> track_by_diskstream_id (PBD::ID);
263         void routes_using_input_from (const std::string& str, RouteList& rl);
264
265         bool route_name_unique (std::string) const;
266         bool route_name_internal (std::string) const;
267
268         uint32_t track_number_decimals () const {
269                 return _track_number_decimals;
270         }
271
272         bool get_record_enabled() const {
273                 return (record_status () >= Enabled);
274         }
275
276         RecordState record_status() const {
277                 return (RecordState) g_atomic_int_get (&_record_status);
278         }
279
280         bool actively_recording () const {
281                 return record_status() == Recording;
282         }
283
284         bool record_enabling_legal () const;
285         void maybe_enable_record ();
286         void disable_record (bool rt_context, bool force = false);
287         void step_back_from_record ();
288
289         void maybe_write_autosave ();
290
291         /* Emitted when all i/o connections are complete */
292
293         PBD::Signal0<void> IOConnectionsComplete;
294
295         /* Record status signals */
296
297         PBD::Signal0<void> RecordStateChanged;
298
299         /* Transport mechanism signals */
300
301         /** Emitted on the following changes in transport state:
302          *  - stop (from the butler thread)
303          *  - change in whether or not we are looping (from the process thread)
304          *  - change in the play range (from the process thread)
305          *  - start (from the process thread)
306          *  - engine halted
307          */
308         PBD::Signal0<void> TransportStateChange;
309
310         PBD::Signal1<void,framepos_t> PositionChanged; /* sent after any non-sequential motion */
311         PBD::Signal1<void,framepos_t> Xrun;
312         PBD::Signal0<void> TransportLooped;
313
314         /** emitted when a locate has occurred */
315         PBD::Signal0<void> Located;
316
317         PBD::Signal1<void,RouteList&> RouteAdded;
318         /** Emitted when a property of one of our route groups changes.
319          *  The parameter is the RouteGroup that has changed.
320          */
321         PBD::Signal1<void, RouteGroup *> RouteGroupPropertyChanged;
322         /** Emitted when a route is added to one of our route groups.
323          *  First parameter is the RouteGroup, second is the route.
324          */
325         PBD::Signal2<void, RouteGroup *, boost::weak_ptr<Route> > RouteAddedToRouteGroup;
326         /** Emitted when a route is removed from one of our route groups.
327          *  First parameter is the RouteGroup, second is the route.
328          */
329         PBD::Signal2<void, RouteGroup *, boost::weak_ptr<Route> > RouteRemovedFromRouteGroup;
330
331         /* Step Editing status changed */
332         PBD::Signal1<void,bool> StepEditStatusChange;
333
334         void queue_event (SessionEvent*);
335
336         void request_roll_at_and_return (framepos_t start, framepos_t return_to);
337         void request_bounded_roll (framepos_t start, framepos_t end);
338         void request_stop (bool abort = false, bool clear_state = false);
339         void request_locate (framepos_t frame, bool with_roll = false);
340
341         void request_play_loop (bool yn, bool leave_rolling = false);
342         bool get_play_loop () const { return play_loop; }
343
344         framepos_t last_transport_start () const { return _last_roll_location; }
345         void goto_end ();
346         void goto_start ();
347         void use_rf_shuttle_speed ();
348         void allow_auto_play (bool yn);
349         void request_transport_speed (double speed, bool as_default = false);
350         void request_transport_speed_nonzero (double, bool as_default = false);
351         void request_overwrite_buffer (Track *);
352         void adjust_playback_buffering();
353         void adjust_capture_buffering();
354         void request_track_speed (Track *, double speed);
355         void request_input_change_handling ();
356
357         bool locate_pending() const { return static_cast<bool>(post_transport_work()&PostTransportLocate); }
358         bool transport_locked () const;
359
360         int wipe ();
361
362         framepos_t current_end_frame () const;
363         framepos_t current_start_frame () const;
364         /** "actual" sample rate of session, set by current audioengine rate, pullup/down etc. */
365         framecnt_t frame_rate () const { return _current_frame_rate; }
366         /** "native" sample rate of session, regardless of current audioengine rate, pullup/down etc */
367         framecnt_t nominal_frame_rate () const { return _nominal_frame_rate; }
368         framecnt_t frames_per_hour () const { return _frames_per_hour; }
369
370         double frames_per_timecode_frame() const { return _frames_per_timecode_frame; }
371         framecnt_t timecode_frames_per_hour() const { return _timecode_frames_per_hour; }
372
373         MIDI::byte get_mtc_timecode_bits() const {
374                 return mtc_timecode_bits;   /* encoding of SMTPE type for MTC */
375         }
376
377         double timecode_frames_per_second() const;
378         bool timecode_drop_frames() const;
379
380         /* Locations */
381
382         Locations *locations() { return _locations; }
383
384         PBD::Signal1<void,Location*>    auto_loop_location_changed;
385         PBD::Signal1<void,Location*>    auto_punch_location_changed;
386         PBD::Signal0<void>              locations_modified;
387
388         void set_auto_punch_location (Location *);
389         void set_auto_loop_location (Location *);
390         void set_session_extents (framepos_t start, framepos_t end);
391         int location_name(std::string& result, std::string base = std::string(""));
392
393         pframes_t get_block_size()        const { return current_block_size; }
394         framecnt_t worst_output_latency () const { return _worst_output_latency; }
395         framecnt_t worst_input_latency ()  const { return _worst_input_latency; }
396         framecnt_t worst_track_latency ()  const { return _worst_track_latency; }
397         framecnt_t worst_playback_latency () const { return _worst_output_latency + _worst_track_latency; }
398         
399         struct SaveAs {
400                 std::string new_parent_folder;  /* parent folder where new session folder will be created */
401                 std::string new_name;           /* name of newly saved session */
402                 bool        switch_to;     /* true if we should be working on newly saved session after save-as; false otherwise */
403                 bool        include_media; /* true if the newly saved session should contain references to media */
404                 bool        copy_media;    /* true if media files (audio, media, etc) should be copied into newly saved session; false otherwise */
405                 bool        copy_external; /* true if external media should be consolidated into the newly saved session; false otherwise */
406
407                 std::string final_session_folder_name; /* filled in by * Session::save_as(), provides full path to newly saved session */
408                 
409                 /* emitted as we make progress. 3 arguments passed to signal
410                  * handler:
411                  *
412                  *  1: percentage complete measured as a fraction (0-1.0) of
413                  *     total data copying done.
414                  *  2: number of files copied so far
415                  *  3: total number of files to copy
416                  *
417                  * Handler should return true for save-as to continue, or false
418                  * to stop (and remove all evidence of partial save-as).
419                  */
420                 PBD::Signal3<bool,float,int64_t,int64_t> Progress;
421
422                 /* if save_as() returns non-zero, this string will indicate the reason why.
423                  */
424                 std::string failure_message;
425         };
426
427         int save_as (SaveAs&);
428         int save_state (std::string snapshot_name, bool pending = false, bool switch_to_snapshot = false, bool template_only = false);
429         int restore_state (std::string snapshot_name);
430         int save_template (std::string template_name);
431         int save_history (std::string snapshot_name = "");
432         int restore_history (std::string snapshot_name);
433         void remove_state (std::string snapshot_name);
434         void rename_state (std::string old_name, std::string new_name);
435         void remove_pending_capture_state ();
436         int rename (const std::string&);
437         bool get_nsm_state () const { return _under_nsm_control; }
438         void set_nsm_state (bool state) { _under_nsm_control = state; }
439         bool save_default_options ();
440
441         PBD::Signal1<void,std::string> StateSaved;
442         PBD::Signal0<void> StateReady;
443
444         /* emitted when session needs to be saved due to some internal
445          * event or condition (i.e. not in response to a user request).
446          *
447          * Only one object should
448          * connect to this signal and take responsibility.
449          *
450          * Argument is the snapshot name to use when saving.
451          */
452         PBD::Signal1<void,std::string> SaveSessionRequested; 
453
454         /* emitted during a session save to allow other entities to add state, via
455          * extra XML, to the session state 
456          */
457         PBD::Signal0<void> SessionSaveUnderway;
458
459         std::vector<std::string> possible_states() const;
460         static std::vector<std::string> possible_states (std::string path);
461
462         XMLNode& get_state();
463         int      set_state(const XMLNode& node, int version); // not idempotent
464         XMLNode& get_template();
465
466         /// The instant xml file is written to the session directory
467         void add_instant_xml (XMLNode&, bool write_to_config = true);
468         XMLNode* instant_xml (const std::string& str);
469
470         enum StateOfTheState {
471                 Clean = 0x0,
472                 Dirty = 0x1,
473                 CannotSave = 0x2,
474                 Deletion = 0x4,
475                 InitialConnecting = 0x8,
476                 Loading = 0x10,
477                 InCleanup = 0x20
478         };
479
480         StateOfTheState state_of_the_state() const { return _state_of_the_state; }
481
482         class StateProtector {
483                                                 public:
484                 StateProtector (Session* s) : _session (s) {
485                         g_atomic_int_inc (&s->_suspend_save);
486                 }
487                 ~StateProtector () {
488                         if (g_atomic_int_dec_and_test (&_session->_suspend_save)) {
489                                 while (_session->_save_queued) {
490                                         _session->_save_queued = false;
491                                         _session->save_state ("");
492                                 }
493                         }
494                 }
495                                                 private:
496                 Session * _session;
497         };
498
499         void add_route_group (RouteGroup *);
500         void remove_route_group (RouteGroup&);
501         void reorder_route_groups (std::list<RouteGroup*>);
502
503         RouteGroup* route_group_by_name (std::string);
504         RouteGroup& all_route_group() const;
505
506         PBD::Signal1<void,RouteGroup*> route_group_added;
507         PBD::Signal0<void>             route_group_removed;
508         PBD::Signal0<void>             route_groups_reordered;
509
510         void foreach_route_group (boost::function<void(RouteGroup*)> f) {
511                 for (std::list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
512                         f (*i);
513                 }
514         }
515
516         std::list<RouteGroup*> const & route_groups () const {
517                 return _route_groups;
518         }
519
520         /* fundamental operations. duh. */
521
522         std::list<boost::shared_ptr<AudioTrack> > new_audio_track (
523                 int input_channels,
524                 int output_channels,
525                 TrackMode mode = Normal,
526                 RouteGroup* route_group = 0,
527                 uint32_t how_many = 1,
528                 std::string name_template = ""
529                 );
530
531         RouteList new_audio_route (
532                 int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, std::string name_template = ""
533                 );
534
535         std::list<boost::shared_ptr<MidiTrack> > new_midi_track (
536                 const ChanCount& input, const ChanCount& output,
537                 boost::shared_ptr<PluginInfo> instrument = boost::shared_ptr<PluginInfo>(),
538                 TrackMode mode = Normal, 
539                 RouteGroup* route_group = 0, uint32_t how_many = 1, std::string name_template = ""
540                 );
541
542         void   remove_route (boost::shared_ptr<Route>);
543         void   resort_routes ();
544         void   resort_routes_using (boost::shared_ptr<RouteList>);
545
546         AudioEngine & engine() { return _engine; }
547         AudioEngine const & engine () const { return _engine; }
548
549         /* Time */
550
551         framepos_t transport_frame () const {return _transport_frame; }
552         framepos_t record_location () const {return _last_record_location; }
553         framepos_t audible_frame () const;
554         framepos_t requested_return_frame() const { return _requested_return_frame; }
555         void set_requested_return_frame(framepos_t return_to);
556
557         enum PullupFormat {
558                 pullup_Plus4Plus1,
559                 pullup_Plus4,
560                 pullup_Plus4Minus1,
561                 pullup_Plus1,
562                 pullup_None,
563                 pullup_Minus1,
564                 pullup_Minus4Plus1,
565                 pullup_Minus4,
566                 pullup_Minus4Minus1
567         };
568
569         void sync_time_vars();
570
571         void bbt_time (framepos_t when, Timecode::BBT_Time&);
572         void timecode_to_sample(Timecode::Time& timecode, framepos_t& sample, bool use_offset, bool use_subframes) const;
573         void sample_to_timecode(framepos_t sample, Timecode::Time& timecode, bool use_offset, bool use_subframes) const;
574         void timecode_time (Timecode::Time &);
575         void timecode_time (framepos_t when, Timecode::Time&);
576         void timecode_time_subframes (framepos_t when, Timecode::Time&);
577
578         void timecode_duration (framecnt_t, Timecode::Time&) const;
579         void timecode_duration_string (char *, size_t len, framecnt_t) const;
580
581         framecnt_t convert_to_frames (AnyTime const & position);
582         framecnt_t any_duration_to_frames (framepos_t position, AnyTime const & duration);
583
584         static PBD::Signal1<void, framepos_t> StartTimeChanged;
585         static PBD::Signal1<void, framepos_t> EndTimeChanged;
586
587         void   request_sync_source (Slave*);
588         bool   synced_to_engine() const { return _slave && config.get_external_sync() && Config->get_sync_source() == Engine; }
589
590         double transport_speed() const { return _transport_speed; }
591         bool   transport_stopped() const { return _transport_speed == 0.0f; }
592         bool   transport_rolling() const { return _transport_speed != 0.0f; }
593
594         bool silent () { return _silent; }
595
596         TempoMap&       tempo_map()       { return *_tempo_map; }
597         const TempoMap& tempo_map() const { return *_tempo_map; }
598
599         unsigned int    get_xrun_count () const {return _xrun_count; }
600         void            reset_xrun_count () {_xrun_count = 0; }
601
602         /* region info  */
603
604         boost::shared_ptr<Region> find_whole_file_parent (boost::shared_ptr<Region const>) const;
605
606         boost::shared_ptr<Region>      XMLRegionFactory (const XMLNode&, bool full);
607         boost::shared_ptr<AudioRegion> XMLAudioRegionFactory (const XMLNode&, bool full);
608         boost::shared_ptr<MidiRegion>  XMLMidiRegionFactory (const XMLNode&, bool full);
609
610         /* source management */
611
612         void import_files (ImportStatus&);
613         bool sample_rate_convert (ImportStatus&, std::string infile, std::string& outfile);
614         std::string build_tmp_convert_name (std::string file);
615
616         boost::shared_ptr<ExportHandler> get_export_handler ();
617         boost::shared_ptr<ExportStatus> get_export_status ();
618
619         int start_audio_export (framepos_t position);
620
621         PBD::Signal1<int, framecnt_t> ProcessExport;
622         static PBD::Signal2<void,std::string, std::string> Exported;
623
624         void add_source (boost::shared_ptr<Source>);
625         void remove_source (boost::weak_ptr<Source>);
626
627         void  cleanup_regions();
628         int  cleanup_sources (CleanupReport&);
629         int  cleanup_trash_sources (CleanupReport&);
630
631         int destroy_sources (std::list<boost::shared_ptr<Source> >);
632
633         int remove_last_capture ();
634
635         /** handlers should return 0 for "everything OK", and any other value for
636          * "cannot setup audioengine".
637          */
638         static PBD::Signal1<int,uint32_t> AudioEngineSetupRequired;
639
640         /** handlers should return -1 for "stop cleanup",
641             0 for "yes, delete this playlist",
642             1 for "no, don't delete this playlist".
643         */
644         static PBD::Signal1<int,boost::shared_ptr<Playlist> >  AskAboutPlaylistDeletion;
645
646         /** handlers should return 0 for "ignore the rate mismatch",
647             !0 for "do not use this session"
648         */
649         static PBD::Signal2<int, framecnt_t, framecnt_t> AskAboutSampleRateMismatch;
650
651         /** handlers should return !0 for use pending state, 0 for ignore it.
652          */
653         static PBD::Signal0<int> AskAboutPendingState;
654
655         boost::shared_ptr<AudioFileSource> create_audio_source_for_session (
656                 size_t, std::string const &, uint32_t, bool destructive);
657
658         boost::shared_ptr<MidiSource> create_midi_source_for_session (std::string const &);
659         boost::shared_ptr<MidiSource> create_midi_source_by_stealing_name (boost::shared_ptr<Track>);
660
661         boost::shared_ptr<Source> source_by_id (const PBD::ID&);
662         boost::shared_ptr<AudioFileSource> audio_source_by_path_and_channel (const std::string&, uint16_t) const;
663         boost::shared_ptr<MidiSource> midi_source_by_path (const std::string&) const;
664         uint32_t count_sources_by_origin (const std::string&);
665
666         void add_playlist (boost::shared_ptr<Playlist>, bool unused = false);
667
668         /* Curves and AutomationLists (TODO when they go away) */
669         void add_automation_list(AutomationList*);
670
671         /* auditioning */
672
673         boost::shared_ptr<Auditioner> the_auditioner() { return auditioner; }
674         void audition_playlist ();
675         void audition_region (boost::shared_ptr<Region>);
676         void cancel_audition ();
677         bool is_auditioning () const;
678
679         PBD::Signal1<void,bool> AuditionActive;
680
681         /* flattening stuff */
682
683         boost::shared_ptr<Region> write_one_track (Track&, framepos_t start, framepos_t end,
684                                                    bool overwrite, std::vector<boost::shared_ptr<Source> >&, InterThreadInfo& wot,
685                                                    boost::shared_ptr<Processor> endpoint,
686                                                    bool include_endpoint, bool for_export, bool for_freeze);
687         int freeze_all (InterThreadInfo&);
688
689         /* session-wide solo/mute/rec-enable */
690
691         bool soloing() const { return _non_soloed_outs_muted; }
692         bool listening() const { return _listen_cnt > 0; }
693         bool solo_isolated() const { return _solo_isolated_cnt > 0; }
694
695         static const SessionEvent::RTeventCallback rt_cleanup;
696
697         void set_solo (boost::shared_ptr<RouteList>, bool, SessionEvent::RTeventCallback after = rt_cleanup, bool group_override = false);
698         void set_just_one_solo (boost::shared_ptr<Route>, bool, SessionEvent::RTeventCallback after = rt_cleanup);
699         void cancel_solo_after_disconnect (boost::shared_ptr<Route>, bool upstream, SessionEvent::RTeventCallback after = rt_cleanup);
700         void set_mute (boost::shared_ptr<RouteList>, bool, SessionEvent::RTeventCallback after = rt_cleanup, bool group_override = false);
701         void set_listen (boost::shared_ptr<RouteList>, bool, SessionEvent::RTeventCallback after = rt_cleanup, bool group_override = false);
702         void set_record_enabled (boost::shared_ptr<RouteList>, bool, SessionEvent::RTeventCallback after = rt_cleanup, bool group_override = false);
703         void set_solo_isolated (boost::shared_ptr<RouteList>, bool, SessionEvent::RTeventCallback after = rt_cleanup, bool group_override = false);
704         void set_monitoring (boost::shared_ptr<RouteList>, MonitorChoice, SessionEvent::RTeventCallback after = rt_cleanup, bool group_override = false);
705         void set_exclusive_input_active (boost::shared_ptr<RouteList> rt, bool onoff, bool flip_others=false);
706
707         PBD::Signal1<void,bool> SoloActive;
708         PBD::Signal0<void> SoloChanged;
709         PBD::Signal0<void> IsolatedChanged;
710
711         /* monitor/master out */
712
713         void add_monitor_section ();
714         void reset_monitor_section ();
715         void remove_monitor_section ();
716
717         boost::shared_ptr<Route> monitor_out() const { return _monitor_out; }
718         boost::shared_ptr<Route> master_out() const { return _master_out; }
719
720         void globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool);
721         void globally_set_send_gains_from_track (boost::shared_ptr<Route> dest);
722         void globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest);
723         void globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest);
724         void add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders);
725         void add_internal_send (boost::shared_ptr<Route>, int, boost::shared_ptr<Route>);
726         void add_internal_send (boost::shared_ptr<Route>, boost::shared_ptr<Processor>, boost::shared_ptr<Route>);
727
728         static void set_disable_all_loaded_plugins (bool yn) {
729                 _disable_all_loaded_plugins = yn;
730         }
731         static bool get_disable_all_loaded_plugins() {
732                 return _disable_all_loaded_plugins;
733         }
734
735         uint32_t next_send_id();
736         uint32_t next_aux_send_id();
737         uint32_t next_return_id();
738         uint32_t next_insert_id();
739         void mark_send_id (uint32_t);
740         void mark_aux_send_id (uint32_t);
741         void mark_return_id (uint32_t);
742         void mark_insert_id (uint32_t);
743         void unmark_send_id (uint32_t);
744         void unmark_aux_send_id (uint32_t);
745         void unmark_return_id (uint32_t);
746         void unmark_insert_id (uint32_t);
747
748         /* s/w "RAID" management */
749
750         boost::optional<framecnt_t> available_capture_duration();
751
752         /* I/O bundles */
753
754         void add_bundle (boost::shared_ptr<Bundle>, bool emit_signal = true);
755         void remove_bundle (boost::shared_ptr<Bundle>);
756         boost::shared_ptr<Bundle> bundle_by_name (std::string) const;
757
758         PBD::Signal0<void> BundleAddedOrRemoved;
759
760         void midi_panic ();
761
762         /* History (for editors, mixers, UIs etc.) */
763
764         /** Undo some transactions.
765          * @param n Number of transactions to undo.
766          */
767         void undo (uint32_t n) {
768                 _history.undo (n);
769         }
770
771         void redo (uint32_t n) {
772                 _history.redo (n);
773         }
774
775         UndoHistory& history() { return _history; }
776
777         uint32_t undo_depth() const { return _history.undo_depth(); }
778         uint32_t redo_depth() const { return _history.redo_depth(); }
779         std::string next_undo() const { return _history.next_undo(); }
780         std::string next_redo() const { return _history.next_redo(); }
781
782         void begin_reversible_command (const std::string& cmd_name);
783         void begin_reversible_command (GQuark);
784         void abort_reversible_command ();
785         void commit_reversible_command (Command* cmd = 0);
786
787         void add_command (Command *const cmd) {
788                 assert (_current_trans);
789                 _current_trans->add_command (cmd);
790         }
791
792         /** @return The list of operations that are currently in progress */
793         std::list<GQuark> const & current_operations () {
794                 return _current_trans_quarks;
795         }
796
797         bool operation_in_progress (GQuark) const;
798
799         void add_commands (std::vector<Command*> const & cmds);
800
801         std::map<PBD::ID,PBD::StatefulDestructible*> registry;
802
803         // these commands are implemented in libs/ardour/session_command.cc
804         Command* memento_command_factory(XMLNode* n);
805         Command* stateful_diff_command_factory (XMLNode *);
806         void register_with_memento_command_factory(PBD::ID, PBD::StatefulDestructible*);
807
808         /* clicking */
809
810         boost::shared_ptr<IO> click_io() { return _click_io; }
811         boost::shared_ptr<Amp> click_gain() { return _click_gain; }
812
813         /* disk, buffer loads */
814
815         uint32_t playback_load ();
816         uint32_t capture_load ();
817
818         /* ranges */
819
820         void request_play_range (std::list<AudioRange>*, bool leave_rolling = false);
821         void request_cancel_play_range ();
822         bool get_play_range () const { return _play_range; }
823
824         void maybe_update_session_range (framepos_t, framepos_t);
825
826         /* buffers for gain and pan */
827
828         gain_t* gain_automation_buffer () const;
829         gain_t* trim_automation_buffer () const;
830         gain_t* send_gain_automation_buffer () const;
831         pan_t** pan_automation_buffer () const;
832
833         void ensure_buffer_set (BufferSet& buffers, const ChanCount& howmany);
834
835         /* VST support */
836
837         static int  vst_current_loading_id;
838         static const char* vst_can_do_strings[];
839         static const int vst_can_do_string_count;
840
841         static intptr_t vst_callback (
842                 AEffect* effect,
843                 int32_t opcode,
844                 int32_t index,
845                 intptr_t value,
846                 void* ptr,
847                 float opt
848                 );
849                         
850         static PBD::Signal0<void> SendFeedback;
851
852         /* Speakers */
853
854         boost::shared_ptr<Speakers> get_speakers ();
855
856         /* Controllables */
857
858         boost::shared_ptr<PBD::Controllable> controllable_by_id (const PBD::ID&);
859         boost::shared_ptr<PBD::Controllable> controllable_by_descriptor (const PBD::ControllableDescriptor&);
860
861         void add_controllable (boost::shared_ptr<PBD::Controllable>);
862         void remove_controllable (PBD::Controllable*);
863
864         boost::shared_ptr<PBD::Controllable> solo_cut_control() const;
865
866         SessionConfiguration config;
867
868         bool exporting () const {
869                 return _exporting;
870         }
871
872         bool bounce_processing() const {
873                 return _bounce_processing_active;
874         }
875
876         /* this is a private enum, but setup_enum_writer() needs it,
877            and i can't find a way to give that function
878            friend access. sigh.
879         */
880
881         enum PostTransportWork {
882                 PostTransportStop               = 0x1,
883                 PostTransportDuration           = 0x2,
884                 PostTransportLocate             = 0x4,
885                 PostTransportRoll               = 0x8,
886                 PostTransportAbort              = 0x10,
887                 PostTransportOverWrite          = 0x20,
888                 PostTransportSpeed              = 0x40,
889                 PostTransportAudition           = 0x80,
890                 PostTransportReverse            = 0x100,
891                 PostTransportInputChange        = 0x200,
892                 PostTransportCurveRealloc       = 0x400,
893                 PostTransportClearSubstate      = 0x800,
894                 PostTransportAdjustPlaybackBuffering  = 0x1000,
895                 PostTransportAdjustCaptureBuffering   = 0x2000
896         };
897
898         enum SlaveState {
899                 Stopped,
900                 Waiting,
901                 Running
902         };
903
904         SlaveState slave_state() const { return _slave_state; }
905         Slave* slave() const { return _slave; }
906
907         boost::shared_ptr<SessionPlaylists> playlists;
908
909         void send_mmc_locate (framepos_t);
910         void queue_full_time_code () { _send_timecode_update = true; }
911         void queue_song_position_pointer () { /* currently does nothing */ }
912
913         bool step_editing() const { return (_step_editors > 0); }
914
915         void request_suspend_timecode_transmission ();
916         void request_resume_timecode_transmission ();
917         bool timecode_transmission_suspended () const;
918
919         std::vector<std::string> source_search_path(DataType) const;
920         void ensure_search_path_includes (const std::string& path, DataType type);
921         void remove_dir_from_search_path (const std::string& path, DataType type);
922
923         std::list<std::string> unknown_processors () const;
924
925         /** Emitted when a feedback cycle has been detected within Ardour's signal
926             processing path.  Until it is fixed (by the user) some (unspecified)
927             routes will not be run.
928         */
929         static PBD::Signal0<void> FeedbackDetected;
930
931         /** Emitted when a graph sort has successfully completed, which means
932             that it has no feedback cycles.
933         */
934         static PBD::Signal0<void> SuccessfulGraphSort;
935
936         /* handlers can return an integer value:
937            0: config.set_audio_search_path() or config.set_midi_search_path() was used
938            to modify the search path and we should try to find it again.
939            1: quit entire session load
940            2: as 0, but don't ask about other missing files
941            3: don't ask about other missing files, and just mark this one missing
942            -1: just mark this one missing
943            any other value: as -1
944         */
945         static PBD::Signal3<int,Session*,std::string,DataType> MissingFile;
946
947         /** Emitted when the session wants Ardour to quit */
948         static PBD::Signal0<void> Quit;
949
950         /** Emitted when Ardour is asked to load a session in an older session
951          * format, and makes a backup copy.
952          */
953         static PBD::Signal2<void,std::string,std::string> VersionMismatch;
954
955         SceneChanger* scene_changer() const { return _scene_changer; }
956
957         boost::shared_ptr<Port> ltc_input_port() const;
958         boost::shared_ptr<Port> ltc_output_port() const;
959
960         boost::shared_ptr<IO> ltc_input_io() { return _ltc_input; }
961         boost::shared_ptr<IO> ltc_output_io() { return _ltc_output; }
962
963         MIDI::Port* midi_input_port () const;
964         MIDI::Port* midi_output_port () const;
965         MIDI::Port* mmc_output_port () const;
966         MIDI::Port* mmc_input_port () const;
967
968         MIDI::Port* scene_input_port () const;
969         MIDI::Port* scene_output_port () const;
970
971         boost::shared_ptr<MidiPort> scene_in () const;
972         boost::shared_ptr<MidiPort> scene_out () const;
973         
974         boost::shared_ptr<MidiPort> midi_clock_output_port () const;
975         boost::shared_ptr<MidiPort> midi_clock_input_port () const;
976         boost::shared_ptr<MidiPort> mtc_output_port () const;
977         boost::shared_ptr<MidiPort> mtc_input_port () const;
978     
979         MIDI::MachineControl& mmc() { return *_mmc; }
980
981   protected:
982         friend class AudioEngine;
983         void set_block_size (pframes_t nframes);
984         void set_frame_rate (framecnt_t nframes);
985         void reconnect_existing_routes (bool withLock, bool reconnect_master = true, bool reconnect_inputs = true, bool reconnect_outputs = true);
986
987   protected:
988         friend class Route;
989         void schedule_curve_reallocation ();
990         void update_latency_compensation (bool force = false);
991
992   private:
993         int  create (const std::string& mix_template, BusProfile*);
994         void destroy ();
995
996         enum SubState {
997                 PendingDeclickIn      = 0x1,  ///< pending de-click fade-in for start
998                 PendingDeclickOut     = 0x2,  ///< pending de-click fade-out for stop
999                 StopPendingCapture    = 0x4,
1000                 PendingLoopDeclickIn  = 0x8,  ///< pending de-click fade-in at the start of a loop
1001                 PendingLoopDeclickOut = 0x10, ///< pending de-click fade-out at the end of a loop
1002                 PendingLocate         = 0x20,
1003         };
1004
1005         /* stuff used in process() should be close together to
1006            maximise cache hits
1007         */
1008
1009         typedef void (Session::*process_function_type)(pframes_t);
1010
1011         AudioEngine&            _engine;
1012         mutable gint             processing_prohibited;
1013         process_function_type    process_function;
1014         process_function_type    last_process_function;
1015         bool                    _bounce_processing_active;
1016         bool                     waiting_for_sync_offset;
1017         framecnt_t              _base_frame_rate;
1018         framecnt_t              _current_frame_rate;  //this includes video pullup offset
1019         framecnt_t              _nominal_frame_rate;  //ignores audioengine setting, "native" SR
1020         int                      transport_sub_state;
1021         mutable gint            _record_status;
1022         framepos_t              _transport_frame;
1023         Location*               _session_range_location; ///< session range, or 0 if there is nothing in the session yet
1024         Slave*                  _slave;
1025         bool                    _silent;
1026
1027         // varispeed playback
1028         double                  _transport_speed;
1029         double                  _default_transport_speed;
1030         double                  _last_transport_speed;
1031         double                  _signalled_varispeed;
1032         double                  _target_transport_speed;
1033         CubicInterpolation       interpolation;
1034
1035         bool                     auto_play_legal;
1036         framepos_t              _last_slave_transport_frame;
1037         framecnt_t               maximum_output_latency;
1038         framepos_t              _requested_return_frame;
1039         pframes_t                current_block_size;
1040         framecnt_t              _worst_output_latency;
1041         framecnt_t              _worst_input_latency;
1042         framecnt_t              _worst_track_latency;
1043         bool                    _have_captured;
1044         bool                    _non_soloed_outs_muted;
1045         uint32_t                _listen_cnt;
1046         uint32_t                _solo_isolated_cnt;
1047         bool                    _writable;
1048         bool                    _was_seamless;
1049         bool                    _under_nsm_control;
1050         unsigned int            _xrun_count;
1051
1052         void initialize_latencies ();
1053         void set_worst_io_latencies ();
1054         void set_worst_playback_latency ();
1055         void set_worst_capture_latency ();
1056         void set_worst_io_latencies_x (IOChange, void *) {
1057                 set_worst_io_latencies ();
1058         }
1059         void post_capture_latency ();
1060         void post_playback_latency ();
1061
1062         void update_latency_compensation_proxy (void* ignored);
1063
1064         void ensure_buffers (ChanCount howmany = ChanCount::ZERO);
1065
1066         void process_scrub          (pframes_t);
1067         void process_without_events (pframes_t);
1068         void process_with_events    (pframes_t);
1069         void process_audition       (pframes_t);
1070         int  process_export         (pframes_t);
1071         int  process_export_fw      (pframes_t);
1072
1073         void block_processing() { g_atomic_int_set (&processing_prohibited, 1); }
1074         void unblock_processing() { g_atomic_int_set (&processing_prohibited, 0); }
1075         bool processing_blocked() const { return g_atomic_int_get (&processing_prohibited); }
1076
1077         static const framecnt_t bounce_chunk_size;
1078
1079         /* slave tracking */
1080
1081         static const int delta_accumulator_size = 25;
1082         int delta_accumulator_cnt;
1083         int32_t delta_accumulator[delta_accumulator_size];
1084         int32_t average_slave_delta;
1085         int  average_dir;
1086         bool have_first_delta_accumulator;
1087
1088         SlaveState _slave_state;
1089         framepos_t slave_wait_end;
1090
1091         void reset_slave_state ();
1092         bool follow_slave (pframes_t);
1093         void calculate_moving_average_of_slave_delta (int dir, framecnt_t this_delta);
1094         void track_slave_state (float slave_speed, framepos_t slave_transport_frame, framecnt_t this_delta);
1095         void follow_slave_silently (pframes_t nframes, float slave_speed);
1096
1097         void switch_to_sync_source (SyncSource); /* !RT context */
1098         void drop_sync_source ();  /* !RT context */
1099         void use_sync_source (Slave*); /* RT context */
1100
1101         bool post_export_sync;
1102         framepos_t post_export_position;
1103
1104         bool _exporting;
1105         bool _export_started;
1106         bool _export_rolling;
1107
1108         boost::shared_ptr<ExportHandler> export_handler;
1109         boost::shared_ptr<ExportStatus>  export_status;
1110
1111         int  pre_export ();
1112         int  stop_audio_export ();
1113         void finalize_audio_export ();
1114         void finalize_export_internal (bool stop_freewheel);
1115         bool _pre_export_mmc_enabled;
1116
1117         PBD::ScopedConnection export_freewheel_connection;
1118
1119         void get_track_statistics ();
1120         int  process_routes (pframes_t, bool& need_butler);
1121         int  silent_process_routes (pframes_t, bool& need_butler);
1122
1123         /** @return 1 if there is a pending declick fade-in,
1124             -1 if there is a pending declick fade-out,
1125             0 if there is no pending declick.
1126         */
1127         int get_transport_declick_required () {
1128                 if (transport_sub_state & PendingDeclickIn) {
1129                         transport_sub_state &= ~PendingDeclickIn;
1130                         return 1;
1131                 } else if (transport_sub_state & PendingDeclickOut) {
1132                         /* XXX: not entirely sure why we don't clear this */
1133                         return -1;
1134                 } else if (transport_sub_state & PendingLoopDeclickOut) {
1135                         /* Return the declick out first ... */
1136                         transport_sub_state &= ~PendingLoopDeclickOut;
1137                         return -1;
1138                 } else if (transport_sub_state & PendingLoopDeclickIn) {
1139                         /* ... then the declick in on the next call */
1140                         transport_sub_state &= ~PendingLoopDeclickIn;
1141                         return 1;
1142                 } else {
1143                         return 0;
1144                 }
1145         }
1146
1147         bool maybe_stop (framepos_t limit);
1148         bool maybe_sync_start (pframes_t &);
1149
1150         void check_declick_out ();
1151
1152         std::string             _path;
1153         std::string             _name;
1154         bool                    _is_new;
1155         bool                    _send_qf_mtc;
1156         /** Number of process frames since the last MTC output (when sending MTC); used to
1157          *  know when to send full MTC messages every so often.
1158          */
1159         pframes_t               _pframes_since_last_mtc;
1160         bool                     session_midi_feedback;
1161         bool                     play_loop;
1162         bool                     loop_changing;
1163         framepos_t               last_loopend;
1164
1165         boost::scoped_ptr<SessionDirectory> _session_dir;
1166
1167         void hookup_io ();
1168         void graph_reordered ();
1169
1170         /** current snapshot name, without the .ardour suffix */
1171         std::string _current_snapshot_name;
1172
1173         XMLTree*         state_tree;
1174         bool             state_was_pending;
1175         StateOfTheState _state_of_the_state;
1176
1177         friend class    StateProtector;
1178         gint            _suspend_save; /* atomic */
1179         volatile bool   _save_queued;
1180         Glib::Threads::Mutex save_state_lock;
1181
1182         int      load_options (const XMLNode&);
1183         int      load_state (std::string snapshot_name);
1184
1185         framepos_t _last_roll_location;
1186         /** the session frame time at which we last rolled, located, or changed transport direction */
1187         framepos_t _last_roll_or_reversal_location;
1188         framepos_t _last_record_location;
1189
1190         bool              pending_locate_roll;
1191         framepos_t        pending_locate_frame;
1192         bool              pending_locate_flush;
1193         bool              pending_abort;
1194         bool              pending_auto_loop;
1195
1196         Butler* _butler;
1197
1198         static const PostTransportWork ProcessCannotProceedMask =
1199                 PostTransportWork (
1200                         PostTransportInputChange|
1201                         PostTransportSpeed|
1202                         PostTransportReverse|
1203                         PostTransportCurveRealloc|
1204                         PostTransportAudition|
1205                         PostTransportLocate|
1206                         PostTransportStop|
1207                         PostTransportClearSubstate);
1208
1209         gint _post_transport_work; /* accessed only atomic ops */
1210         PostTransportWork post_transport_work() const        { return (PostTransportWork) g_atomic_int_get (const_cast<gint*>(&_post_transport_work)); }
1211         void set_post_transport_work (PostTransportWork ptw) { g_atomic_int_set (&_post_transport_work, (gint) ptw); }
1212         void add_post_transport_work (PostTransportWork ptw);
1213
1214         void schedule_playback_buffering_adjustment ();
1215         void schedule_capture_buffering_adjustment ();
1216
1217         uint32_t    cumulative_rf_motion;
1218         uint32_t    rf_scale;
1219
1220         void set_rf_speed (float speed);
1221         void reset_rf_scale (framecnt_t frames_moved);
1222
1223         Locations*       _locations;
1224         void location_added (Location*);
1225         void location_removed (Location*);
1226         void locations_changed ();
1227         void _locations_changed (const Locations::LocationList&);
1228
1229         void update_skips (Location*, bool consolidate);
1230         void update_marks (Location* loc);
1231         void update_loop (Location* loc);
1232         void consolidate_skips (Location*);
1233         void sync_locations_to_skips ();
1234         void _sync_locations_to_skips ();
1235     
1236         PBD::ScopedConnectionList skip_update_connections;
1237         bool _ignore_skips_updates;
1238
1239         PBD::ScopedConnectionList punch_connections;
1240         void             auto_punch_start_changed (Location *);
1241         void             auto_punch_end_changed (Location *);
1242         void             auto_punch_changed (Location *);
1243
1244         PBD::ScopedConnectionList loop_connections;
1245         void             auto_loop_changed (Location *);
1246         void             auto_loop_declick_range (Location *, framepos_t &, framepos_t &);
1247
1248         int  ensure_engine (uint32_t desired_sample_rate);
1249         void pre_engine_init (std::string path);
1250         int  post_engine_init ();
1251         int  immediately_post_engine ();
1252         void remove_empty_sounds ();
1253
1254         void setup_midi_control ();
1255         int  midi_read (MIDI::Port *);
1256
1257         void enable_record ();
1258
1259         void increment_transport_position (framecnt_t val) {
1260                 if (max_framepos - val < _transport_frame) {
1261                         _transport_frame = max_framepos;
1262                 } else {
1263                         _transport_frame += val;
1264                 }
1265         }
1266
1267         void decrement_transport_position (framecnt_t val) {
1268                 if (val < _transport_frame) {
1269                         _transport_frame -= val;
1270                 } else {
1271                         _transport_frame = 0;
1272                 }
1273         }
1274
1275         void post_transport_motion ();
1276         static void *session_loader_thread (void *arg);
1277
1278         void *do_work();
1279
1280         /* Signal Forwarding */
1281         void emit_route_signals ();
1282         void emit_thread_run ();
1283         static void *emit_thread (void *);
1284         void emit_thread_start ();
1285         void emit_thread_terminate ();
1286
1287         pthread_t       _rt_emit_thread;
1288         bool            _rt_thread_active;
1289
1290         pthread_mutex_t _rt_emit_mutex;
1291         pthread_cond_t  _rt_emit_cond;
1292         bool            _rt_emit_pending;
1293
1294
1295         /* SessionEventManager interface */
1296
1297         void process_event (SessionEvent*);
1298         void set_next_event ();
1299         void cleanup_event (SessionEvent*,int);
1300
1301         /* MIDI Machine Control */
1302
1303         void spp_start ();
1304         void spp_continue ();
1305         void spp_stop ();
1306
1307         void mmc_deferred_play (MIDI::MachineControl &);
1308         void mmc_stop (MIDI::MachineControl &);
1309         void mmc_step (MIDI::MachineControl &, int);
1310         void mmc_pause (MIDI::MachineControl &);
1311         void mmc_record_pause (MIDI::MachineControl &);
1312         void mmc_record_strobe (MIDI::MachineControl &);
1313         void mmc_record_exit (MIDI::MachineControl &);
1314         void mmc_track_record_status (MIDI::MachineControl &, uint32_t track, bool enabled);
1315         void mmc_fast_forward (MIDI::MachineControl &);
1316         void mmc_rewind (MIDI::MachineControl &);
1317         void mmc_locate (MIDI::MachineControl &, const MIDI::byte *);
1318         void mmc_shuttle (MIDI::MachineControl &mmc, float speed, bool forw);
1319         void mmc_record_enable (MIDI::MachineControl &mmc, size_t track, bool enabled);
1320
1321         struct timeval last_mmc_step;
1322         double step_speed;
1323
1324         typedef boost::function<bool()> MidiTimeoutCallback;
1325         typedef std::list<MidiTimeoutCallback> MidiTimeoutList;
1326
1327         MidiTimeoutList midi_timeouts;
1328         bool mmc_step_timeout ();
1329         void send_immediate_mmc (MIDI::MachineControlCommand);
1330
1331         MIDI::byte mtc_msg[16];
1332         MIDI::byte mtc_timecode_bits;   /* encoding of SMTPE type for MTC */
1333         MIDI::byte midi_msg[16];
1334         double outbound_mtc_timecode_frame;
1335         Timecode::Time transmitting_timecode_time;
1336         int next_quarter_frame_to_send;
1337
1338         double _frames_per_timecode_frame; /* has to be floating point because of drop frame */
1339         framecnt_t _frames_per_hour;
1340         framecnt_t _timecode_frames_per_hour;
1341
1342         /* cache the most-recently requested time conversions. This helps when we
1343          * have multiple clocks showing the same time (e.g. the transport frame) */
1344         bool last_timecode_valid;
1345         framepos_t last_timecode_when;
1346         Timecode::Time last_timecode;
1347
1348         bool _send_timecode_update; ///< Flag to send a full frame (Timecode) MTC message this cycle
1349
1350         int send_midi_time_code_for_cycle (framepos_t, framepos_t, pframes_t nframes);
1351
1352         LTCEncoder*       ltc_encoder;
1353         ltcsnd_sample_t*  ltc_enc_buf;
1354
1355         Timecode::TimecodeFormat ltc_enc_tcformat;
1356         int32_t           ltc_buf_off;
1357         int32_t           ltc_buf_len;
1358
1359         double            ltc_speed;
1360         int32_t           ltc_enc_byte;
1361         framepos_t        ltc_enc_pos;
1362         double            ltc_enc_cnt;
1363         framepos_t        ltc_enc_off;
1364         bool              restarting;
1365         framepos_t        ltc_prev_cycle;
1366
1367         framepos_t        ltc_timecode_offset;
1368         bool              ltc_timecode_negative_offset;
1369
1370         LatencyRange      ltc_out_latency;
1371
1372         void ltc_tx_initialize();
1373         void ltc_tx_cleanup();
1374         void ltc_tx_reset();
1375         void ltc_tx_resync_latency();
1376         void ltc_tx_recalculate_position();
1377         void ltc_tx_parse_offset();
1378         void ltc_tx_send_time_code_for_cycle (framepos_t, framepos_t, double, double, pframes_t nframes);
1379
1380         void reset_record_status ();
1381
1382         int no_roll (pframes_t nframes);
1383         int fail_roll (pframes_t nframes);
1384
1385         bool non_realtime_work_pending() const { return static_cast<bool>(post_transport_work()); }
1386         bool process_can_proceed() const { return !(post_transport_work() & ProcessCannotProceedMask); }
1387
1388         MidiControlUI* midi_control_ui;
1389
1390         int           start_midi_thread ();
1391
1392         void set_play_loop (bool yn, double speed);
1393         void unset_play_loop ();
1394         void overwrite_some_buffers (Track *);
1395         void flush_all_inserts ();
1396         int  micro_locate (framecnt_t distance);
1397         void locate (framepos_t, bool with_roll, bool with_flush, bool with_loop=false, bool force=false, bool with_mmc=true);
1398         void start_locate (framepos_t, bool with_roll, bool with_flush, bool with_loop=false, bool force=false);
1399         void force_locate (framepos_t frame, bool with_roll = false);
1400         void set_track_speed (Track *, double speed);
1401         void set_transport_speed (double speed, framepos_t destination_frame, bool abort = false, bool clear_state = false, bool as_default = false);
1402         void stop_transport (bool abort = false, bool clear_state = false);
1403         void start_transport ();
1404         void realtime_stop (bool abort, bool clear_state);
1405         void realtime_locate ();
1406         void non_realtime_start_scrub ();
1407         void non_realtime_set_speed ();
1408         void non_realtime_locate ();
1409         void non_realtime_stop (bool abort, int entry_request_count, bool& finished);
1410         void non_realtime_overwrite (int entry_request_count, bool& finished);
1411         void post_transport ();
1412         void engine_halted ();
1413         void xrun_recovery ();
1414         void set_track_loop (bool);
1415         
1416         /* These are synchronous and so can only be called from within the process
1417          * cycle
1418          */
1419
1420         int  send_full_time_code (framepos_t, pframes_t nframes);
1421         void send_song_position_pointer (framepos_t);
1422
1423         TempoMap    *_tempo_map;
1424         void          tempo_map_changed (const PBD::PropertyChange&);
1425
1426         /* edit/mix groups */
1427
1428         int load_route_groups (const XMLNode&, int);
1429
1430         std::list<RouteGroup *> _route_groups;
1431         RouteGroup*             _all_route_group;
1432
1433         /* routes stuff */
1434
1435         boost::shared_ptr<Graph> _process_graph;
1436
1437         SerializedRCUManager<RouteList>  routes;
1438
1439         void add_routes (RouteList&, bool input_auto_connect, bool output_auto_connect, bool save);
1440         void add_routes_inner (RouteList&, bool input_auto_connect, bool output_auto_connect);
1441         bool _adding_routes_in_progress;
1442         uint32_t destructive_index;
1443
1444         boost::shared_ptr<Route> XMLRouteFactory (const XMLNode&, int);
1445         boost::shared_ptr<Route> XMLRouteFactory_2X (const XMLNode&, int);
1446
1447         void route_processors_changed (RouteProcessorChange);
1448
1449         bool find_route_name (std::string const &, uint32_t& id, char* name, size_t name_len, bool);
1450         void count_existing_track_channels (ChanCount& in, ChanCount& out);
1451         void auto_connect_route (boost::shared_ptr<Route> route, ChanCount& existing_inputs, ChanCount& existing_outputs,
1452                                  bool with_lock, bool connect_inputs = true,
1453                                  ChanCount input_start = ChanCount (), ChanCount output_start = ChanCount ());
1454         void midi_output_change_handler (IOChange change, void* /*src*/, boost::weak_ptr<Route> midi_track);
1455
1456         /* track numbering */
1457
1458         void reassign_track_numbers ();
1459         uint32_t _track_number_decimals;
1460
1461         /* mixer stuff */
1462
1463         bool solo_update_disabled;
1464
1465         void route_listen_changed (void *src, boost::weak_ptr<Route>);
1466         void route_mute_changed (void *src);
1467         void route_solo_changed (bool self_solo_change, void *src, boost::weak_ptr<Route>);
1468         void route_solo_isolated_changed (void *src, boost::weak_ptr<Route>);
1469         void update_route_solo_state (boost::shared_ptr<RouteList> r = boost::shared_ptr<RouteList>());
1470
1471         void listen_position_changed ();
1472         void solo_control_mode_changed ();
1473
1474         /* REGION MANAGEMENT */
1475
1476         mutable Glib::Threads::Mutex region_lock;
1477
1478         int load_regions (const XMLNode& node);
1479         int load_compounds (const XMLNode& node);
1480
1481         void route_added_to_route_group (RouteGroup *, boost::weak_ptr<Route>);
1482         void route_removed_from_route_group (RouteGroup *, boost::weak_ptr<Route>);
1483         void route_group_property_changed (RouteGroup *);
1484
1485         /* SOURCES */
1486
1487         mutable Glib::Threads::Mutex source_lock;
1488
1489   public:
1490         typedef std::map<PBD::ID,boost::shared_ptr<Source> > SourceMap;
1491
1492   private:
1493         void reset_write_sources (bool mark_write_complete, bool force = false);
1494         SourceMap sources;
1495
1496
1497   private:
1498         int load_sources (const XMLNode& node);
1499         XMLNode& get_sources_as_xml ();
1500
1501         boost::shared_ptr<Source> XMLSourceFactory (const XMLNode&);
1502
1503         /* PLAYLISTS */
1504
1505         void remove_playlist (boost::weak_ptr<Playlist>);
1506         void track_playlist_changed (boost::weak_ptr<Track>);
1507         void playlist_region_added (boost::weak_ptr<Region>);
1508         void playlist_ranges_moved (std::list<Evoral::RangeMove<framepos_t> > const &);
1509         void playlist_regions_extended (std::list<Evoral::Range<framepos_t> > const &);
1510
1511         /* CURVES and AUTOMATION LISTS */
1512         std::map<PBD::ID, AutomationList*> automation_lists;
1513
1514         /* DEFAULT FADE CURVES */
1515
1516         float default_fade_steepness;
1517         float default_fade_msecs;
1518
1519         /* AUDITIONING */
1520
1521         boost::shared_ptr<Auditioner> auditioner;
1522         void set_audition (boost::shared_ptr<Region>);
1523         void non_realtime_set_audition ();
1524         boost::shared_ptr<Region> pending_audition_region;
1525
1526         /* EXPORT */
1527
1528         /* FLATTEN */
1529
1530         int flatten_one_track (AudioTrack&, framepos_t start, framecnt_t cnt);
1531
1532         /* INSERT AND SEND MANAGEMENT */
1533
1534         boost::dynamic_bitset<uint32_t> send_bitset;
1535         boost::dynamic_bitset<uint32_t> aux_send_bitset;
1536         boost::dynamic_bitset<uint32_t> return_bitset;
1537         boost::dynamic_bitset<uint32_t> insert_bitset;
1538
1539         /* S/W RAID */
1540
1541         struct space_and_path {
1542                 uint32_t blocks;     ///< 4kB blocks
1543                 bool blocks_unknown; ///< true if blocks is unknown
1544                 std::string path;
1545
1546                 space_and_path ()
1547                         : blocks (0)
1548                         , blocks_unknown (true)
1549                 {}
1550         };
1551
1552         struct space_and_path_ascending_cmp {
1553                 bool operator() (space_and_path a, space_and_path b) {
1554                         if (a.blocks_unknown != b.blocks_unknown) {
1555                                 return !a.blocks_unknown;
1556                         }
1557                         return a.blocks > b.blocks;
1558                 }
1559         };
1560
1561         void setup_raid_path (std::string path);
1562
1563         std::vector<space_and_path> session_dirs;
1564         std::vector<space_and_path>::iterator last_rr_session_dir;
1565         uint32_t _total_free_4k_blocks;
1566         /** If this is true, _total_free_4k_blocks is not definite,
1567             as one or more of the session directories' filesystems
1568             could not report free space.
1569         */
1570         bool _total_free_4k_blocks_uncertain;
1571         Glib::Threads::Mutex space_lock;
1572
1573         bool no_questions_about_missing_files;
1574
1575         std::string get_best_session_directory_for_new_audio ();
1576
1577         mutable gint _playback_load;
1578         mutable gint _capture_load;
1579
1580         /* I/O bundles */
1581
1582         SerializedRCUManager<BundleList> _bundles;
1583         XMLNode* _bundle_xml_node;
1584         int load_bundles (XMLNode const &);
1585
1586         UndoHistory      _history;
1587         /** current undo transaction, or 0 */
1588         UndoTransaction* _current_trans;
1589         /** GQuarks to describe the reversible commands that are currently in progress.
1590          *  These may be nested, in which case more recently-started commands are toward
1591          *  the front of the list.
1592          */
1593         std::list<GQuark> _current_trans_quarks;
1594
1595         int  backend_sync_callback (TransportState, framepos_t);
1596
1597         void process_rtop (SessionEvent*);
1598
1599         void  update_latency (bool playback);
1600
1601         XMLNode& state(bool);
1602
1603         /* click track */
1604         typedef std::list<Click*> Clicks;
1605         Clicks                  clicks;
1606         bool                   _clicking;
1607         boost::shared_ptr<IO>  _click_io;
1608         boost::shared_ptr<Amp> _click_gain;
1609         Sample*                 click_data;
1610         Sample*                 click_emphasis_data;
1611         framecnt_t              click_length;
1612         framecnt_t              click_emphasis_length;
1613         mutable Glib::Threads::RWLock    click_lock;
1614
1615         static const Sample     default_click[];
1616         static const framecnt_t default_click_length;
1617         static const Sample     default_click_emphasis[];
1618         static const framecnt_t default_click_emphasis_length;
1619
1620         Click *get_click();
1621         framepos_t _clicks_cleared;
1622         void   setup_click_sounds (int which);
1623         void   setup_click_sounds (Sample**, Sample const *, framecnt_t*, framecnt_t, std::string const &);
1624         void   clear_clicks ();
1625         void   click (framepos_t start, framecnt_t nframes);
1626
1627         std::vector<Route*> master_outs;
1628
1629         /* range playback */
1630
1631         std::list<AudioRange> current_audio_range;
1632         bool _play_range;
1633         void set_play_range (std::list<AudioRange>&, bool leave_rolling);
1634         void unset_play_range ();
1635
1636         /* main outs */
1637         uint32_t main_outs;
1638
1639         boost::shared_ptr<Route> _master_out;
1640         boost::shared_ptr<Route> _monitor_out;
1641
1642         void auto_connect_master_bus ();
1643
1644         /* Windows VST support */
1645
1646         long _windows_vst_callback (
1647                 WindowsVSTPlugin*,
1648                 long opcode,
1649                 long index,
1650                 long value,
1651                 void* ptr,
1652                 float opt
1653                 );
1654
1655         int find_all_sources (std::string path, std::set<std::string>& result);
1656         int find_all_sources_across_snapshots (std::set<std::string>& result, bool exclude_this_snapshot);
1657
1658         typedef std::set<boost::shared_ptr<PBD::Controllable> > Controllables;
1659         Glib::Threads::Mutex controllables_lock;
1660         Controllables controllables;
1661
1662         boost::shared_ptr<PBD::Controllable> _solo_cut_control;
1663
1664         void reset_native_file_format();
1665         bool first_file_data_format_reset;
1666         bool first_file_header_format_reset;
1667
1668         void config_changed (std::string, bool);
1669
1670         XMLNode& get_control_protocol_state ();
1671
1672         void set_history_depth (uint32_t depth);
1673
1674         static bool _disable_all_loaded_plugins;
1675
1676         mutable bool have_looped; ///< Used in ::audible_frame(*)
1677
1678         void update_have_rec_enabled_track ();
1679         gint _have_rec_enabled_track;
1680
1681         static int ask_about_playlist_deletion (boost::shared_ptr<Playlist>);
1682
1683         /* realtime "apply to set of routes" operations */
1684         template<typename T> SessionEvent*
1685                 get_rt_event (boost::shared_ptr<RouteList> rl, T targ, SessionEvent::RTeventCallback after, bool group_override,
1686                               void (Session::*method) (boost::shared_ptr<RouteList>, T, bool)) {
1687                 SessionEvent* ev = new SessionEvent (SessionEvent::RealTimeOperation, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
1688                 ev->rt_slot = boost::bind (method, this, rl, targ, group_override);
1689                 ev->rt_return = after;
1690                 ev->event_loop = PBD::EventLoop::get_event_loop_for_thread ();
1691                 
1692                 return ev;
1693         }
1694
1695         void rt_cancel_solo_after_disconnect (boost::shared_ptr<RouteList>, bool upstream, bool /* ignored*/ );
1696         void rt_set_solo (boost::shared_ptr<RouteList>, bool yn, bool group_override);
1697         void rt_set_just_one_solo (boost::shared_ptr<RouteList>, bool yn, bool /* ignored*/ );
1698         void rt_set_mute (boost::shared_ptr<RouteList>, bool yn, bool group_override);
1699         void rt_set_listen (boost::shared_ptr<RouteList>, bool yn, bool group_override);
1700         void rt_set_solo_isolated (boost::shared_ptr<RouteList>, bool yn, bool group_override);
1701         void rt_set_record_enabled (boost::shared_ptr<RouteList>, bool yn, bool group_override);
1702         void rt_set_monitoring (boost::shared_ptr<RouteList>, MonitorChoice, bool group_override);
1703
1704         /** temporary list of Diskstreams used only during load of 2.X sessions */
1705         std::list<boost::shared_ptr<Diskstream> > _diskstreams_2X;
1706
1707         void add_session_range_location (framepos_t, framepos_t);
1708
1709         void setup_midi_machine_control ();
1710
1711         void step_edit_status_change (bool);
1712         uint32_t _step_editors;
1713
1714         /** true if timecode transmission by the transport is suspended, otherwise false */
1715         mutable gint _suspend_timecode_transmission;
1716
1717         void update_locations_after_tempo_map_change (const Locations::LocationList &);
1718
1719         void start_time_changed (framepos_t);
1720         void end_time_changed (framepos_t);
1721
1722         void set_track_monitor_input_status (bool);
1723         framepos_t compute_stop_limit () const;
1724
1725         boost::shared_ptr<Speakers> _speakers;
1726         void load_nested_sources (const XMLNode& node);
1727
1728         /** The directed graph of routes that is currently being used for audio processing
1729             and solo/mute computations.
1730         */
1731         GraphEdges _current_route_graph;
1732
1733         uint32_t next_control_id () const;
1734         int32_t _order_hint;
1735         bool ignore_route_processor_changes;
1736
1737         MidiClockTicker* midi_clock;
1738
1739         boost::shared_ptr<IO>   _ltc_input;
1740         boost::shared_ptr<IO>   _ltc_output;
1741
1742         void reconnect_ltc_input ();
1743         void reconnect_ltc_output ();
1744
1745         /* Scene Changing */
1746         SceneChanger* _scene_changer;
1747         
1748         /* persistent, non-track related MIDI ports */
1749         MidiPortManager* _midi_ports;
1750         MIDI::MachineControl* _mmc;
1751         
1752         void setup_ltc ();
1753         void setup_click ();
1754         void setup_click_state (const XMLNode*);
1755         void setup_bundles ();
1756         
1757         void save_as_bring_callback (uint32_t, uint32_t, std::string);
1758
1759         static int get_session_info_from_path (XMLTree& state_tree, const std::string& xmlpath);
1760 };
1761
1762
1763 } // namespace ARDOUR
1764
1765 #endif /* __ardour_session_h__ */