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