3d70520c49c05987d0e275f0db6042c44e15eb0a
[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 ControlProtocolManager;
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 sigc::trackable, 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             jack_nframes_t action_frame;
158             jack_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, jack_nframes_t when, jack_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 jack_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                  jack_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 (jack_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,jack_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 (jack_nframes_t start, jack_nframes_t end);
347         void request_stop (bool abort = false);
348         void request_locate (jack_nframes_t frame, bool with_roll = false);
349         void request_play_loop (bool yn);
350         jack_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 (jack_nframes_t start) { start_location->set_start(start); }
354         void set_session_end (jack_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         jack_nframes_t get_maximum_extent () const;
369         jack_nframes_t current_end_frame() const { return end_location->start(); }
370         jack_nframes_t current_start_frame() const { return start_location->start(); }
371         jack_nframes_t frame_rate() const   { return _current_frame_rate; }
372         jack_nframes_t frames_per_hour() const { return _frames_per_hour; }
373
374         double frames_per_smpte_frame() const { return _frames_per_smpte_frame; }
375         jack_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 (jack_nframes_t action_frame, Event::Type type, jack_nframes_t target_frame = 0);
391         void remove_event (jack_nframes_t frame, Event::Type type);
392         void clear_events (Event::Type type);
393
394         jack_nframes_t get_block_size() const { return current_block_size; }
395         jack_nframes_t worst_output_latency () const { return _worst_output_latency; }
396         jack_nframes_t worst_input_latency () const { return _worst_input_latency; }
397         jack_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         jack_nframes_t transport_frame () const {return _transport_frame; }
477         jack_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 (jack_nframes_t when, BBT_Time&);
509         void smpte_to_sample( SMPTE::Time& smpte, jack_nframes_t& sample, bool use_offset, bool use_subframes ) const;
510         void sample_to_smpte( jack_nframes_t sample, SMPTE::Time& smpte, bool use_offset, bool use_subframes ) const;
511         void smpte_time (SMPTE::Time &);
512         void smpte_time (jack_nframes_t when, SMPTE::Time&);
513         void smpte_time_subframes (jack_nframes_t when, SMPTE::Time&);
514
515         void smpte_duration (jack_nframes_t, SMPTE::Time&) const;
516         void smpte_duration_string (char *, jack_nframes_t) const;
517
518         void           set_smpte_offset (jack_nframes_t);
519         jack_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         jack_nframes_t convert_to_frames_at (jack_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 (jack_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         jack_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&, jack_nframes_t start, jack_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         jack_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 (jack_nframes_t where);
733         void stop_scrub ();
734         void set_scrub_speed (float);
735         jack_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         /* need to call this whenever we change native file formats */
837
838         void reset_native_file_format();
839
840         /* disk, buffer loads */
841
842         uint32_t playback_load ();
843         uint32_t capture_load ();
844         uint32_t playback_load_min ();
845         uint32_t capture_load_min ();
846
847         void reset_playback_load_min ();
848         void reset_capture_load_min ();
849         
850         float read_data_rate () const;
851         float write_data_rate () const;
852
853         /* ranges */
854
855         void set_audio_range (list<AudioRange>&);
856         void set_music_range (list<MusicRange>&);
857
858         void request_play_range (bool yn);
859         bool get_play_range () const { return _play_range; }
860
861         /* favorite dirs */
862         typedef vector<string> FavoriteDirs;
863
864         static int read_favorite_dirs (FavoriteDirs&);
865
866         static int write_favorite_dirs (FavoriteDirs&);
867         
868         /* file suffixes */
869
870         static const char* template_suffix() { return _template_suffix; }
871         static const char* statefile_suffix() { return _statefile_suffix; }
872         static const char* pending_suffix() { return _pending_suffix; }
873
874         /* buffers for gain and pan */
875
876         gain_t* gain_automation_buffer () const { return _gain_automation_buffer; }
877         pan_t** pan_automation_buffer() const { return _pan_automation_buffer; }
878
879         /* buffers for conversion */
880         enum RunContext {
881                 ButlerContext = 0,
882                 TransportContext,
883                 ExportContext
884         };
885         
886         /* VST support */
887
888         static long vst_callback (AEffect* effect,
889                                   long opcode,
890                                   long index,
891                                   long value,
892                                   void* ptr,
893                                   float opt);
894
895         typedef float (*compute_peak_t)                         (Sample *, jack_nframes_t, float);
896         typedef void  (*apply_gain_to_buffer_t)         (Sample *, jack_nframes_t, float);
897         typedef void  (*mix_buffers_with_gain_t)        (Sample *, Sample *, jack_nframes_t, float);
898         typedef void  (*mix_buffers_no_gain_t)          (Sample *, Sample *, jack_nframes_t);
899
900         static compute_peak_t                   compute_peak;
901         static apply_gain_to_buffer_t   apply_gain_to_buffer;
902         static mix_buffers_with_gain_t  mix_buffers_with_gain;
903         static mix_buffers_no_gain_t    mix_buffers_no_gain;
904
905         static sigc::signal<void> SendFeedback;
906
907         /* Controllables */
908
909         PBD::Controllable* controllable_by_id (const PBD::ID&);
910
911   protected:
912         friend class AudioEngine;
913         void set_block_size (jack_nframes_t nframes);
914         void set_frame_rate (jack_nframes_t nframes);
915
916   protected:
917         friend class Diskstream;
918         void stop_butler ();
919         void wait_till_butler_finished();
920
921   protected:
922         friend class Route;
923         void schedule_curve_reallocation ();
924         void update_latency_compensation (bool, bool);
925         
926   private:
927         int  create (bool& new_session, string* mix_template, jack_nframes_t initial_length);
928
929         static const char* _template_suffix;
930         static const char* _statefile_suffix;
931         static const char* _pending_suffix;
932
933         enum SubState {
934                 PendingDeclickIn   = 0x1,
935                 PendingDeclickOut  = 0x2,
936                 StopPendingCapture = 0x4,
937                 AutoReturning      = 0x10,
938                 PendingLocate      = 0x20,
939                 PendingSetLoop     = 0x40
940         };
941
942         /* stuff used in process() should be close together to
943            maximise cache hits
944         */
945
946         typedef void (Session::*process_function_type)(jack_nframes_t);
947
948         AudioEngine            &_engine;
949         mutable gint            processing_prohibited;
950         process_function_type    process_function;
951         process_function_type    last_process_function;
952         bool                     waiting_for_sync_offset;
953         jack_nframes_t          _base_frame_rate;
954         jack_nframes_t          _current_frame_rate;  //this includes video pullup offset
955         int                      transport_sub_state;
956         mutable gint           _record_status;
957         jack_nframes_t          _transport_frame;
958         Location*                end_location;
959         Location*                start_location;
960         Slave                  *_slave;
961         volatile float          _transport_speed;
962         volatile float          _desired_transport_speed;
963         float                   _last_transport_speed;
964         jack_nframes_t          _last_slave_transport_frame;
965         jack_nframes_t           maximum_output_latency;
966         jack_nframes_t           last_stop_frame;
967         vector<Sample *>        _passthru_buffers;
968         vector<Sample *>        _silent_buffers;
969         vector<Sample *>        _send_buffers;
970         jack_nframes_t           current_block_size;
971         jack_nframes_t          _worst_output_latency;
972         jack_nframes_t          _worst_input_latency;
973         jack_nframes_t          _worst_track_latency;
974         bool                    _have_captured;
975         float                   _meter_hold;
976         float                   _meter_falloff;
977         bool                    _end_location_is_free;
978
979         void set_worst_io_latencies ();
980         void set_worst_io_latencies_x (IOChange asifwecare, void *ignored) {
981                 set_worst_io_latencies ();
982         }
983
984         void update_latency_compensation_proxy (void* ignored);
985
986         void ensure_passthru_buffers (uint32_t howmany);
987         
988         void process_scrub          (jack_nframes_t);
989         void process_without_events (jack_nframes_t);
990         void process_with_events    (jack_nframes_t);
991         void process_audition       (jack_nframes_t);
992         int  process_export         (jack_nframes_t, ARDOUR::AudioExportSpecification*);
993         
994         /* slave tracking */
995
996         static const int delta_accumulator_size = 25;
997         int delta_accumulator_cnt;
998         long delta_accumulator[delta_accumulator_size];
999         long average_slave_delta;
1000         int  average_dir;
1001         bool have_first_delta_accumulator;
1002         
1003         enum SlaveState {
1004                 Stopped,
1005                 Waiting,
1006                 Running
1007         };
1008         
1009         SlaveState slave_state;
1010         jack_nframes_t slave_wait_end;
1011
1012         void reset_slave_state ();
1013         bool follow_slave (jack_nframes_t, jack_nframes_t);
1014         void set_slave_source (SlaveSource);
1015
1016         bool _exporting;
1017         int prepare_to_export (ARDOUR::AudioExportSpecification&);
1018
1019         void prepare_diskstreams ();
1020         void commit_diskstreams (jack_nframes_t, bool& session_requires_butler);
1021         int  process_routes (jack_nframes_t, jack_nframes_t);
1022         int  silent_process_routes (jack_nframes_t, jack_nframes_t);
1023
1024         bool get_rec_monitors_input () {
1025                 if (actively_recording()) {
1026                         return true;
1027                 } else {
1028                         if (Config->get_auto_input()) {
1029                                 return false;
1030                         } else {
1031                                 return true;
1032                         }
1033                 }
1034         }
1035
1036         int get_transport_declick_required () {
1037
1038                 if (transport_sub_state & PendingDeclickIn) {
1039                         transport_sub_state &= ~PendingDeclickIn;
1040                         return 1;
1041                 } else if (transport_sub_state & PendingDeclickOut) {
1042                         return -1;
1043                 } else {
1044                         return 0;
1045                 }
1046         }
1047
1048         bool maybe_stop (jack_nframes_t limit) {
1049                 if ((_transport_speed > 0.0f && _transport_frame >= limit) || (_transport_speed < 0.0f && _transport_frame == 0)) {
1050                         stop_transport ();
1051                         return true;
1052                 }
1053                 return false;
1054         }
1055
1056         bool maybe_sync_start (jack_nframes_t&, jack_nframes_t&);
1057
1058         void check_declick_out ();
1059
1060         MIDI::MachineControl*    mmc;
1061         MIDI::Port*             _mmc_port;
1062         MIDI::Port*             _mtc_port;
1063         MIDI::Port*             _midi_port;
1064         string                  _path;
1065         string                  _name;
1066         bool                     session_send_mmc;
1067         bool                     session_send_mtc;
1068         bool                     session_midi_feedback;
1069         bool                     play_loop;
1070         bool                     loop_changing;
1071         jack_nframes_t           last_loopend;
1072
1073         RingBuffer<Event*> pending_events;
1074
1075         void hookup_io ();
1076         void when_engine_running ();
1077         sigc::connection first_time_running;
1078         void graph_reordered ();
1079
1080         string _current_snapshot_name;
1081
1082         XMLTree* state_tree;
1083         bool     state_was_pending;
1084         StateOfTheState _state_of_the_state;
1085
1086         void     auto_save();
1087         int      load_options (const XMLNode&);
1088         XMLNode& get_options () const;
1089         int      load_state (string snapshot_name);
1090
1091         jack_nframes_t   _last_roll_location;
1092         jack_nframes_t   _last_record_location;
1093         bool              pending_locate_roll;
1094         jack_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 (jack_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, jack_nframes_t action_frame, jack_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, jack_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         jack_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         jack_nframes_t _frames_per_hour;
1277         jack_nframes_t _smpte_frames_per_hour;
1278         jack_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         jack_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, jack_nframes_t frame = 0);
1297
1298         jack_nframes_t adjust_apparent_position (jack_nframes_t frames);
1299         
1300         void reset_record_status ();
1301         
1302         int no_roll (jack_nframes_t nframes, jack_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             jack_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 (jack_nframes_t, bool with_roll, bool with_flush, bool with_loop=false);
1371         void start_locate (jack_nframes_t, bool with_roll, bool with_flush, bool with_loop=false);
1372         void force_locate (jack_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::shared_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 region_renamed (boost::shared_ptr<Region>);
1438         void region_changed (Change, boost::shared_ptr<Region>);
1439         void add_region (boost::shared_ptr<Region>);
1440         void remove_region (boost::shared_ptr<Region>);
1441
1442         int load_regions (const XMLNode& node);
1443
1444         /* SOURCES */
1445         
1446         mutable Glib::Mutex audio_source_lock;
1447         typedef std::map<PBD::ID,boost::shared_ptr<AudioSource> > AudioSourceList;
1448
1449         AudioSourceList audio_sources;
1450
1451         int load_sources (const XMLNode& node);
1452         XMLNode& get_sources_as_xml ();
1453
1454         boost::shared_ptr<Source> XMLSourceFactory (const XMLNode&);
1455
1456         /* PLAYLISTS */
1457         
1458         mutable Glib::Mutex playlist_lock;
1459         typedef set<Playlist *> PlaylistList;
1460         PlaylistList playlists;
1461         PlaylistList unused_playlists;
1462
1463         int load_playlists (const XMLNode&);
1464         int load_unused_playlists (const XMLNode&);
1465         void remove_playlist (Playlist *);
1466         void track_playlist (Playlist *, bool);
1467
1468         Playlist *playlist_factory (string name);
1469         Playlist *XMLPlaylistFactory (const XMLNode&);
1470
1471         void playlist_length_changed (Playlist *);
1472         void diskstream_playlist_changed (boost::shared_ptr<Diskstream>);
1473
1474         /* NAMED SELECTIONS */
1475
1476         mutable Glib::Mutex named_selection_lock;
1477         typedef set<NamedSelection *> NamedSelectionList;
1478         NamedSelectionList named_selections;
1479
1480         int load_named_selections (const XMLNode&);
1481
1482         NamedSelection *named_selection_factory (string name);
1483         NamedSelection *XMLNamedSelectionFactory (const XMLNode&);
1484
1485         /* CURVES and AUTOMATION LISTS */
1486         std::map<PBD::ID, Curve*> curves;
1487         std::map<PBD::ID, AutomationList*> automation_lists;
1488
1489         /* DEFAULT FADE CURVES */
1490
1491         float default_fade_steepness;
1492         float default_fade_msecs;
1493
1494         /* AUDITIONING */
1495
1496         boost::shared_ptr<Auditioner> auditioner;
1497         void set_audition (boost::shared_ptr<Region>);
1498         void non_realtime_set_audition ();
1499         boost::shared_ptr<Region> pending_audition_region;
1500
1501         /* EXPORT */
1502
1503         /* FLATTEN */
1504
1505         int flatten_one_track (AudioTrack&, jack_nframes_t start, jack_nframes_t cnt);
1506
1507         /* INSERT AND SEND MANAGEMENT */
1508         
1509         list<PortInsert *>   _port_inserts;
1510         list<PluginInsert *> _plugin_inserts;
1511         list<Send *>         _sends;
1512         uint32_t          send_cnt;
1513         uint32_t          insert_cnt;
1514
1515         void add_redirect (Redirect *);
1516         void remove_redirect (Redirect *);
1517
1518         /* S/W RAID */
1519
1520         struct space_and_path {
1521             uint32_t blocks; /* 4kB blocks */
1522             string path;
1523             
1524             space_and_path() { 
1525                     blocks = 0;
1526             }
1527         };
1528
1529         struct space_and_path_ascending_cmp {
1530             bool operator() (space_and_path a, space_and_path b) {
1531                     return a.blocks > b.blocks;
1532             }
1533         };
1534         
1535         void setup_raid_path (string path);
1536
1537         vector<space_and_path> session_dirs;
1538         vector<space_and_path>::iterator last_rr_session_dir;
1539         uint32_t _total_free_4k_blocks;
1540         Glib::Mutex space_lock;
1541
1542         static const char* old_sound_dir_name;
1543         static const char* sound_dir_name;
1544         static const char* dead_sound_dir_name;
1545         static const char* interchange_dir_name;
1546         static const char* peak_dir_name;
1547
1548         string discover_best_sound_dir (bool destructive = false);
1549         int ensure_sound_dir (string, string&);
1550         void refresh_disk_space ();
1551
1552         mutable gint _playback_load;
1553         mutable gint _capture_load;
1554         mutable gint _playback_load_min;
1555         mutable gint _capture_load_min;
1556
1557         /* I/O Connections */
1558
1559         typedef list<Connection *> ConnectionList;
1560         mutable Glib::Mutex connection_lock;
1561         ConnectionList _connections;
1562         int load_connections (const XMLNode&);
1563
1564         void reverse_diskstream_buffers ();
1565
1566         UndoHistory history;
1567         UndoTransaction* current_trans;
1568
1569         GlobalRouteBooleanState get_global_route_boolean (bool (Route::*method)(void) const);
1570         GlobalRouteMeterState get_global_route_metering ();
1571
1572         void set_global_route_boolean (GlobalRouteBooleanState s, void (Route::*method)(bool, void*), void *arg);
1573         void set_global_route_metering (GlobalRouteMeterState s, void *arg);
1574
1575         void set_global_mute (GlobalRouteBooleanState s, void *src);
1576         void set_global_solo (GlobalRouteBooleanState s, void *src);
1577         void set_global_record_enable (GlobalRouteBooleanState s, void *src);
1578
1579         void jack_timebase_callback (jack_transport_state_t, jack_nframes_t, jack_position_t*, int);
1580         int  jack_sync_callback (jack_transport_state_t, jack_position_t*);
1581         void record_enable_change_all (bool yn);
1582
1583         XMLNode& state(bool);
1584
1585         /* click track */
1586
1587         struct Click {
1588             jack_nframes_t start;
1589             jack_nframes_t duration;
1590             jack_nframes_t offset;
1591             const Sample *data;
1592
1593             Click (jack_nframes_t s, jack_nframes_t d, const Sample *b) 
1594                     : start (s), duration (d), data (b) { offset = 0; }
1595             
1596             void *operator new(size_t ignored) {
1597                     return pool.alloc ();
1598             };
1599
1600             void operator delete(void *ptr, size_t size) {
1601                     pool.release (ptr);
1602             }
1603
1604           private:
1605             static Pool pool;
1606         };
1607  
1608         typedef list<Click*> Clicks;
1609
1610         Clicks          clicks;
1611         bool           _clicking;
1612         boost::shared_ptr<IO> _click_io;
1613         Sample*         click_data;
1614         Sample*         click_emphasis_data;
1615         jack_nframes_t  click_length;
1616         jack_nframes_t  click_emphasis_length;
1617         mutable Glib::RWLock click_lock;
1618
1619         static const Sample         default_click[];
1620         static const jack_nframes_t default_click_length;
1621         static const Sample         default_click_emphasis[];
1622         static const jack_nframes_t default_click_emphasis_length;
1623
1624         Click *get_click();
1625         void   setup_click_sounds (int which);
1626         void   clear_clicks ();
1627         void   click (jack_nframes_t start, jack_nframes_t nframes, jack_nframes_t offset);
1628
1629         vector<Route*> master_outs;
1630         
1631         /* range playback */
1632
1633         list<AudioRange> current_audio_range;
1634         bool _play_range;
1635         void set_play_range (bool yn);
1636         void setup_auto_play ();
1637
1638         /* main outs */
1639         uint32_t main_outs;
1640         
1641         boost::shared_ptr<IO> _master_out;
1642         boost::shared_ptr<IO> _control_out;
1643
1644         AutoConnectOption input_auto_connect;
1645         AutoConnectOption output_auto_connect;
1646
1647         gain_t* _gain_automation_buffer;
1648         pan_t** _pan_automation_buffer;
1649         void allocate_pan_automation_buffers (jack_nframes_t nframes, uint32_t howmany, bool force);
1650         uint32_t _npan_buffers;
1651
1652         /* VST support */
1653
1654         long _vst_callback (VSTPlugin*,
1655                             long opcode,
1656                             long index,
1657                             long value,
1658                             void* ptr,
1659                             float opt);
1660
1661         /* number of hardware audio ports we're using,
1662            based on max (requested,available)
1663         */
1664
1665         uint32_t n_physical_outputs;
1666         uint32_t n_physical_inputs;
1667
1668         void remove_pending_capture_state ();
1669
1670         int find_all_sources (std::string path, std::set<std::string>& result);
1671         int find_all_sources_across_snapshots (std::set<std::string>& result, bool exclude_this_snapshot);
1672
1673         LayerModel layer_model;
1674         CrossfadeModel xfade_model;
1675
1676         typedef std::list<PBD::Controllable*> Controllables;
1677         Glib::Mutex controllables_lock;
1678         Controllables controllables;
1679
1680         void add_controllable (PBD::Controllable*);
1681         void remove_controllable (PBD::Controllable*);
1682
1683         void config_changed (const char*);
1684 };
1685
1686 } // namespace ARDOUR
1687
1688 #endif /* __ardour_session_h__ */