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