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