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