Add some comments.
[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 <string>
24 #include <list>
25 #include <map>
26 #include <vector>
27 #include <set>
28 #include <stack>
29
30 #include <boost/weak_ptr.hpp>
31 #include <boost/dynamic_bitset.hpp>
32
33 #include <stdint.h>
34
35 #include <sndfile.h>
36
37 #include <glibmm/thread.h>
38
39 #include <pbd/error.h>
40 #include <pbd/undo.h>
41 #include <pbd/pool.h>
42 #include <pbd/rcu.h>
43 #include <pbd/statefuldestructible.h>
44
45 #include <midi++/types.h>
46 #include <midi++/mmc.h>
47
48 #include <pbd/stateful.h> 
49 #include <pbd/destructible.h> 
50
51 #include <ardour/ardour.h>
52 #include <ardour/configuration.h>
53 #include <ardour/location.h>
54 #include <ardour/gain.h>
55 #include <ardour/io.h>
56
57 #include <ardour/smpte.h>
58
59 class XMLTree;
60 class XMLNode;
61 class AEffect;
62
63 namespace MIDI {
64         class Port;
65 }
66
67 namespace PBD {
68         class Controllable;
69 }
70
71 namespace ARDOUR {
72
73 class Port;
74 class AudioEngine;
75 class Slave;
76 class Diskstream;
77 class Route;
78 class AuxInput;
79 class Source;
80 class AudioSource;
81 class BufferSet;
82
83 class Diskstream;
84 class AudioDiskstream;
85 class MidiDiskstream;
86 class AudioFileSource;
87 class MidiSource;
88 class Auditioner;
89 class Insert;
90 class Send;
91 class Redirect;
92 class PortInsert;
93 class PluginInsert;
94 class Connection;
95 class TempoMap;
96 class AudioTrack;
97 class NamedSelection;
98 class AudioRegion;
99
100 class Region;
101 class Playlist;
102 class VSTPlugin;
103 class ControlProtocolInfo;
104
105 class MidiTrack;
106 class MidiRegion;
107 class SMFSource;
108
109 struct AudioExportSpecification;
110 struct RouteGroup;
111
112 using std::vector;
113 using std::string;
114 using std::map;
115 using std::set;
116
117 class Session : public PBD::StatefulDestructible
118 {
119   private:
120         typedef std::pair<boost::weak_ptr<Route>,bool> RouteBooleanState;
121         typedef vector<RouteBooleanState> GlobalRouteBooleanState;
122         typedef std::pair<boost::weak_ptr<Route>,MeterPoint> RouteMeterState;
123         typedef vector<RouteMeterState> GlobalRouteMeterState;
124
125   public:
126         enum RecordState {
127                 Disabled = 0,
128                 Enabled = 1,
129                 Recording = 2
130         };
131
132         struct Event {
133             enum Type {
134                     SetTransportSpeed,
135                     SetDiskstreamSpeed,
136                     Locate,
137                     LocateRoll,
138                     SetLoop,
139                     PunchIn,
140                     PunchOut,
141                     RangeStop,
142                     RangeLocate,
143                     Overwrite,
144                     SetSlaveSource,
145                     Audition,
146                     InputConfigurationChange,
147                     SetAudioRange,
148                     SetPlayRange,
149                     
150                     /* only one of each of these events
151                        can be queued at any one time
152                     */
153
154                     StopOnce,
155                     AutoLoop
156             };
157
158             enum Action {
159                     Add,
160                     Remove,
161                     Replace,
162                     Clear
163             };
164                 
165                 Type           type;
166             Action         action;
167             nframes_t action_frame;
168             nframes_t target_frame;
169             float          speed;
170
171             union {
172                         void*                ptr;
173                         bool                 yes_or_no;
174                         SlaveSource slave;
175                         Route*               route;
176             };
177
178             boost::shared_ptr<Region>     region;
179
180             list<AudioRange>     audio_range;
181             list<MusicRange>     music_range;
182
183             Event(Type t, Action a, nframes_t when, nframes_t where, float spd, bool yn = false)
184                     : type (t), 
185                       action (a),
186                       action_frame (when),
187                       target_frame (where),
188                       speed (spd),
189                       yes_or_no (yn) {}
190
191             void set_ptr (void* p) { 
192                     ptr = p;
193             }
194
195             bool before (const Event& other) const {
196                     return action_frame < other.action_frame;
197             }
198
199             bool after (const Event& other) const {
200                     return action_frame > other.action_frame;
201             }
202
203             static bool compare (const Event *e1, const Event *e2) {
204                     return e1->before (*e2);
205             }
206
207             void *operator new (size_t ignored) {
208                     return pool.alloc ();
209             }
210
211             void operator delete(void *ptr, size_t size) {
212                     pool.release (ptr);
213             }
214
215             static const nframes_t Immediate = 0;
216
217          private:
218             static MultiAllocSingleReleasePool pool;
219         };
220
221         /* creating from an XML file */
222
223         Session (AudioEngine&,
224                  string fullpath,
225                  string snapshot_name,
226                  string* mix_template = 0);
227
228         /* creating a new Session */
229
230         Session (AudioEngine&,
231                  string fullpath,
232                  string snapshot_name,
233                  AutoConnectOption input_auto_connect,
234                  AutoConnectOption output_auto_connect,
235                  uint32_t control_out_channels,
236                  uint32_t master_out_channels,
237                  uint32_t n_physical_in,
238                  uint32_t n_physical_out,
239                  nframes_t initial_length);
240         
241         virtual ~Session ();
242
243
244         static int find_session (string str, string& path, string& snapshot, bool& isnew);
245         
246         string path() const { return _path; }
247         string name() const { return _name; }
248         string snap_name() const { return _current_snapshot_name; }
249         string raid_path () const;
250         string export_dir () const;
251
252         void set_snap_name ();
253
254         void set_dirty ();
255         void set_clean ();
256         bool dirty() const { return _state_of_the_state & Dirty; }
257         void set_deletion_in_progress ();
258         bool deletion_in_progress() const { return _state_of_the_state & Deletion; }
259         sigc::signal<void> DirtyChanged;
260
261         std::string sound_dir (bool with_path = true) const;
262         std::string peak_dir () const;
263         std::string dead_sound_dir () const;
264         std::string automation_dir () const;
265
266         static string suffixed_search_path (std::string suffix, bool data);
267         static string control_protocol_path ();
268         static string template_path ();
269         static string template_dir ();
270         static void get_template_list (list<string>&);
271         
272         static string change_audio_path_by_name (string oldpath, string oldname, string newname, bool destructive);
273         static string change_midi_path_by_name (string oldpath, string oldname, string newname, bool destructive);
274         
275         string peak_path_from_audio_path (string) const;
276         string audio_path_from_name (string, uint32_t nchans, uint32_t chan, bool destructive);
277         string midi_path_from_name (string);
278
279         void process (nframes_t nframes);
280
281         BufferSet& get_silent_buffers (ChanCount count = ChanCount::ZERO);
282         BufferSet& get_scratch_buffers (ChanCount count = ChanCount::ZERO);
283         BufferSet& get_send_buffers (ChanCount count = ChanCount::ZERO);
284         
285         void add_diskstream (boost::shared_ptr<Diskstream>);
286         boost::shared_ptr<Diskstream> diskstream_by_id (const PBD::ID& id);
287         boost::shared_ptr<Diskstream> diskstream_by_name (string name);
288
289         bool have_captured() const { return _have_captured; }
290
291         void refill_all_diskstream_buffers ();
292         uint32_t diskstream_buffer_size() const { return dstream_buffer_size; }
293         
294         uint32_t get_next_diskstream_id() const { return n_diskstreams(); }
295         uint32_t n_diskstreams() const;
296         
297         typedef std::list<boost::shared_ptr<Diskstream> > DiskstreamList;
298         typedef std::list<boost::shared_ptr<Route> >      RouteList; 
299         
300         boost::shared_ptr<RouteList> get_routes() const {
301                 return routes.reader ();
302         }
303         
304         uint32_t nroutes() const { return routes.reader()->size(); }
305         uint32_t ntracks () const;
306         uint32_t nbusses () const;
307
308         struct RoutePublicOrderSorter {
309             bool operator() (boost::shared_ptr<Route>, boost::shared_ptr<Route> b);
310         };
311         
312         template<class T> void foreach_route (T *obj, void (T::*func)(Route&));
313         template<class T> void foreach_route (T *obj, void (T::*func)(boost::shared_ptr<Route>));
314         template<class T, class A> void foreach_route (T *obj, void (T::*func)(Route&, A), A arg);
315
316         boost::shared_ptr<Route> route_by_name (string);
317         boost::shared_ptr<Route> route_by_id (PBD::ID);
318         boost::shared_ptr<Route> route_by_remote_id (uint32_t id);
319
320         bool route_name_unique (string) const;
321
322         bool get_record_enabled() const { 
323                 return (record_status () >= Enabled);
324         }
325
326         RecordState record_status() const {
327                 return (RecordState) g_atomic_int_get (&_record_status);
328         }
329
330         bool actively_recording () {
331                 return record_status() == Recording;
332         }
333
334         bool record_enabling_legal () const;
335         void maybe_enable_record ();
336         void disable_record (bool rt_context, bool force = false);
337         void step_back_from_record ();
338         
339         void maybe_write_autosave ();
340
341         /* Proxy signal for region hidden changes */
342
343         sigc::signal<void,boost::shared_ptr<Region> > RegionHiddenChange;
344
345         /* Emitted when all i/o connections are complete */
346         
347         sigc::signal<void> IOConnectionsComplete;
348         
349         /* Record status signals */
350
351         sigc::signal<void> RecordStateChanged;
352
353         /* Transport mechanism signals */
354
355         sigc::signal<void> TransportStateChange; /* generic */
356         sigc::signal<void,nframes_t> PositionChanged; /* sent after any non-sequential motion */
357         sigc::signal<void> DurationChanged;
358         sigc::signal<void> HaltOnXrun;
359
360         sigc::signal<void,RouteList&> RouteAdded;
361
362         void request_roll ();
363         void request_bounded_roll (nframes_t start, nframes_t end);
364         void request_stop (bool abort = false);
365         void request_locate (nframes_t frame, bool with_roll = false);
366
367         void request_play_loop (bool yn);
368         bool get_play_loop () const { return play_loop; }
369
370         nframes_t  last_transport_start() const { return _last_roll_location; }
371         void goto_end ()   { request_locate (end_location->start(), false);}
372         void goto_start () { request_locate (start_location->start(), false); }
373         void set_session_start (nframes_t start) { start_location->set_start(start); }
374         void set_session_end (nframes_t end) { end_location->set_start(end); _end_location_is_free = false; }
375         void use_rf_shuttle_speed ();
376         void allow_auto_play (bool yn);
377         void request_transport_speed (float speed);
378         void request_overwrite_buffer (Diskstream*);
379         void request_diskstream_speed (Diskstream&, float speed);
380         void request_input_change_handling ();
381
382         bool locate_pending() const { return static_cast<bool>(post_transport_work&PostTransportLocate); }
383         bool transport_locked () const;
384
385         int wipe ();
386         //int wipe_diskstream (AudioDiskstream *);
387
388         int remove_region_from_region_list (boost::shared_ptr<Region>);
389
390         nframes_t get_maximum_extent () const;
391         nframes_t current_end_frame() const { return end_location->start(); }
392         nframes_t current_start_frame() const { return start_location->start(); }
393         nframes_t frame_rate() const   { return _current_frame_rate; }
394         nframes_t frames_per_hour() const { return _frames_per_hour; }
395
396         double frames_per_smpte_frame() const { return _frames_per_smpte_frame; }
397         nframes_t smpte_frames_per_hour() const { return _smpte_frames_per_hour; }
398
399         float smpte_frames_per_second() const;
400         bool smpte_drop_frames() const;
401
402         /* Locations */
403
404         Locations *locations() { return &_locations; }
405
406         sigc::signal<void,Location*>    auto_loop_location_changed;
407         sigc::signal<void,Location*>    auto_punch_location_changed;
408         sigc::signal<void>              locations_modified;
409
410         void set_auto_punch_location (Location *);
411         void set_auto_loop_location (Location *);
412         int location_name(string& result, string base = string(""));
413
414         void reset_input_monitor_state ();
415
416         void add_event (nframes_t action_frame, Event::Type type, nframes_t target_frame = 0);
417         void remove_event (nframes_t frame, Event::Type type);
418         void clear_events (Event::Type type);
419
420         nframes_t get_block_size() const { return current_block_size; }
421         nframes_t worst_output_latency () const { return _worst_output_latency; }
422         nframes_t worst_input_latency () const { return _worst_input_latency; }
423         nframes_t worst_track_latency () const { return _worst_track_latency; }
424
425         int save_state (string snapshot_name, bool pending = false);
426         int restore_state (string snapshot_name);
427         int save_template (string template_name);
428         int save_history (string snapshot_name = "");
429         int restore_history (string snapshot_name);
430         void remove_state (string snapshot_name);
431         void rename_state (string old_name, string new_name);
432
433         static int rename_template (string old_name, string new_name);
434
435         static int delete_template (string name);
436         
437         sigc::signal<void,string> StateSaved;
438         sigc::signal<void> StateReady;
439
440         vector<string*>* possible_states() const;
441         static vector<string*>* possible_states(string path);
442
443         XMLNode& get_state();
444         int      set_state(const XMLNode& node); // not idempotent
445         XMLNode& get_template();
446         
447         void add_instant_xml (XMLNode&, const std::string& dir);
448
449         enum StateOfTheState {
450                 Clean = 0x0,
451                 Dirty = 0x1,
452                 CannotSave = 0x2,
453                 Deletion = 0x4,
454                 InitialConnecting = 0x8,
455                 Loading = 0x10,
456                 InCleanup = 0x20
457         };
458
459         StateOfTheState state_of_the_state() const { return _state_of_the_state; }
460
461         RouteGroup* add_edit_group (string);
462         RouteGroup* add_mix_group (string);
463
464         void remove_edit_group (RouteGroup&);
465         void remove_mix_group (RouteGroup&);
466
467         RouteGroup *mix_group_by_name (string);
468         RouteGroup *edit_group_by_name (string);
469
470         sigc::signal<void,RouteGroup*> edit_group_added;
471         sigc::signal<void,RouteGroup*> mix_group_added;
472         sigc::signal<void> edit_group_removed;
473         sigc::signal<void> mix_group_removed;
474
475         void foreach_edit_group (sigc::slot<void,RouteGroup*> sl) {
476                 for (list<RouteGroup *>::iterator i = edit_groups.begin(); i != edit_groups.end(); i++) {
477                         sl (*i);
478                 }
479         }
480
481         void foreach_mix_group (sigc::slot<void,RouteGroup*> sl) {
482                 for (list<RouteGroup *>::iterator i = mix_groups.begin(); i != mix_groups.end(); i++) {
483                         sl (*i);
484                 }
485         }
486
487         /* fundamental operations. duh. */
488
489         std::list<boost::shared_ptr<AudioTrack> > new_audio_track (int input_channels, int output_channels, TrackMode mode = Normal, uint32_t how_many = 1);
490         RouteList new_audio_route (int input_channels, int output_channels, uint32_t how_many);
491         
492         std::list<boost::shared_ptr<MidiTrack> > new_midi_track (TrackMode mode = Normal, uint32_t how_many = 1);
493         //boost::shared_ptr<Route>     new_midi_route (uint32_t how_many = 1);
494
495         void   remove_route (boost::shared_ptr<Route>);
496         void   resort_routes ();
497         void   resort_routes_using (boost::shared_ptr<RouteList>);
498         
499         void    set_remote_control_ids();
500
501         AudioEngine &engine() { return _engine; };
502
503         int32_t  max_level;
504         int32_t  min_level;
505
506         /* Time */
507
508         nframes_t transport_frame () const {return _transport_frame; }
509         nframes_t audible_frame () const;
510
511         enum PullupFormat {
512                 pullup_Plus4Plus1,
513                 pullup_Plus4,
514                 pullup_Plus4Minus1,
515                 pullup_Plus1,
516                 pullup_None,
517                 pullup_Minus1,
518                 pullup_Minus4Plus1,
519                 pullup_Minus4,
520                 pullup_Minus4Minus1
521         };
522
523         int  set_smpte_format (SmpteFormat);
524         void sync_time_vars();
525
526         void bbt_time (nframes_t when, BBT_Time&);
527         void smpte_to_sample( SMPTE::Time& smpte, nframes_t& sample, bool use_offset, bool use_subframes ) const;
528         void sample_to_smpte( nframes_t sample, SMPTE::Time& smpte, bool use_offset, bool use_subframes ) const;
529         void smpte_time (SMPTE::Time &);
530         void smpte_time (nframes_t when, SMPTE::Time&);
531         void smpte_time_subframes (nframes_t when, SMPTE::Time&);
532
533         void smpte_duration (nframes_t, SMPTE::Time&) const;
534         void smpte_duration_string (char *, nframes_t) const;
535
536         void           set_smpte_offset (nframes_t);
537         nframes_t smpte_offset () const { return _smpte_offset; }
538         void           set_smpte_offset_negative (bool);
539         bool           smpte_offset_negative () const { return _smpte_offset_negative; }
540
541         nframes_t convert_to_frames_at (nframes_t position, AnyTime&);
542
543         static sigc::signal<void> StartTimeChanged;
544         static sigc::signal<void> EndTimeChanged;
545         static sigc::signal<void> SMPTEOffsetChanged;
546
547         void        request_slave_source (SlaveSource);
548         bool        synced_to_jack() const { return Config->get_slave_source() == JACK; }
549
550         float       transport_speed() const { return _transport_speed; }
551         bool        transport_stopped() const { return _transport_speed == 0.0f; }
552         bool        transport_rolling() const { return _transport_speed != 0.0f; }
553
554         int jack_slave_sync (nframes_t);
555
556         TempoMap& tempo_map() { return *_tempo_map; }
557         
558         /* region info  */
559
560         sigc::signal<void,boost::shared_ptr<Region> > RegionAdded;
561         sigc::signal<void,boost::shared_ptr<Region> > RegionRemoved;
562
563         int region_name (string& result, string base = string(""), bool newlevel = false) const;
564         string new_region_name (string);
565         string path_from_region_name (string name, string identifier);
566
567         boost::shared_ptr<Region> find_whole_file_parent (boost::shared_ptr<Region const>);
568         
569         void find_equivalent_playlist_regions (boost::shared_ptr<Region>, std::vector<boost::shared_ptr<Region> >& result);
570
571         boost::shared_ptr<Region>      XMLRegionFactory (const XMLNode&, bool full);
572         boost::shared_ptr<AudioRegion> XMLAudioRegionFactory (const XMLNode&, bool full);
573         boost::shared_ptr<MidiRegion>  XMLMidiRegionFactory (const XMLNode&, bool full);
574
575         template<class T> void foreach_region (T *obj, void (T::*func)(boost::shared_ptr<Region>));
576
577         /* source management */
578
579         struct import_status : public InterThreadInfo {
580             string doing_what;
581             
582             /* control info */
583             bool multichan;
584             bool sample_convert;
585             volatile bool freeze;
586             std::vector<Glib::ustring> paths;
587             
588             /* result */
589             std::vector<boost::shared_ptr<Region> > new_regions;
590         };
591
592         int import_audiofile (import_status&);
593         bool sample_rate_convert (import_status&, string infile, string& outfile);
594         string build_tmp_convert_name (string file);
595
596         SlaveSource post_export_slave;
597         nframes_t post_export_position;
598
599         int start_audio_export (ARDOUR::AudioExportSpecification&);
600         int stop_audio_export (ARDOUR::AudioExportSpecification&);
601         void finalize_audio_export ();
602
603         void add_source (boost::shared_ptr<Source>);
604         void remove_source (boost::weak_ptr<Source>);
605
606         struct cleanup_report {
607             vector<string> paths;
608             int64_t space;
609         };
610
611         int  cleanup_sources (cleanup_report&);
612         int  cleanup_trash_sources (cleanup_report&);
613
614         int destroy_region (boost::shared_ptr<Region>);
615         int destroy_regions (std::list<boost::shared_ptr<Region> >);
616
617         int remove_last_capture ();
618
619         /* handlers should return -1 for "stop cleanup", 0 for
620            "yes, delete this playlist" and 1 for "no, don't delete
621            this playlist.
622         */
623         
624         sigc::signal<int,boost::shared_ptr<ARDOUR::Playlist> > AskAboutPlaylistDeletion;
625
626         /* handlers should return !0 for use pending state, 0 for
627            ignore it.
628         */
629
630         static sigc::signal<int> AskAboutPendingState;
631         
632         boost::shared_ptr<AudioFileSource> create_audio_source_for_session (ARDOUR::AudioDiskstream&, uint32_t which_channel, bool destructive);
633
634         boost::shared_ptr<MidiSource> create_midi_source_for_session (ARDOUR::MidiDiskstream&);
635
636         boost::shared_ptr<Source> source_by_id (const PBD::ID&);
637         boost::shared_ptr<Source> source_by_path_and_channel (const Glib::ustring&, uint16_t);
638
639         /* playlist management */
640
641         boost::shared_ptr<Playlist> playlist_by_name (string name);
642         void add_playlist (boost::shared_ptr<Playlist>);
643         sigc::signal<void,boost::shared_ptr<Playlist> > PlaylistAdded;
644         sigc::signal<void,boost::shared_ptr<Playlist> > PlaylistRemoved;
645
646         uint32_t n_playlists() const;
647
648         template<class T> void foreach_playlist (T *obj, void (T::*func)(boost::shared_ptr<Playlist>));
649         void get_playlists (std::vector<boost::shared_ptr<Playlist> >&);
650
651         /* named selections */
652
653         NamedSelection* named_selection_by_name (string name);
654         void add_named_selection (NamedSelection *);
655         void remove_named_selection (NamedSelection *);
656
657         template<class T> void foreach_named_selection (T& obj, void (T::*func)(NamedSelection&));
658         sigc::signal<void> NamedSelectionAdded;
659         sigc::signal<void> NamedSelectionRemoved;
660
661         /* Curves and AutomationLists (TODO when they go away) */
662         void add_curve(Curve*);
663         void add_automation_list(AutomationList*);
664
665         /* fade curves */
666
667         float get_default_fade_length () const { return default_fade_msecs; }
668         float get_default_fade_steepness () const { return default_fade_steepness; }
669         void set_default_fade (float steepness, float msecs);
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         sigc::signal<void,bool> AuditionActive;
680
681         /* flattening stuff */
682
683         int write_one_audio_track (AudioTrack&, nframes_t start, nframes_t cnt, bool overwrite, vector<boost::shared_ptr<Source> >&,
684                                    InterThreadInfo& wot);
685         int freeze (InterThreadInfo&);
686
687         /* session-wide solo/mute/rec-enable */
688         
689         bool soloing() const { return currently_soloing; }
690
691         void set_all_solo (bool);
692         void set_all_mute (bool);
693
694         sigc::signal<void,bool> SoloActive;
695         sigc::signal<void> SoloChanged;
696         
697         void record_disenable_all ();
698         void record_enable_all ();
699
700         /* control/master out */
701
702         boost::shared_ptr<IO> control_out() const { return _control_out; }
703         boost::shared_ptr<IO> master_out() const { return _master_out; }
704
705         /* insert/send management */
706         
707         uint32_t n_port_inserts() const { return _port_inserts.size(); }
708         uint32_t n_plugin_inserts() const { return _plugin_inserts.size(); }
709         uint32_t n_sends() const { return _sends.size(); }
710
711         uint32_t next_send_id();
712         uint32_t next_insert_id();
713         void mark_send_id (uint32_t);
714         void mark_insert_id (uint32_t);
715
716         /* s/w "RAID" management */
717         
718         nframes_t available_capture_duration();
719
720         /* I/O Connections */
721
722         template<class T> void foreach_connection (T *obj, void (T::*func)(Connection *));
723         void add_connection (Connection *);
724         void remove_connection (Connection *);
725         Connection *connection_by_name (string) const;
726
727         sigc::signal<void,Connection *> ConnectionAdded;
728         sigc::signal<void,Connection *> ConnectionRemoved;
729
730         /* MIDI */
731
732         int set_mtc_port (string port_tag);
733         int set_mmc_port (string port_tag);
734         int set_midi_port (string port_tag);
735         MIDI::Port *mtc_port() const { return _mtc_port; }
736         MIDI::Port *mmc_port() const { return _mmc_port; }
737         MIDI::Port *midi_port() const { return _midi_port; }
738
739         sigc::signal<void> MTC_PortChanged;
740         sigc::signal<void> MMC_PortChanged;
741         sigc::signal<void> MIDI_PortChanged;
742
743         void set_trace_midi_input (bool, MIDI::Port* port = 0);
744         void set_trace_midi_output (bool, MIDI::Port* port = 0);
745
746         bool get_trace_midi_input(MIDI::Port *port = 0);
747         bool get_trace_midi_output(MIDI::Port *port = 0);
748         
749         void send_midi_message (MIDI::Port * port, MIDI::eventType ev, MIDI::channel_t, MIDI::EventTwoBytes);
750
751         void deliver_midi (MIDI::Port*, MIDI::byte*, int32_t size);
752
753         void set_mmc_device_id (uint32_t id);
754         
755         /* Scrubbing */
756
757         void start_scrub (nframes_t where);
758         void stop_scrub ();
759         void set_scrub_speed (float);
760         nframes_t scrub_buffer_size() const;
761         sigc::signal<void> ScrubReady;
762
763         /* History (for editors, mixers, UIs etc.) */
764
765         /** Undo some transactions.
766          * @param n Number of transactions to undo.
767          */
768         void undo (uint32_t n) {
769                 _history.undo (n);
770         }
771
772         void redo (uint32_t n) {
773                 _history.redo (n);
774         }
775
776         UndoHistory& history() { return _history; }
777         
778         uint32_t undo_depth() const { return _history.undo_depth(); }
779         uint32_t redo_depth() const { return _history.redo_depth(); }
780         string next_undo() const { return _history.next_undo(); }
781         string next_redo() const { return _history.next_redo(); }
782
783         void begin_reversible_command (string cmd_name);
784         void commit_reversible_command (Command* cmd = 0);
785
786         void add_command (Command *const cmd) {
787                 current_trans->add_command (cmd);
788         }
789
790         std::map<PBD::ID, PBD::StatefulThingWithGoingAway*> registry;
791
792         // these commands are implemented in libs/ardour/session_command.cc
793         Command* memento_command_factory(XMLNode* n);
794         void register_with_memento_command_factory(PBD::ID, PBD::StatefulThingWithGoingAway*);
795
796         Command* global_state_command_factory (const XMLNode& n);
797
798         class GlobalRouteStateCommand : public Command
799         {
800           public:
801                 GlobalRouteStateCommand (Session&, void*);
802                 GlobalRouteStateCommand (Session&, const XMLNode& node);
803                 int set_state (const XMLNode&);
804                 XMLNode& get_state ();
805
806           protected:
807                 GlobalRouteBooleanState before, after;
808                 Session& sess;
809                 void* src;
810                 
811         };
812
813         class GlobalSoloStateCommand : public GlobalRouteStateCommand
814         {
815           public:
816                 GlobalSoloStateCommand (Session &, void *src);
817                 GlobalSoloStateCommand (Session&, const XMLNode&);
818                 void operator()(); //redo
819                 void undo();
820                 XMLNode &get_state();
821                 void mark();
822         };
823
824         class GlobalMuteStateCommand : public GlobalRouteStateCommand
825         {
826           public:
827                 GlobalMuteStateCommand(Session &, void *src);
828                 GlobalMuteStateCommand (Session&, const XMLNode&);
829                 void operator()(); // redo
830                 void undo();
831                 XMLNode &get_state();
832                 void mark();
833         };
834
835         class GlobalRecordEnableStateCommand : public GlobalRouteStateCommand
836         {
837           public:
838                 GlobalRecordEnableStateCommand(Session &, void *src);
839                 GlobalRecordEnableStateCommand (Session&, const XMLNode&);
840                 void operator()(); // redo
841                 void undo();
842                 XMLNode &get_state();
843                 void mark();
844         };
845
846         class GlobalMeteringStateCommand : public Command
847         {
848           public:
849                 GlobalMeteringStateCommand(Session &, void *src);
850                 GlobalMeteringStateCommand (Session&, const XMLNode&);
851                 void operator()();
852                 void undo();
853                 XMLNode &get_state();
854                 int set_state (const XMLNode&);
855                 void mark();
856
857           protected:
858                 Session& sess;
859                 void* src;
860                 GlobalRouteMeterState before;
861                 GlobalRouteMeterState after;
862         };
863
864         /* clicking */
865
866         boost::shared_ptr<IO>  click_io() { return _click_io; }
867                 
868         /* tempo FX */
869
870         struct TimeStretchRequest {
871             boost::shared_ptr<ARDOUR::AudioRegion> region;
872             float                fraction; /* session: read ; GUI: write */
873             float                progress; /* session: write ; GUI: read */
874             bool                 running;  /* read/write */
875             bool                 quick_seek; /* GUI: write */
876             bool                 antialias;  /* GUI: write */
877
878             TimeStretchRequest () {} 
879         };
880
881         boost::shared_ptr<AudioRegion> tempoize_region (TimeStretchRequest&);
882
883         /* disk, buffer loads */
884
885         uint32_t playback_load ();
886         uint32_t capture_load ();
887         uint32_t playback_load_min ();
888         uint32_t capture_load_min ();
889
890         void reset_playback_load_min ();
891         void reset_capture_load_min ();
892         
893         float read_data_rate () const;
894         float write_data_rate () const;
895
896         /* ranges */
897
898         void set_audio_range (list<AudioRange>&);
899         void set_music_range (list<MusicRange>&);
900
901         void request_play_range (bool yn);
902         bool get_play_range () const { return _play_range; }
903
904         /* favorite dirs */
905         typedef vector<string> FavoriteDirs;
906
907         static int read_favorite_dirs (FavoriteDirs&);
908
909         static int write_favorite_dirs (FavoriteDirs&);
910         
911         /* file suffixes */
912
913         static const char* template_suffix() { return _template_suffix; }
914         static const char* statefile_suffix() { return _statefile_suffix; }
915         static const char* pending_suffix() { return _pending_suffix; }
916
917         /* buffers for gain and pan */
918
919         gain_t* gain_automation_buffer () const { return _gain_automation_buffer; }
920         pan_t** pan_automation_buffer () const  { return _pan_automation_buffer; }
921
922         /* buffers for conversion */
923         enum RunContext {
924                 ButlerContext = 0,
925                 TransportContext,
926                 ExportContext
927         };
928         
929         /* VST support */
930
931         static long vst_callback (AEffect* effect,
932                                   long opcode,
933                                   long index,
934                                   long value,
935                                   void* ptr,
936                                   float opt);
937
938         static sigc::signal<void> SendFeedback;
939
940         /* Controllables */
941
942         PBD::Controllable* controllable_by_id (const PBD::ID&);
943
944         void add_controllable (PBD::Controllable*);
945         void remove_controllable (PBD::Controllable*);
946
947   protected:
948         friend class AudioEngine;
949         void set_block_size (nframes_t nframes);
950         void set_frame_rate (nframes_t nframes);
951
952   protected:
953         friend class Diskstream;
954         void stop_butler ();
955         void wait_till_butler_finished();
956
957   protected:
958         friend class Route;
959         void schedule_curve_reallocation ();
960         void update_latency_compensation (bool, bool);
961         
962   private:
963         int  create (bool& new_session, string* mix_template, nframes_t initial_length);
964         void destroy ();
965
966         nframes_t compute_initial_length ();
967
968         static const char* _template_suffix;
969         static const char* _statefile_suffix;
970         static const char* _pending_suffix;
971
972         enum SubState {
973                 PendingDeclickIn   = 0x1,
974                 PendingDeclickOut  = 0x2,
975                 StopPendingCapture = 0x4,
976                 AutoReturning      = 0x10,
977                 PendingLocate      = 0x20,
978                 PendingSetLoop     = 0x40
979         };
980
981         /* stuff used in process() should be close together to
982            maximise cache hits
983         */
984
985         typedef void (Session::*process_function_type)(nframes_t);
986
987         AudioEngine            &_engine;
988         mutable gint            processing_prohibited;
989         /// the function called when the main JACK process callback happens
990         process_function_type    process_function;
991         process_function_type    last_process_function;
992         bool                     waiting_for_sync_offset;
993         nframes_t          _base_frame_rate;
994         nframes_t          _current_frame_rate;  //this includes video pullup offset
995         int                      transport_sub_state;
996         mutable gint           _record_status;
997         nframes_t          _transport_frame;
998         Location*                end_location;
999         Location*                start_location;
1000         Slave                  *_slave;
1001         volatile float          _transport_speed;
1002         volatile float          _desired_transport_speed;
1003         float                   _last_transport_speed;
1004         bool                     auto_play_legal;
1005         nframes_t          _last_slave_transport_frame;
1006         nframes_t           maximum_output_latency;
1007         nframes_t           last_stop_frame;
1008         BufferSet*              _scratch_buffers;
1009         BufferSet*              _silent_buffers;
1010         BufferSet*              _send_buffers;
1011         nframes_t           current_block_size;
1012         nframes_t          _worst_output_latency;
1013         nframes_t          _worst_input_latency;
1014         nframes_t          _worst_track_latency;
1015         bool                    _have_captured;
1016         float                   _meter_hold;
1017         float                   _meter_falloff;
1018         bool                    _end_location_is_free;
1019
1020         void set_worst_io_latencies ();
1021         void set_worst_io_latencies_x (IOChange asifwecare, void *ignored) {
1022                 set_worst_io_latencies ();
1023         }
1024
1025         void update_latency_compensation_proxy (void* ignored);
1026
1027         void ensure_buffers (ChanCount howmany);
1028         
1029         void process_scrub          (nframes_t);
1030         void process_without_events (nframes_t);
1031         void process_with_events    (nframes_t);
1032         void process_audition       (nframes_t);
1033         int  process_export         (nframes_t, ARDOUR::AudioExportSpecification*);
1034         
1035         /* slave tracking */
1036
1037         static const int delta_accumulator_size = 25;
1038         int delta_accumulator_cnt;
1039         long delta_accumulator[delta_accumulator_size];
1040         long average_slave_delta;
1041         int  average_dir;
1042         bool have_first_delta_accumulator;
1043         
1044         enum SlaveState {
1045                 Stopped,
1046                 Waiting,
1047                 Running
1048         };
1049         
1050         SlaveState slave_state;
1051         nframes_t slave_wait_end;
1052
1053         void reset_slave_state ();
1054         bool follow_slave (nframes_t, nframes_t);
1055         void set_slave_source (SlaveSource);
1056
1057         bool _exporting;
1058         int prepare_to_export (ARDOUR::AudioExportSpecification&);
1059
1060         void prepare_diskstreams ();
1061         void commit_diskstreams (nframes_t, bool& session_requires_butler);
1062         int  process_routes (nframes_t, nframes_t);
1063         int  silent_process_routes (nframes_t, nframes_t);
1064
1065         bool get_rec_monitors_input () {
1066                 if (actively_recording()) {
1067                         return true;
1068                 } else {
1069                         if (Config->get_auto_input()) {
1070                                 return false;
1071                         } else {
1072                                 return true;
1073                         }
1074                 }
1075         }
1076
1077         int get_transport_declick_required () {
1078
1079                 if (transport_sub_state & PendingDeclickIn) {
1080                         transport_sub_state &= ~PendingDeclickIn;
1081                         return 1;
1082                 } else if (transport_sub_state & PendingDeclickOut) {
1083                         return -1;
1084                 } else {
1085                         return 0;
1086                 }
1087         }
1088
1089         bool maybe_stop (nframes_t limit) {
1090                 if ((_transport_speed > 0.0f && _transport_frame >= limit) || (_transport_speed < 0.0f && _transport_frame == 0)) {
1091                         stop_transport ();
1092                         return true;
1093                 }
1094                 return false;
1095         }
1096
1097         bool maybe_sync_start (nframes_t&, nframes_t&);
1098
1099         void check_declick_out ();
1100
1101         MIDI::MachineControl*    mmc;
1102         MIDI::Port*             _mmc_port;
1103         MIDI::Port*             _mtc_port;
1104         MIDI::Port*             _midi_port;
1105         string                  _path;
1106         string                  _name;
1107         bool                     session_send_mmc;
1108         bool                     session_send_mtc;
1109         bool                     session_midi_feedback;
1110         bool                     play_loop;
1111         bool                     loop_changing;
1112         nframes_t           last_loopend;
1113
1114         RingBuffer<Event*> pending_events;
1115
1116         void hookup_io ();
1117         void when_engine_running ();
1118         void graph_reordered ();
1119
1120         string _current_snapshot_name;
1121
1122         XMLTree* state_tree;
1123         bool     state_was_pending;
1124         StateOfTheState _state_of_the_state;
1125
1126         void     auto_save();
1127         int      load_options (const XMLNode&);
1128         XMLNode& get_options () const;
1129         int      load_state (string snapshot_name);
1130         bool     save_config_options_predicate (ConfigVariableBase::Owner owner) const;
1131
1132         nframes_t   _last_roll_location;
1133         nframes_t   _last_record_location;
1134         bool              pending_locate_roll;
1135         nframes_t    pending_locate_frame;
1136
1137         bool              pending_locate_flush;
1138         bool              pending_abort;
1139         bool              pending_auto_loop;
1140         
1141         Sample*           butler_mixdown_buffer;
1142         float*            butler_gain_buffer;
1143         pthread_t         butler_thread;
1144         Glib::Mutex       butler_request_lock;
1145         Glib::Cond        butler_paused;
1146         bool              butler_should_run;
1147         mutable gint      butler_should_do_transport_work;
1148         int               butler_request_pipe[2];
1149
1150         inline bool transport_work_requested() const { return g_atomic_int_get(&butler_should_do_transport_work); }
1151         
1152         struct ButlerRequest {
1153             enum Type {
1154                     Wake,
1155                     Run,
1156                     Pause,
1157                     Quit
1158             };
1159         };
1160
1161         enum PostTransportWork {
1162                 PostTransportStop               = 0x1,
1163                 PostTransportDisableRecord      = 0x2,
1164                 PostTransportPosition           = 0x8,
1165                 PostTransportDidRecord          = 0x20,
1166                 PostTransportDuration           = 0x40,
1167                 PostTransportLocate             = 0x80,
1168                 PostTransportRoll               = 0x200,
1169                 PostTransportAbort              = 0x800,
1170                 PostTransportOverWrite          = 0x1000,
1171                 PostTransportSpeed              = 0x2000,
1172                 PostTransportAudition           = 0x4000,
1173                 PostTransportScrub              = 0x8000,
1174                 PostTransportReverse            = 0x10000,
1175                 PostTransportInputChange        = 0x20000,
1176                 PostTransportCurveRealloc       = 0x40000
1177         };
1178         
1179         static const PostTransportWork ProcessCannotProceedMask = 
1180                 PostTransportWork (PostTransportInputChange|
1181                                    PostTransportSpeed|
1182                                    PostTransportReverse|
1183                                    PostTransportCurveRealloc|
1184                                    PostTransportScrub|
1185                                    PostTransportAudition|
1186                                    PostTransportLocate|
1187                                    PostTransportStop);
1188         
1189         PostTransportWork post_transport_work;
1190
1191         void             summon_butler ();
1192         void             schedule_butler_transport_work ();
1193         int              start_butler_thread ();
1194         void             terminate_butler_thread ();
1195         static void    *_butler_thread_work (void *arg);
1196         void*            butler_thread_work ();
1197
1198         uint32_t    cumulative_rf_motion;
1199         uint32_t    rf_scale;
1200
1201         void set_rf_speed (float speed);
1202         void reset_rf_scale (nframes_t frames_moved);
1203
1204         Locations        _locations;
1205         void              locations_changed ();
1206         void              locations_added (Location*);
1207         void              handle_locations_changed (Locations::LocationList&);
1208
1209         sigc::connection auto_punch_start_changed_connection;
1210         sigc::connection auto_punch_end_changed_connection;
1211         sigc::connection auto_punch_changed_connection;
1212         void             auto_punch_start_changed (Location *);
1213         void             auto_punch_end_changed (Location *);
1214         void             auto_punch_changed (Location *);
1215
1216         sigc::connection auto_loop_start_changed_connection;
1217         sigc::connection auto_loop_end_changed_connection;
1218         sigc::connection auto_loop_changed_connection;
1219         void             auto_loop_changed (Location *);
1220
1221         typedef list<Event *> Events;
1222         Events           events;
1223         Events           immediate_events;
1224         Events::iterator next_event;
1225
1226         /* there can only ever be one of each of these */
1227
1228         Event *auto_loop_event;
1229         Event *punch_out_event;
1230         Event *punch_in_event;
1231
1232         /* events */
1233
1234         void dump_events () const;
1235         void queue_event (Event *ev);
1236         void merge_event (Event*);
1237         void replace_event (Event::Type, nframes_t action_frame, nframes_t target = 0);
1238         bool _replace_event (Event*);
1239         bool _remove_event (Event *);
1240         void _clear_event_type (Event::Type);
1241
1242         void first_stage_init (string path, string snapshot_name);
1243         int  second_stage_init (bool new_tracks);
1244         void find_current_end ();
1245         void remove_empty_sounds ();
1246
1247         void setup_midi_control ();
1248         //int  midi_read (MIDI::Port *);
1249
1250         void enable_record ();
1251         
1252         void increment_transport_position (uint32_t val) {
1253                 if (max_frames - val < _transport_frame) {
1254                         _transport_frame = max_frames;
1255                 } else {
1256                         _transport_frame += val;
1257                 }
1258         }
1259
1260         void decrement_transport_position (uint32_t val) {
1261                 if (val < _transport_frame) {
1262                         _transport_frame -= val;
1263                 } else {
1264                         _transport_frame = 0;
1265                 }
1266         }
1267
1268         void post_transport_motion ();
1269         static void *session_loader_thread (void *arg);
1270
1271         void *do_work();
1272
1273         void set_next_event ();
1274         void process_event (Event *ev);
1275
1276         /* MIDI Machine Control */
1277
1278         void deliver_mmc (MIDI::MachineControl::Command, nframes_t);
1279         //void deliver_midi_message (MIDI::Port * port, MIDI::eventType ev, MIDI::channel_t, MIDI::EventTwoBytes);
1280         //void deliver_data (MIDI::Port* port, MIDI::byte*, int32_t size);
1281
1282         void spp_start (MIDI::Parser&);
1283         void spp_continue (MIDI::Parser&);
1284         void spp_stop (MIDI::Parser&);
1285
1286         void mmc_deferred_play (MIDI::MachineControl &);
1287         void mmc_stop (MIDI::MachineControl &);
1288         void mmc_step (MIDI::MachineControl &, int);
1289         void mmc_pause (MIDI::MachineControl &);
1290         void mmc_record_pause (MIDI::MachineControl &);
1291         void mmc_record_strobe (MIDI::MachineControl &);
1292         void mmc_record_exit (MIDI::MachineControl &);
1293         void mmc_track_record_status (MIDI::MachineControl &, uint32_t track, bool enabled);
1294         void mmc_fast_forward (MIDI::MachineControl &);
1295         void mmc_rewind (MIDI::MachineControl &);
1296         void mmc_locate (MIDI::MachineControl &, const MIDI::byte *);
1297         void mmc_shuttle (MIDI::MachineControl &mmc, float speed, bool forw);
1298         void mmc_record_enable (MIDI::MachineControl &mmc, size_t track, bool enabled);
1299
1300         struct timeval last_mmc_step;
1301         double step_speed;
1302
1303         typedef sigc::slot<bool> MidiTimeoutCallback;
1304         typedef list<MidiTimeoutCallback> MidiTimeoutList;
1305
1306         MidiTimeoutList midi_timeouts;
1307         bool mmc_step_timeout ();
1308
1309         MIDI::byte mmc_buffer[32];
1310         MIDI::byte mtc_msg[16];
1311         MIDI::byte mtc_smpte_bits;   /* encoding of SMTPE type for MTC */
1312         MIDI::byte midi_msg[16];
1313         nframes_t  outbound_mtc_smpte_frame;
1314         SMPTE::Time transmitting_smpte_time;
1315         int next_quarter_frame_to_send;
1316         
1317         double _frames_per_smpte_frame; /* has to be floating point because of drop frame */
1318         nframes_t _frames_per_hour;
1319         nframes_t _smpte_frames_per_hour;
1320         nframes_t _smpte_offset;
1321         bool _smpte_offset_negative;
1322
1323         /* cache the most-recently requested time conversions. This helps when we
1324          * have multiple clocks showing the same time (e.g. the transport frame) */
1325         bool           last_smpte_valid;
1326         nframes_t last_smpte_when;
1327         SMPTE::Time    last_smpte;
1328         
1329         bool _send_smpte_update; ///< Flag to send a full frame (SMPTE) MTC message this cycle
1330
1331         int send_full_time_code(nframes_t nframes);
1332         int send_midi_time_code_for_cycle(nframes_t nframes);
1333
1334         nframes_t adjust_apparent_position (nframes_t frames);
1335         
1336         void reset_record_status ();
1337         
1338         int no_roll (nframes_t nframes, nframes_t offset);
1339         
1340         bool non_realtime_work_pending() const { return static_cast<bool>(post_transport_work); }
1341         bool process_can_proceed() const { return !(post_transport_work & ProcessCannotProceedMask); }
1342
1343         struct MIDIRequest {
1344             
1345             enum Type {
1346                     SendFullMTC,
1347                     SendMTC,
1348                     SendMMC,
1349                     PortChange,
1350                     SendMessage,
1351                     Deliver,
1352                     Quit
1353             };
1354             
1355             Type type;
1356             MIDI::MachineControl::Command mmc_cmd;
1357             nframes_t locate_frame;
1358
1359             // for SendMessage type
1360
1361             MIDI::Port * port;
1362             MIDI::channel_t chan;
1363             union {
1364                 MIDI::EventTwoBytes data;
1365                 MIDI::byte* buf;
1366             };
1367
1368             union { 
1369                 MIDI::eventType ev;
1370                 int32_t size;
1371             };
1372
1373             MIDIRequest () {}
1374             
1375             void *operator new(size_t ignored) {
1376                     return pool.alloc ();
1377             };
1378
1379             void operator delete(void *ptr, size_t size) {
1380                     pool.release (ptr);
1381             }
1382
1383           private:
1384             static MultiAllocSingleReleasePool pool;
1385         };
1386
1387         mutable  gint   butler_active;
1388         
1389         void          change_midi_ports ();
1390         int           use_config_midi_ports ();
1391
1392         bool waiting_to_start;
1393
1394         void set_play_loop (bool yn);
1395         void overwrite_some_buffers (Diskstream*);
1396         void flush_all_redirects ();
1397         void locate (nframes_t, bool with_roll, bool with_flush, bool with_loop=false);
1398         void start_locate (nframes_t, bool with_roll, bool with_flush, bool with_loop=false);
1399         void force_locate (nframes_t frame, bool with_roll = false);
1400         void set_diskstream_speed (Diskstream*, float speed);
1401         void set_transport_speed (float speed, bool abort = false);
1402         void stop_transport (bool abort = false);
1403         void start_transport ();
1404         void actually_start_transport ();
1405         void realtime_stop (bool abort);
1406         void non_realtime_start_scrub ();
1407         void non_realtime_set_speed ();
1408         void non_realtime_stop (bool abort, int entry_request_count, bool& finished);
1409         void non_realtime_overwrite (int entry_request_count, bool& finished);
1410         void butler_transport_work ();
1411         void post_transport ();
1412         void engine_halted ();
1413         void xrun_recovery ();
1414
1415         TempoMap    *_tempo_map;
1416         void          tempo_map_changed (Change);
1417
1418         /* edit/mix groups */
1419
1420         int load_route_groups (const XMLNode&, bool is_edit);
1421         int load_edit_groups (const XMLNode&);
1422         int load_mix_groups (const XMLNode&);
1423
1424
1425         list<RouteGroup *> edit_groups;
1426         list<RouteGroup *> mix_groups;
1427
1428         /* disk-streams */
1429
1430         SerializedRCUManager<DiskstreamList>  diskstreams; 
1431
1432         uint32_t dstream_buffer_size;
1433         int  load_diskstreams (const XMLNode&);
1434
1435         /* routes stuff */
1436
1437         SerializedRCUManager<RouteList>  routes;
1438
1439         void   add_routes (RouteList&, bool save = true);
1440         uint32_t destructive_index;
1441
1442         int load_routes (const XMLNode&);
1443         boost::shared_ptr<Route> XMLRouteFactory (const XMLNode&);
1444
1445         /* mixer stuff */
1446
1447         bool       solo_update_disabled;
1448         bool       currently_soloing;
1449         
1450         void route_mute_changed (void *src);
1451         void route_solo_changed (void *src, boost::weak_ptr<Route>);
1452         void catch_up_on_solo ();
1453         void update_route_solo_state ();
1454         void modify_solo_mute (bool, bool);
1455         void strip_portname_for_solo (string& portname);
1456
1457         /* REGION MANAGEMENT */
1458
1459         mutable Glib::Mutex region_lock;
1460         typedef map<PBD::ID,boost::shared_ptr<Region> > RegionList;
1461         RegionList regions;
1462         
1463         void add_region (boost::shared_ptr<Region>);
1464         void region_changed (Change, boost::weak_ptr<Region>);
1465         void remove_region (boost::weak_ptr<Region>);
1466
1467         int load_regions (const XMLNode& node);
1468
1469         /* SOURCES */
1470         
1471         mutable Glib::Mutex source_lock;
1472         typedef std::map<PBD::ID,boost::shared_ptr<Source> > SourceMap;
1473
1474         SourceMap sources;
1475
1476         int load_sources (const XMLNode& node);
1477         XMLNode& get_sources_as_xml ();
1478
1479         boost::shared_ptr<Source> XMLSourceFactory (const XMLNode&);
1480
1481         /* PLAYLISTS */
1482         
1483         mutable Glib::Mutex playlist_lock;
1484         typedef set<boost::shared_ptr<Playlist> > PlaylistList;
1485         PlaylistList playlists;
1486         PlaylistList unused_playlists;
1487
1488         int load_playlists (const XMLNode&);
1489         int load_unused_playlists (const XMLNode&);
1490         void remove_playlist (boost::weak_ptr<Playlist>);
1491         void track_playlist (bool, boost::weak_ptr<Playlist>);
1492
1493         boost::shared_ptr<Playlist> playlist_factory (string name);
1494         boost::shared_ptr<Playlist> XMLPlaylistFactory (const XMLNode&);
1495
1496         void playlist_length_changed ();
1497         void diskstream_playlist_changed (boost::shared_ptr<Diskstream>);
1498
1499         /* NAMED SELECTIONS */
1500
1501         mutable Glib::Mutex named_selection_lock;
1502         typedef set<NamedSelection *> NamedSelectionList;
1503         NamedSelectionList named_selections;
1504
1505         int load_named_selections (const XMLNode&);
1506
1507         NamedSelection *named_selection_factory (string name);
1508         NamedSelection *XMLNamedSelectionFactory (const XMLNode&);
1509
1510         /* CURVES and AUTOMATION LISTS */
1511         std::map<PBD::ID, Curve*> curves;
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&, nframes_t start, nframes_t cnt);
1531
1532         /* INSERT AND SEND MANAGEMENT */
1533         
1534         list<PortInsert *>   _port_inserts;
1535         list<PluginInsert *> _plugin_inserts;
1536         list<Send *>         _sends;
1537         boost::dynamic_bitset<uint32_t>  send_bitset;
1538         boost::dynamic_bitset<uint32_t>  insert_bitset;
1539         uint32_t          send_cnt;
1540         uint32_t          insert_cnt;
1541
1542
1543         void add_redirect (Redirect *);
1544         void remove_redirect (Redirect *);
1545
1546         /* S/W RAID */
1547
1548         struct space_and_path {
1549             uint32_t blocks; /* 4kB blocks */
1550             string path;
1551             
1552             space_and_path() { 
1553                     blocks = 0;
1554             }
1555         };
1556
1557         struct space_and_path_ascending_cmp {
1558             bool operator() (space_and_path a, space_and_path b) {
1559                     return a.blocks > b.blocks;
1560             }
1561         };
1562         
1563         void setup_raid_path (string path);
1564
1565         vector<space_and_path> session_dirs;
1566         vector<space_and_path>::iterator last_rr_session_dir;
1567         uint32_t _total_free_4k_blocks;
1568         Glib::Mutex space_lock;
1569
1570         static const char* old_sound_dir_name;
1571         static const char* sound_dir_name;
1572         static const char* dead_sound_dir_name;
1573         static const char* interchange_dir_name;
1574         static const char* peak_dir_name;
1575         static const char* export_dir_name;
1576         
1577         string old_sound_dir (bool with_path = true) const;
1578         string discover_best_sound_dir (bool destructive = false);
1579         int ensure_sound_dir (string, string&);
1580         void refresh_disk_space ();
1581
1582         mutable gint _playback_load;
1583         mutable gint _capture_load;
1584         mutable gint _playback_load_min;
1585         mutable gint _capture_load_min;
1586
1587         /* I/O Connections */
1588
1589         typedef list<Connection *> ConnectionList;
1590         mutable Glib::Mutex connection_lock;
1591         ConnectionList _connections;
1592         int load_connections (const XMLNode&);
1593
1594         void reverse_diskstream_buffers ();
1595
1596         UndoHistory _history;
1597         UndoTransaction* current_trans;
1598
1599         GlobalRouteBooleanState get_global_route_boolean (bool (Route::*method)(void) const);
1600         GlobalRouteMeterState get_global_route_metering ();
1601
1602         void set_global_route_boolean (GlobalRouteBooleanState s, void (Route::*method)(bool, void*), void *arg);
1603         void set_global_route_metering (GlobalRouteMeterState s, void *arg);
1604
1605         void set_global_mute (GlobalRouteBooleanState s, void *src);
1606         void set_global_solo (GlobalRouteBooleanState s, void *src);
1607         void set_global_record_enable (GlobalRouteBooleanState s, void *src);
1608
1609         void jack_timebase_callback (jack_transport_state_t, nframes_t, jack_position_t*, int);
1610         int  jack_sync_callback (jack_transport_state_t, jack_position_t*);
1611         void reset_jack_connection (jack_client_t* jack);
1612         void record_enable_change_all (bool yn);
1613
1614         XMLNode& state(bool);
1615
1616         /* click track */
1617
1618         struct Click {
1619             nframes_t start;
1620             nframes_t duration;
1621             nframes_t offset;
1622             const Sample *data;
1623
1624             Click (nframes_t s, nframes_t d, const Sample *b) 
1625                     : start (s), duration (d), data (b) { offset = 0; }
1626             
1627             void *operator new(size_t ignored) {
1628                     return pool.alloc ();
1629             };
1630
1631             void operator delete(void *ptr, size_t size) {
1632                     pool.release (ptr);
1633             }
1634
1635           private:
1636             static Pool pool;
1637         };
1638  
1639         typedef list<Click*> Clicks;
1640
1641         Clicks          clicks;
1642         bool           _clicking;
1643         boost::shared_ptr<IO> _click_io;
1644         Sample*         click_data;
1645         Sample*         click_emphasis_data;
1646         nframes_t  click_length;
1647         nframes_t  click_emphasis_length;
1648         mutable Glib::RWLock click_lock;
1649
1650         static const Sample         default_click[];
1651         static const nframes_t default_click_length;
1652         static const Sample         default_click_emphasis[];
1653         static const nframes_t default_click_emphasis_length;
1654
1655         Click *get_click();
1656         void   setup_click_sounds (int which);
1657         void   clear_clicks ();
1658         void   click (nframes_t start, nframes_t nframes, nframes_t offset);
1659
1660         vector<Route*> master_outs;
1661         
1662         /* range playback */
1663
1664         list<AudioRange> current_audio_range;
1665         bool _play_range;
1666         void set_play_range (bool yn);
1667         void setup_auto_play ();
1668
1669         /* main outs */
1670         uint32_t main_outs;
1671         
1672         boost::shared_ptr<IO> _master_out;
1673         boost::shared_ptr<IO> _control_out;
1674
1675         gain_t* _gain_automation_buffer;
1676         pan_t** _pan_automation_buffer;
1677         void allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force);
1678         uint32_t _npan_buffers;
1679
1680         /* VST support */
1681
1682         long _vst_callback (VSTPlugin*,
1683                             long opcode,
1684                             long index,
1685                             long value,
1686                             void* ptr,
1687                             float opt);
1688
1689         /* number of hardware ports we're using,
1690            based on max (requested,available)
1691         */
1692
1693         uint32_t n_physical_outputs;
1694         uint32_t n_physical_inputs;
1695
1696         void remove_pending_capture_state ();
1697
1698         int find_all_sources (std::string path, std::set<std::string>& result);
1699         int find_all_sources_across_snapshots (std::set<std::string>& result, bool exclude_this_snapshot);
1700
1701         LayerModel layer_model;
1702         CrossfadeModel xfade_model;
1703
1704         typedef std::set<PBD::Controllable*> Controllables;
1705         Glib::Mutex controllables_lock;
1706         Controllables controllables;
1707
1708         void reset_native_file_format();
1709         bool first_file_data_format_reset;
1710         bool first_file_header_format_reset;
1711
1712         void config_changed (const char*);
1713
1714         XMLNode& get_control_protocol_state ();
1715         
1716 };
1717
1718 } // namespace ARDOUR
1719
1720 #endif /* __ardour_session_h__ */