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