show a different audio/MIDI option screen if JACK is already running. try to fix...
[ardour.git] / gtk2_ardour / engine_dialog.cc
1 /*
2     Copyright (C) 2010 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 #include <exception>
21 #include <vector>
22 #include <cmath>
23 #include <fstream>
24 #include <map>
25
26 #include <boost/scoped_ptr.hpp>
27
28 #include <gtkmm/messagedialog.h>
29
30 #include "pbd/error.h"
31 #include "pbd/xml++.h"
32 #include "pbd/unwind.h"
33
34 #include <gtkmm/alignment.h>
35 #include <gtkmm/stock.h>
36 #include <gtkmm/notebook.h>
37 #include <gtkmm2ext/utils.h>
38
39 #include "ardour/audio_backend.h"
40 #include "ardour/audioengine.h"
41 #include "ardour/mtdm.h"
42 #include "ardour/rc_configuration.h"
43 #include "ardour/types.h"
44
45 #include "pbd/convert.h"
46 #include "pbd/error.h"
47
48 #include "ardour_ui.h"
49 #include "engine_dialog.h"
50 #include "gui_thread.h"
51 #include "i18n.h"
52
53 using namespace std;
54 using namespace Gtk;
55 using namespace Gtkmm2ext;
56 using namespace PBD;
57 using namespace Glib;
58
59 EngineControl::EngineControl ()
60         : ArdourDialog (_("Audio/MIDI Setup"))
61         , basic_packer (9, 3)
62         , input_latency_adjustment (0, 0, 99999, 1)
63         , input_latency (input_latency_adjustment)
64         , output_latency_adjustment (0, 0, 99999, 1)
65         , output_latency (output_latency_adjustment)
66         , input_channels_adjustment (0, 0, 256, 1)
67         , input_channels (input_channels_adjustment)
68         , output_channels_adjustment (0, 0, 256, 1)
69         , output_channels (output_channels_adjustment)
70         , ports_adjustment (128, 8, 1024, 1, 16)
71         , ports_spinner (ports_adjustment)
72         , control_app_button (_("Device Control Panel"))
73         , lm_start_stop_label (_("Measure latency"))
74         , lm_use_button (_("Use results"))
75         , lm_table (5, 2)
76         , have_lm_results (false)
77         , midi_refresh_button (_("Refresh list"))
78         , aj_button (_("Start MIDI ALSA/JACK bridge"))
79         , ignore_changes (0)
80         , _desired_sample_rate (0)
81         , no_push (true)
82 {
83         using namespace Notebook_Helpers;
84         vector<string> strings;
85         Label* label;
86         AttachOptions xopt = AttachOptions (FILL|EXPAND);
87         int row;
88
89         set_name (X_("AudioMIDISetup"));
90
91         /* the backend combo is the one thing that is ALWAYS visible 
92          */
93
94         vector<const ARDOUR::AudioBackendInfo*> backends = ARDOUR::AudioEngine::instance()->available_backends();
95         for (vector<const ARDOUR::AudioBackendInfo*>::const_iterator b = backends.begin(); b != backends.end(); ++b) {
96                 strings.push_back ((*b)->name);
97         }
98
99         set_popdown_strings (backend_combo, strings);
100         backend_combo.set_active_text (strings.front());
101         backend_combo.signal_changed().connect (sigc::mem_fun (*this, &EngineControl::backend_changed));
102
103         /* setup basic packing characteristics for the table used on the main
104          * tab of the notebook
105          */
106
107         basic_packer.set_spacings (6);
108         basic_packer.set_border_width (12);
109         basic_packer.set_homogeneous (true);
110
111         /* pack it in */
112
113         basic_hbox.pack_start (basic_packer, false, false);
114
115         /* latency tab */
116
117         /* latency measurement tab */
118         
119         lm_title.set_markup (string_compose ("<span size=\"large\" weight=\"bold\">%1</span>", _("Latency Measurement Tool")));
120         
121         row = 0;
122         lm_table.set_row_spacings (12);
123
124         lm_table.attach (lm_title, 0, 2, row, row+1, xopt, (AttachOptions) 0);
125         row++;
126
127         Gtk::Label* preamble;
128
129         preamble = manage (new Label);
130         preamble->set_width_chars (60);
131         preamble->set_line_wrap (true);
132         preamble->set_markup (_("<span weight=\"bold\">Turn down the volume on your hardware to a very low level.</span>"));
133
134         lm_table.attach (*preamble, 0, 2, row, row+1, AttachOptions(FILL|EXPAND), (AttachOptions) 0);
135         row++;
136
137         preamble = manage (new Label);
138         preamble->set_width_chars (60);
139         preamble->set_line_wrap (true);
140         preamble->set_markup (_("Select two channels below and connect them using a cable or (less ideally) a speaker and microphone."));
141
142         lm_table.attach (*preamble, 0, 2, row, row+1, AttachOptions(FILL|EXPAND), (AttachOptions) 0);
143         row++;
144
145         label = manage (new Label (_("Output channel")));
146         lm_table.attach (*label, 0, 1, row, row+1, xopt, (AttachOptions) 0);
147
148         Gtk::Alignment* misc_align = manage (new Alignment (0.0, 0.5));
149         misc_align->add (lm_output_channel_combo);
150         lm_table.attach (*misc_align, 1, 2, row, row+1, xopt, (AttachOptions) 0);
151         ++row;
152
153         label = manage (new Label (_("Input channel")));
154         lm_table.attach (*label, 0, 1, row, row+1, xopt, (AttachOptions) 0);
155
156         misc_align = manage (new Alignment (0.0, 0.5));
157         misc_align->add (lm_input_channel_combo);
158         lm_table.attach (*misc_align, 1, 2, row, row+1, FILL, (AttachOptions) 0);
159         ++row;
160
161         xopt = AttachOptions(0);
162
163         lm_measure_button.add (lm_start_stop_label);
164         
165         lm_measure_button.signal_toggled().connect (sigc::mem_fun (*this, &EngineControl::latency_button_toggled));
166         lm_use_button.signal_clicked().connect (sigc::mem_fun (*this, &EngineControl::use_latency_button_clicked));
167         lm_use_button.set_sensitive (false);
168
169         preamble = manage (new Label);
170         preamble->set_width_chars (60);
171         preamble->set_line_wrap (true);
172         preamble->set_markup (_("Once the channels are connected, click the \"Measure latency\" button."));
173         lm_table.attach (*preamble, 0, 2, row, row+1, AttachOptions(FILL|EXPAND), (AttachOptions) 0);
174         row++;
175
176         lm_table.attach (lm_measure_button, 0, 2, row, row+1, xopt, (AttachOptions) 0);
177         ++row;
178         lm_table.attach (lm_results, 0, 2, row, row+1, AttachOptions(FILL|EXPAND), (AttachOptions) 0);
179         ++row;
180
181
182         preamble = manage (new Label);
183         preamble->set_width_chars (60);
184         preamble->set_line_wrap (true);
185         preamble->set_markup (_("When satisfied with the results, click the \"Use results\" button."));
186         lm_table.attach (*preamble, 0, 2, row, row+1, AttachOptions(FILL|EXPAND), (AttachOptions) 0);
187         row++;
188
189         lm_table.attach (lm_use_button, 0, 2, row, row+1, xopt, (AttachOptions) 0);
190         ++row;
191
192         lm_results.set_markup ("<i>No measurement results yet</i>");
193
194         lm_vbox.set_border_width (12);
195         lm_vbox.pack_start (lm_table, false, false);
196
197         /* pack it all up */
198
199         notebook.pages().push_back (TabElem (basic_vbox, _("Audio")));
200         notebook.pages().push_back (TabElem (midi_vbox, _("MIDI")));
201         notebook.pages().push_back (TabElem (lm_vbox, _("Latency")));
202         notebook.set_border_width (12);
203
204         notebook.set_tab_pos (POS_RIGHT);
205         notebook.show_all ();
206
207         notebook.set_name ("SettingsNotebook");
208
209         /* packup the notebook */
210
211         get_vbox()->set_border_width (12);
212         get_vbox()->pack_start (notebook);
213
214         /* need a special function to print "all available channels" when the
215          * channel counts hit zero.
216          */
217
218         input_channels.signal_output().connect (sigc::bind (sigc::ptr_fun (&EngineControl::print_channel_count), &input_channels));
219         output_channels.signal_output().connect (sigc::bind (sigc::ptr_fun (&EngineControl::print_channel_count), &output_channels));
220
221         control_app_button.signal_clicked().connect (mem_fun (*this, &EngineControl::control_app_button_clicked));
222         manage_control_app_sensitivity ();
223
224         cancel_button = add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
225         ok_button = add_button (Gtk::Stock::OK, Gtk::RESPONSE_OK);
226         apply_button = add_button (Gtk::Stock::APPLY, Gtk::RESPONSE_APPLY);
227
228         /* Pick up any existing audio setup configuration, if appropriate */
229
230         XMLNode* audio_setup = ARDOUR::Config->extra_xml ("AudioMIDISetup");
231         
232         ARDOUR::AudioEngine::instance()->Running.connect (running_connection, MISSING_INVALIDATOR, boost::bind (&EngineControl::engine_running, this), gui_context());
233         ARDOUR::AudioEngine::instance()->Stopped.connect (stopped_connection, MISSING_INVALIDATOR, boost::bind (&EngineControl::engine_stopped, this), gui_context());
234         ARDOUR::AudioEngine::instance()->Halted.connect (stopped_connection, MISSING_INVALIDATOR, boost::bind (&EngineControl::engine_stopped, this), gui_context());
235
236         backend_changed ();
237
238         if (audio_setup) {
239                 set_state (*audio_setup);
240         }
241
242         /* Connect to signals */
243
244         driver_combo.signal_changed().connect (sigc::mem_fun (*this, &EngineControl::driver_changed));
245         sample_rate_combo.signal_changed().connect (sigc::mem_fun (*this, &EngineControl::sample_rate_changed));
246         buffer_size_combo.signal_changed().connect (sigc::mem_fun (*this, &EngineControl::buffer_size_changed));
247         device_combo.signal_changed().connect (sigc::mem_fun (*this, &EngineControl::device_changed));
248
249         input_latency.signal_changed().connect (sigc::mem_fun (*this, &EngineControl::parameter_changed));
250         output_latency.signal_changed().connect (sigc::mem_fun (*this, &EngineControl::parameter_changed));
251         input_channels.signal_changed().connect (sigc::mem_fun (*this, &EngineControl::parameter_changed));
252         output_channels.signal_changed().connect (sigc::mem_fun (*this, &EngineControl::parameter_changed));
253
254         notebook.signal_switch_page().connect (sigc::mem_fun (*this, &EngineControl::on_switch_page));
255
256         no_push = false;
257 }
258
259 void
260 EngineControl::on_response (int response_id)
261 {
262         ArdourDialog::on_response (response_id);
263
264         switch (response_id) {
265         case RESPONSE_APPLY:
266                 push_state_to_backend (true);
267                 break;
268         case RESPONSE_OK:
269                 push_state_to_backend (true);
270                 hide ();
271                 break;
272         case RESPONSE_DELETE_EVENT: {
273                 GdkEventButton ev;
274                 ev.type = GDK_BUTTON_PRESS;
275                 ev.button = 1;
276                 on_delete_event ((GdkEventAny*) &ev);
277                 break;
278         }
279         default:
280                 hide ();
281         }
282 }
283
284 void
285 EngineControl::build_notebook ()
286 {
287         Label* label;
288         AttachOptions xopt = AttachOptions (FILL|EXPAND);
289
290         /* clear the table */
291
292         Gtkmm2ext::container_clear (basic_vbox);
293         Gtkmm2ext::container_clear (basic_packer);
294
295         label = manage (left_aligned_label (_("Audio System:")));
296         basic_packer.attach (*label, 0, 1, 0, 1, xopt, (AttachOptions) 0);
297         basic_packer.attach (backend_combo, 1, 2, 0, 1, xopt, (AttachOptions) 0);
298         
299         if (_have_control) {
300                 build_full_control_notebook ();
301         } else {
302                 build_no_control_notebook ();
303         }
304
305         basic_vbox.pack_start (basic_hbox, false, false);
306
307         if (_have_control) {
308                 Gtk::HBox* hpacker = manage (new HBox);
309                 hpacker->set_border_width (12);
310                 hpacker->pack_start (control_app_button, false, false);
311                 hpacker->show ();
312                 control_app_button.show();
313                 basic_vbox.pack_start (*hpacker);
314         }
315
316         basic_vbox.show_all ();
317 }
318
319 void
320 EngineControl::build_full_control_notebook ()
321 {
322         boost::shared_ptr<ARDOUR::AudioBackend> backend = ARDOUR::AudioEngine::instance()->current_backend();
323         assert (backend);
324
325         using namespace Notebook_Helpers;
326         Label* label;
327         vector<string> strings;
328         AttachOptions xopt = AttachOptions (FILL|EXPAND);
329         int row = 1; // row zero == backend combo
330
331         /* start packing it up */
332
333         if (backend->requires_driver_selection()) {
334                 label = manage (left_aligned_label (_("Driver:")));
335                 basic_packer.attach (*label, 0, 1, row, row + 1, xopt, (AttachOptions) 0);
336                 basic_packer.attach (driver_combo, 1, 2, row, row + 1, xopt, (AttachOptions) 0);
337                 row++;
338         }
339
340         label = manage (left_aligned_label (_("Device:")));
341         basic_packer.attach (*label, 0, 1, row, row + 1, xopt, (AttachOptions) 0);
342         basic_packer.attach (device_combo, 1, 2, row, row + 1, xopt, (AttachOptions) 0);
343         row++;
344
345         label = manage (left_aligned_label (_("Sample rate:")));
346         basic_packer.attach (*label, 0, 1, row, row + 1, xopt, (AttachOptions) 0);
347         basic_packer.attach (sample_rate_combo, 1, 2, row, row + 1, xopt, (AttachOptions) 0);
348         row++;
349
350
351         label = manage (left_aligned_label (_("Buffer size:")));
352         basic_packer.attach (*label, 0, 1, row, row + 1, xopt, (AttachOptions) 0);
353         basic_packer.attach (buffer_size_combo, 1, 2, row, row + 1, xopt, (AttachOptions) 0);
354         buffer_size_duration_label.set_alignment (0.0); /* left-align */
355         basic_packer.attach (buffer_size_duration_label, 2, 3, row, row+1, xopt, (AttachOptions) 0);
356         row++;
357
358         input_channels.set_name ("InputChannels");
359         input_channels.set_flags(Gtk::CAN_FOCUS);
360         input_channels.set_digits(0);
361         input_channels.set_wrap(false);
362         output_channels.set_editable (true);
363
364         label = manage (left_aligned_label (_("Input Channels:")));
365         basic_packer.attach (*label, 0, 1, row, row+1, xopt, (AttachOptions) 0);
366         basic_packer.attach (input_channels, 1, 2, row, row+1, xopt, (AttachOptions) 0);
367         ++row;
368
369         output_channels.set_name ("OutputChannels");
370         output_channels.set_flags(Gtk::CAN_FOCUS);
371         output_channels.set_digits(0);
372         output_channels.set_wrap(false);
373         output_channels.set_editable (true);
374
375         label = manage (left_aligned_label (_("Output Channels:")));
376         basic_packer.attach (*label, 0, 1, row, row+1, xopt, (AttachOptions) 0);
377         basic_packer.attach (output_channels, 1, 2, row, row+1, xopt, (AttachOptions) 0);
378         ++row;
379
380         input_latency.set_name ("InputLatency");
381         input_latency.set_flags(Gtk::CAN_FOCUS);
382         input_latency.set_digits(0);
383         input_latency.set_wrap(false);
384         input_latency.set_editable (true);
385
386         label = manage (left_aligned_label (_("Hardware input latency:")));
387         basic_packer.attach (*label, 0, 1, row, row+1, xopt, (AttachOptions) 0);
388         basic_packer.attach (input_latency, 1, 2, row, row+1, xopt, (AttachOptions) 0);
389         label = manage (left_aligned_label (_("samples")));
390         basic_packer.attach (*label, 2, 3, row, row+1, xopt, (AttachOptions) 0);
391         ++row;
392
393         output_latency.set_name ("OutputLatency");
394         output_latency.set_flags(Gtk::CAN_FOCUS);
395         output_latency.set_digits(0);
396         output_latency.set_wrap(false);
397         output_latency.set_editable (true);
398
399         label = manage (left_aligned_label (_("Hardware output latency:")));
400         basic_packer.attach (*label, 0, 1, row, row+1, xopt, (AttachOptions) 0);
401         basic_packer.attach (output_latency, 1, 2, row, row+1, xopt, (AttachOptions) 0);
402         label = manage (left_aligned_label (_("samples")));
403         basic_packer.attach (*label, 2, 3, row, row+1, xopt, (AttachOptions) 0);
404         ++row;
405
406 }
407
408 void
409 EngineControl::build_no_control_notebook ()
410 {
411         boost::shared_ptr<ARDOUR::AudioBackend> backend = ARDOUR::AudioEngine::instance()->current_backend();
412         assert (backend);
413
414         using namespace Notebook_Helpers;
415         Label* label;
416         vector<string> strings;
417         AttachOptions xopt = AttachOptions (FILL|EXPAND);
418         int row = 1; // row zero == backend combo
419         const string msg = string_compose (_("The %1 audio backend was configured and started externally.\nThis limits your control over it."), backend->name());
420
421         label = manage (new Label);
422         label->set_markup (string_compose ("<span weight=\"bold\" foreground=\"red\">%1</span>", msg));
423         basic_packer.attach (*label, 0, 2, row, row + 1, xopt, (AttachOptions) 0);
424         row++;
425
426         if (backend->can_change_sample_rate_when_running()) {
427                 label = manage (left_aligned_label (_("Sample rate:")));
428                 basic_packer.attach (*label, 0, 1, row, row + 1, xopt, (AttachOptions) 0);
429                 basic_packer.attach (sample_rate_combo, 1, 2, row, row + 1, xopt, (AttachOptions) 0);
430                 row++;
431         }
432
433         if (backend->can_change_buffer_size_when_running()) {
434                 label = manage (left_aligned_label (_("Buffer size:")));
435                 basic_packer.attach (*label, 0, 1, row, row + 1, xopt, (AttachOptions) 0);
436                 basic_packer.attach (buffer_size_combo, 1, 2, row, row + 1, xopt, (AttachOptions) 0);
437                 buffer_size_duration_label.set_alignment (0.0); /* left-align */
438                 basic_packer.attach (buffer_size_duration_label, 2, 3, row, row+1, xopt, (AttachOptions) 0);
439                 row++;
440         }
441
442         connect_disconnect_button.signal_clicked().connect (sigc::mem_fun (*this, &EngineControl::connect_disconnect_click));
443
444         basic_packer.attach (connect_disconnect_button, 0, 2, row, row+1, FILL, AttachOptions (0));
445         row++;
446 }
447
448 EngineControl::~EngineControl ()
449 {
450
451 }
452
453 void
454 EngineControl::disable_latency_tab ()
455 {
456         vector<string> empty;
457         set_popdown_strings (lm_output_channel_combo, empty);
458         set_popdown_strings (lm_input_channel_combo, empty);
459         lm_measure_button.set_sensitive (false);
460         lm_use_button.set_sensitive (false);
461 }
462
463 void
464 EngineControl::enable_latency_tab ()
465 {
466         vector<string> outputs;
467         ARDOUR::AudioEngine::instance()->get_physical_outputs (ARDOUR::DataType::AUDIO, outputs);
468         set_popdown_strings (lm_output_channel_combo, outputs);
469         lm_output_channel_combo.set_active_text (outputs.front());
470
471         vector<string> inputs;
472         ARDOUR::AudioEngine::instance()->get_physical_inputs (ARDOUR::DataType::AUDIO, inputs);
473         set_popdown_strings (lm_input_channel_combo, inputs);
474         lm_input_channel_combo.set_active_text (inputs.front());
475
476         lm_measure_button.set_sensitive (true);
477 }
478
479 void
480 EngineControl::setup_midi_tab_for_backend ()
481 {
482         string backend = backend_combo.get_active_text ();
483
484         Gtkmm2ext::container_clear (midi_vbox);
485
486         midi_vbox.set_border_width (12);
487         midi_device_table.set_border_width (12);
488
489         if (backend == "JACK") {
490                 setup_midi_tab_for_jack ();
491         }
492
493         midi_vbox.pack_start (midi_device_table, true, true);
494         midi_vbox.pack_start (midi_refresh_button, false, false);
495         midi_vbox.show_all ();
496
497         midi_refresh_button.signal_clicked().connect (sigc::mem_fun (*this, &EngineControl::refresh_midi_display));
498 }
499
500 void
501 EngineControl::setup_midi_tab_for_jack ()
502 {
503         midi_vbox.pack_start (aj_button, false, false);
504 }       
505
506 void
507 EngineControl::refresh_midi_display ()
508 {
509         boost::shared_ptr<ARDOUR::AudioBackend> backend = ARDOUR::AudioEngine::instance()->current_backend();
510         assert (backend);
511
512         vector<string> midi_inputs;
513         vector<string> midi_outputs;
514         int row  = 0;
515         AttachOptions xopt = AttachOptions (FILL|EXPAND);
516         Gtk::Label* l;
517
518         Gtkmm2ext::container_clear (midi_device_table);
519
520         backend->get_physical_inputs (ARDOUR::DataType::MIDI, midi_inputs);
521         backend->get_physical_outputs (ARDOUR::DataType::MIDI, midi_outputs);
522
523         midi_device_table.set_spacings (6);
524         midi_device_table.set_homogeneous (true);
525         midi_device_table.resize (midi_inputs.size() + midi_outputs.size() + 3, 1);
526
527         l = manage (new Label);
528         l->set_markup (string_compose ("<span size=\"large\" weight=\"bold\">%1</span>", _("MIDI Inputs")));
529         midi_device_table.attach (*l, 0, 1, row, row + 1, xopt, AttachOptions (0));
530         l->set_alignment (0, 0.5);
531         row++;
532         l->show ();
533         
534         for (vector<string>::iterator p = midi_inputs.begin(); p != midi_inputs.end(); ++p) {
535                 l = manage (new Label ((*p).substr ((*p).find_last_of (':') + 1)));
536                 l->set_alignment (0, 0.5);
537                 midi_device_table.attach (*l, 0, 1, row, row + 1, xopt, AttachOptions (0));
538                 l->show ();
539                 row++;
540         }
541
542         row++; // extra row of spacing
543
544         l = manage (new Label);
545         l->set_markup (string_compose ("<span size=\"large\" weight=\"bold\">%1</span>", _("MIDI Outputs")));
546         midi_device_table.attach (*l, 0, 1, row, row + 1, xopt, AttachOptions (0));
547         l->set_alignment (0, 0.5);
548         row++;
549         l->show ();
550
551         for (vector<string>::iterator p = midi_outputs.begin(); p != midi_outputs.end(); ++p) {
552                 l = manage (new Label ((*p).substr ((*p).find_last_of (':') + 1)));
553                 l->set_alignment (0, 0.5);
554                 midi_device_table.attach (*l, 0, 1, row, row + 1, xopt, AttachOptions (0));
555                 l->show ();
556                 row++;
557         }
558 }
559
560 void
561 EngineControl::update_sensitivity ()
562 {
563 }
564
565 void
566 EngineControl::backend_changed ()
567 {
568         if (ignore_changes) {
569                 return;
570         }
571
572         string backend_name = backend_combo.get_active_text();
573         boost::shared_ptr<ARDOUR::AudioBackend> backend;
574
575         if (!(backend = ARDOUR::AudioEngine::instance()->set_backend (backend_name, "ardour", ""))) {
576                 /* eh? setting the backend failed... how ? */
577                 return;
578         }
579
580         _have_control = ARDOUR::AudioEngine::instance()->setup_required ();
581
582         build_notebook ();
583         setup_midi_tab_for_backend ();
584
585         if (backend->requires_driver_selection()) {
586                 vector<string> drivers = backend->enumerate_drivers();
587                 
588                 if (!drivers.empty()) {
589                         {
590                                 PBD::Unwinder<uint32_t> protect_ignore_changes (ignore_changes, ignore_changes + 1);
591                                 set_popdown_strings (driver_combo, drivers);
592                                 driver_combo.set_active_text (drivers.front());
593                         }
594
595                         driver_changed ();
596                 }
597                 
598         } else {
599                 driver_combo.set_sensitive (false);
600                 /* this will change the device text which will cause a call to
601                  * device changed which will set up parameters
602                  */
603                 list_devices ();
604         }
605         
606         maybe_display_saved_state ();
607 }
608
609 bool
610 EngineControl::print_channel_count (Gtk::SpinButton* sb)
611 {
612         uint32_t cnt = (uint32_t) sb->get_value();
613         if (cnt == 0) {
614                 sb->set_text (_("all available channels"));
615         } else {
616                 char buf[32];
617                 snprintf (buf, sizeof (buf), "%d", cnt);
618                 sb->set_text (buf);
619         }
620         return true;
621 }
622
623 void
624 EngineControl::list_devices ()
625 {
626         boost::shared_ptr<ARDOUR::AudioBackend> backend = ARDOUR::AudioEngine::instance()->current_backend();
627         assert (backend);
628
629         /* now fill out devices, mark sample rates, buffer sizes insensitive */
630             
631         vector<ARDOUR::AudioBackend::DeviceStatus> all_devices = backend->enumerate_devices ();
632         
633         /* NOTE: Ardour currently does not display the "available" field of the
634          * returned devices.
635          *
636          * Doing so would require a different GUI widget than the combo
637          * box/popdown that we currently use, since it has no way to list
638          * items that are not selectable. Something more like a popup menu,
639          * which could have unselectable items, would be appropriate.
640          */
641
642         vector<string> available_devices;
643
644         for (vector<ARDOUR::AudioBackend::DeviceStatus>::const_iterator i = all_devices.begin(); i != all_devices.end(); ++i) {
645                 available_devices.push_back (i->name);
646         }
647
648         if (!available_devices.empty()) {
649
650                 update_sensitivity ();
651                                                 
652                 {
653                         PBD::Unwinder<uint32_t> protect_ignore_changes (ignore_changes, ignore_changes + 1);
654                         set_popdown_strings (device_combo, available_devices);
655                         device_combo.set_active_text (available_devices.front());
656                 }
657
658                 device_changed ();
659
660                 ok_button->set_sensitive (true);
661                 apply_button->set_sensitive (true);
662
663         } else {
664                 sample_rate_combo.set_sensitive (false);
665                 buffer_size_combo.set_sensitive (false);
666                 input_latency.set_sensitive (false);
667                 output_latency.set_sensitive (false);
668                 input_channels.set_sensitive (false);
669                 output_channels.set_sensitive (false);
670                 ok_button->set_sensitive (false);
671                 apply_button->set_sensitive (false);
672         }
673 }
674
675 void
676 EngineControl::driver_changed ()
677 {
678         if (ignore_changes) {
679                 return;
680         }
681
682         boost::shared_ptr<ARDOUR::AudioBackend> backend = ARDOUR::AudioEngine::instance()->current_backend();
683         assert (backend);
684
685         backend->set_driver (driver_combo.get_active_text());
686         list_devices ();
687
688         maybe_display_saved_state ();
689 }
690
691 void
692 EngineControl::device_changed ()
693 {
694         if (ignore_changes) {
695                 return;
696         }
697
698         boost::shared_ptr<ARDOUR::AudioBackend> backend = ARDOUR::AudioEngine::instance()->current_backend();
699         assert (backend);
700         string device_name = device_combo.get_active_text ();
701         vector<string> s;
702
703         {
704                 PBD::Unwinder<uint32_t> protect_ignore_changes (ignore_changes, ignore_changes + 1);
705
706                 /* don't allow programmatic change to combos to cause a
707                    recursive call to this method.
708                 */
709                 
710                 /* sample rates */
711                 
712                 string desired;
713                 
714                 vector<float> sr;
715
716                 if (_have_control) {
717                         sr = backend->available_sample_rates (device_name);
718                 } else {
719
720                         sr.push_back (8000.0f);
721                         sr.push_back (16000.0f);
722                         sr.push_back (32000.0f);
723                         sr.push_back (44100.0f);
724                         sr.push_back (48000.0f);
725                         sr.push_back (88200.0f);
726                         sr.push_back (96000.0f);
727                         sr.push_back (192000.0f);
728                         sr.push_back (384000.0f);
729                 }
730
731                 for (vector<float>::const_iterator x = sr.begin(); x != sr.end(); ++x) {
732                         s.push_back (rate_as_string (*x));
733                         if (*x == _desired_sample_rate) {
734                                 desired = s.back();
735                         }
736                 }
737                 
738                 if (!s.empty()) {
739                         sample_rate_combo.set_sensitive (true);
740                         set_popdown_strings (sample_rate_combo, s);
741
742                         if (desired.empty()) {
743                                 sample_rate_combo.set_active_text (s.front());
744                         } else {
745                                 sample_rate_combo.set_active_text (desired);
746                         }
747
748                 } else {
749                         sample_rate_combo.set_sensitive (false);
750                 }
751
752                 /* buffer sizes */
753                 
754                 vector<uint32_t> bs;
755                 
756                 if (_have_control) {
757                         bs = backend->available_buffer_sizes(device_name);
758                 } else if (backend->can_change_buffer_size_when_running()) {
759                         bs.push_back (8);
760                         bs.push_back (16);
761                         bs.push_back (32);
762                         bs.push_back (64);
763                         bs.push_back (128);
764                         bs.push_back (256);
765                         bs.push_back (512);
766                         bs.push_back (1024);
767                         bs.push_back (2048);
768                         bs.push_back (4096);
769                         bs.push_back (8192);
770                 }
771                 s.clear ();
772                 for (vector<uint32_t>::const_iterator x = bs.begin(); x != bs.end(); ++x) {
773                         s.push_back (bufsize_as_string (*x));
774                 }
775                 
776                 if (!s.empty()) {
777                         buffer_size_combo.set_sensitive (true);
778                         set_popdown_strings (buffer_size_combo, s);
779                         
780                         buffer_size_combo.set_active_text (s.front());
781                         show_buffer_duration ();
782                 } else {
783                         buffer_size_combo.set_sensitive (false);
784                 }
785
786                 /* XXX theoretically need to set min + max channel counts here
787                  */
788                 
789                 manage_control_app_sensitivity ();
790         }
791
792         /* pick up any saved state for this device */
793
794         maybe_display_saved_state ();
795
796         /* and push it to the backend */
797
798         push_state_to_backend (false);
799 }       
800
801 string
802 EngineControl::rate_as_string (float r)
803 {
804         char buf[32];
805         if (fmod (r, 1000.0f)) {
806                 snprintf (buf, sizeof (buf), "%.1f kHz", r/1000.0);
807         } else {
808                 snprintf (buf, sizeof (buf), "%.0f kHz", r/1000.0);
809         }
810         return buf;
811 }
812
813 string
814 EngineControl::bufsize_as_string (uint32_t sz)
815 {
816         /* Translators: "samples" is always plural here, so no
817            need for plural+singular forms.
818         */
819         char buf[32];
820         snprintf (buf, sizeof (buf), _("%u samples"), sz);
821         return buf;
822 }
823
824 void 
825 EngineControl::sample_rate_changed ()
826 {
827         if (ignore_changes) {
828                 return;
829         }
830
831         /* reset the strings for buffer size to show the correct msec value
832            (reflecting the new sample rate).
833         */
834
835         show_buffer_duration ();
836         save_state ();
837
838 }
839
840 void 
841 EngineControl::buffer_size_changed ()
842 {
843         if (ignore_changes) {
844                 return;
845         }
846
847         show_buffer_duration ();
848         save_state ();
849 }
850
851 void
852 EngineControl::show_buffer_duration ()
853 {
854
855         /* buffer sizes  - convert from just samples to samples + msecs for
856          * the displayed string
857          */
858
859         string bs_text = buffer_size_combo.get_active_text ();
860         uint32_t samples = atoi (bs_text); /* will ignore trailing text */
861         uint32_t rate = get_rate();
862
863         /* Translators: "msecs" is ALWAYS plural here, so we do not
864            need singular form as well.
865         */
866         /* Developers: note the hard-coding of a double buffered model
867            in the (2 * samples) computation of latency. we always start
868            the audiobackend in this configuration.
869         */
870         char buf[32];
871         snprintf (buf, sizeof (buf), _("(%.1f msecs)"), (2 * samples) / (rate/1000.0));
872         buffer_size_duration_label.set_text (buf);
873 }
874
875 void
876 EngineControl::parameter_changed ()
877 {
878         if (!ignore_changes) {
879                 save_state ();
880         }
881 }
882
883 EngineControl::State*
884 EngineControl::get_matching_state (const string& backend,
885                                    const string& driver,
886                                    const string& device)
887 {
888         for (StateList::iterator i = states.begin(); i != states.end(); ++i) {
889                 if ((*i).backend == backend &&
890                     (*i).driver == driver &&
891                     (*i).device == device) {
892                         return &(*i);
893                 }
894         }
895         return 0;
896 }
897
898 EngineControl::State*
899 EngineControl::get_saved_state_for_currently_displayed_backend_and_device ()
900 {
901         boost::shared_ptr<ARDOUR::AudioBackend> backend = ARDOUR::AudioEngine::instance()->current_backend();
902
903         if (backend) {
904                 return get_matching_state (backend_combo.get_active_text(),
905                                            (backend->requires_driver_selection() ? (std::string) driver_combo.get_active_text() : string()),
906                                            device_combo.get_active_text());
907         }
908
909
910         return get_matching_state (backend_combo.get_active_text(),
911                                    string(),
912                                    device_combo.get_active_text());
913 }
914
915 EngineControl::State*
916 EngineControl::save_state ()
917 {
918         if (!_have_control) {
919                 return 0;
920         }
921
922         bool existing = true;
923         State* state = get_saved_state_for_currently_displayed_backend_and_device ();
924
925         if (!state) {
926                 existing = false;
927                 state = new State;
928         }
929         
930         store_state (*state);
931
932         if (!existing) {
933                 states.push_back (*state);
934         }
935
936         return state;
937 }
938
939 void
940 EngineControl::store_state (State& state)
941 {
942         state.backend = get_backend ();
943         state.driver = get_driver ();
944         state.device = get_device_name ();
945         state.sample_rate = get_rate ();
946         state.buffer_size = get_buffer_size ();
947         state.input_latency = get_input_latency ();
948         state.output_latency = get_output_latency ();
949         state.input_channels = get_input_channels ();
950         state.output_channels = get_output_channels ();
951 }
952
953 void
954 EngineControl::maybe_display_saved_state ()
955 {
956         if (!_have_control) {
957                 return;
958         }
959
960         State* state = get_saved_state_for_currently_displayed_backend_and_device ();
961
962         if (state) {
963                 PBD::Unwinder<uint32_t> protect_ignore_changes (ignore_changes, ignore_changes + 1);
964
965                 if (!_desired_sample_rate) {
966                         sample_rate_combo.set_active_text (rate_as_string (state->sample_rate));
967                 }
968                 buffer_size_combo.set_active_text (bufsize_as_string (state->buffer_size));
969                 /* call this explicitly because we're ignoring changes to
970                    the controls at this point.
971                 */
972                 show_buffer_duration ();
973                 input_latency.set_value (state->input_latency);
974                 output_latency.set_value (state->output_latency);
975         }
976 }
977         
978 XMLNode&
979 EngineControl::get_state ()
980 {
981         XMLNode* root = new XMLNode ("AudioMIDISetup");
982         std::string path;
983
984         if (!states.empty()) {
985                 XMLNode* state_nodes = new XMLNode ("EngineStates");
986                 
987                 for (StateList::const_iterator i = states.begin(); i != states.end(); ++i) {
988                         
989                         XMLNode* node = new XMLNode ("State");
990                         
991                         node->add_property ("backend", (*i).backend);
992                         node->add_property ("driver", (*i).driver);
993                         node->add_property ("device", (*i).device);
994                         node->add_property ("sample-rate", (*i).sample_rate);
995                         node->add_property ("buffer-size", (*i).buffer_size);
996                         node->add_property ("input-latency", (*i).input_latency);
997                         node->add_property ("output-latency", (*i).output_latency);
998                         node->add_property ("input-channels", (*i).input_channels);
999                         node->add_property ("output-channels", (*i).output_channels);
1000                         node->add_property ("active", (*i).active ? "yes" : "no");
1001                         
1002                         state_nodes->add_child_nocopy (*node);
1003                 }
1004                 
1005                 root->add_child_nocopy (*state_nodes);
1006         }
1007
1008         return *root;
1009 }
1010
1011 void
1012 EngineControl::set_state (const XMLNode& root)
1013 {
1014         XMLNodeList          clist, cclist;
1015         XMLNodeConstIterator citer, cciter;
1016         XMLNode* child;
1017         XMLNode* grandchild;
1018         XMLProperty* prop = NULL;
1019
1020         if (root.name() != "AudioMIDISetup") {
1021                 return;
1022         }
1023
1024         clist = root.children();
1025
1026         states.clear ();
1027
1028         for (citer = clist.begin(); citer != clist.end(); ++citer) {
1029
1030                 child = *citer;
1031                 
1032                 if (child->name() != "EngineStates") {
1033                         continue;
1034                 }
1035
1036                 cclist = child->children();
1037
1038                 for (cciter = cclist.begin(); cciter != cclist.end(); ++cciter) {
1039                         State state;
1040                         
1041                         grandchild = *cciter;
1042
1043                         if (grandchild->name() != "State") {
1044                                 continue;
1045                         }
1046                         
1047                         if ((prop = grandchild->property ("backend")) == 0) {
1048                                 continue;
1049                         }
1050                         state.backend = prop->value ();
1051                         
1052                         if ((prop = grandchild->property ("driver")) == 0) {
1053                                 continue;
1054                         }
1055                         state.driver = prop->value ();
1056                         
1057                         if ((prop = grandchild->property ("device")) == 0) {
1058                                 continue;
1059                         }
1060                         state.device = prop->value ();
1061                         
1062                         if ((prop = grandchild->property ("sample-rate")) == 0) {
1063                                 continue;
1064                         }
1065                         state.sample_rate = atof (prop->value ());
1066                         
1067                         if ((prop = grandchild->property ("buffer-size")) == 0) {
1068                                 continue;
1069                         }
1070                         state.buffer_size = atoi (prop->value ());
1071                         
1072                         if ((prop = grandchild->property ("input-latency")) == 0) {
1073                                 continue;
1074                         }
1075                         state.input_latency = atoi (prop->value ());
1076                         
1077                         if ((prop = grandchild->property ("output-latency")) == 0) {
1078                                 continue;
1079                         }
1080                         state.output_latency = atoi (prop->value ());
1081                         
1082                         if ((prop = grandchild->property ("input-channels")) == 0) {
1083                                 continue;
1084                         }
1085                         state.input_channels = atoi (prop->value ());
1086                         
1087                         if ((prop = grandchild->property ("output-channels")) == 0) {
1088                                 continue;
1089                         }
1090                         state.output_channels = atoi (prop->value ());
1091
1092                         if ((prop = grandchild->property ("active")) == 0) {
1093                                 continue;
1094                         }
1095                         state.active = string_is_affirmative (prop->value ());
1096                         
1097                         states.push_back (state);
1098                 }
1099         }
1100
1101         /* now see if there was an active state and switch the setup to it */
1102         
1103         for (StateList::const_iterator i = states.begin(); i != states.end(); ++i) {
1104
1105                 if ((*i).active) {
1106                         ignore_changes++;
1107                         backend_combo.set_active_text ((*i).backend);
1108                         driver_combo.set_active_text ((*i).driver);
1109                         device_combo.set_active_text ((*i).device);
1110                         sample_rate_combo.set_active_text (rate_as_string ((*i).sample_rate));
1111                         buffer_size_combo.set_active_text (bufsize_as_string ((*i).buffer_size));
1112                         input_latency.set_value ((*i).input_latency);
1113                         output_latency.set_value ((*i).output_latency);
1114                         ignore_changes--;
1115                         break;
1116                 }
1117         }
1118 }
1119
1120
1121 int
1122 EngineControl::push_state_to_backend (bool start)
1123 {
1124         if (no_push) {
1125                 return 0;
1126         }
1127
1128         boost::shared_ptr<ARDOUR::AudioBackend> backend = ARDOUR::AudioEngine::instance()->current_backend();
1129
1130         if (!backend) {
1131                 return 0;
1132         }
1133         
1134         /* figure out what is going to change */
1135
1136         bool restart_required = false;
1137         bool was_running = ARDOUR::AudioEngine::instance()->running();
1138         bool change_driver = false;
1139         bool change_device = false;
1140         bool change_rate = false;
1141         bool change_bufsize = false;
1142         bool change_latency = false;
1143         bool change_channels = false;
1144
1145         uint32_t ochan = get_output_channels ();
1146         uint32_t ichan = get_input_channels ();
1147
1148         if (_have_control) {
1149
1150                 if (started_at_least_once) {
1151                         
1152                         /* we can control the backend */
1153                         
1154                         if (backend->requires_driver_selection()) {
1155                                 if (get_driver() != backend->driver_name()) {
1156                                         change_driver = true;
1157                                 }
1158                         }
1159                         
1160                         if (get_device_name() != backend->device_name()) {
1161                                 change_device = true;
1162                         }
1163                         
1164                         if (get_rate() != backend->sample_rate()) {
1165                                 change_rate = true;
1166                         }
1167                         
1168                         if (get_buffer_size() != backend->buffer_size()) {
1169                                 change_bufsize = true;
1170                         }
1171                         
1172                         /* zero-requested channels means "all available" */
1173
1174                         if (ichan == 0) {
1175                                 ichan = backend->input_channels();
1176                         }
1177                         
1178                         if (ochan == 0) {
1179                                 ochan = backend->output_channels();
1180                         }
1181                         
1182                         if (ichan != backend->input_channels()) {
1183                                 change_channels = true;
1184                         }
1185                         
1186                         if (ochan != backend->output_channels()) {
1187                                 change_channels = true;
1188                         }
1189
1190                         if (get_input_latency() != backend->systemic_input_latency() ||
1191                             get_output_latency() != backend->systemic_output_latency()) {
1192                                 change_latency = true;
1193                         }
1194                 } else {
1195                         /* backend never started, so we have to force a group
1196                            of settings.
1197                         */
1198                         change_driver = true;
1199                         change_device = true;
1200                         change_rate = true;
1201                         change_bufsize = true;
1202                         change_channels = true;
1203                         change_latency = true;
1204                 }
1205
1206         } else {
1207
1208                 /* we have no control over the backend, meaning that we can
1209                  * only possibly change sample rate and buffer size.
1210                  */
1211
1212
1213                 if (get_rate() != backend->sample_rate()) {
1214                         change_bufsize = true;
1215                 }
1216
1217                 if (get_buffer_size() != backend->buffer_size()) {
1218                         change_bufsize = true;
1219                 }
1220         }
1221
1222         if (!_have_control) {
1223
1224                 /* We do not have control over the backend, so the best we can
1225                  * do is try to change the sample rate and/or bufsize and get
1226                  * out of here.
1227                  */
1228
1229                 if (change_rate && !backend->can_change_sample_rate_when_running()) {
1230                         return 1;
1231                 }
1232
1233                 if (change_bufsize && !backend->can_change_buffer_size_when_running()) {
1234                         return 1;
1235                 }
1236                 
1237                 if (change_rate) {
1238                         backend->set_sample_rate (get_rate());
1239                 }
1240                 
1241                 if (change_bufsize) {
1242                         backend->set_buffer_size (get_buffer_size());
1243                 }
1244
1245                 post_push ();
1246
1247                 return 0;
1248         } 
1249
1250         /* determine if we need to stop the backend before changing parameters */
1251
1252         if (change_driver || change_device || change_channels || change_latency ||
1253             (change_rate && !backend->can_change_sample_rate_when_running()) ||
1254             (change_bufsize && !backend->can_change_buffer_size_when_running())) {
1255                 restart_required = true;
1256         } else {
1257                 restart_required = false;
1258         }
1259
1260         if (was_running) {
1261
1262                 if (!change_driver && !change_device && !change_channels && !change_latency) {
1263                         /* no changes in any parameters that absolutely require a
1264                          * restart, so check those that might be changeable without a
1265                          * restart
1266                          */
1267                         
1268                         if (change_rate && !backend->can_change_sample_rate_when_running()) {
1269                                 /* can't do this while running ... */
1270                                 restart_required = true;
1271                         }
1272
1273                         if (change_bufsize && !backend->can_change_buffer_size_when_running()) {
1274                                 /* can't do this while running ... */
1275                                 restart_required = true;
1276                         }
1277                 }
1278         }
1279
1280         if (was_running) {
1281                 if (restart_required) {
1282                         if (ARDOUR_UI::instance()->disconnect_from_engine ()) {
1283                                 return -1;
1284                         }
1285                 }
1286         }
1287                 
1288
1289         if (change_driver && backend->set_driver (get_driver())) {
1290                 error << string_compose (_("Cannot set driver to %1"), get_driver()) << endmsg;
1291                 return -1;
1292         }
1293         if (change_device && backend->set_device_name (get_device_name())) {
1294                 error << string_compose (_("Cannot set device name to %1"), get_device_name()) << endmsg;
1295                 return -1;
1296         }
1297         if (change_rate && backend->set_sample_rate (get_rate())) {
1298                 error << string_compose (_("Cannot set sample rate to %1"), get_rate()) << endmsg;
1299                 return -1;
1300         }
1301         if (change_bufsize && backend->set_buffer_size (get_buffer_size())) {
1302                 error << string_compose (_("Cannot set buffer size to %1"), get_buffer_size()) << endmsg;
1303                 return -1;
1304         }
1305
1306         if (change_channels || get_input_channels() == 0 || get_output_channels() == 0) {
1307                 if (backend->set_input_channels (get_input_channels())) {
1308                         error << string_compose (_("Cannot set input channels to %1"), get_input_channels()) << endmsg;
1309                         return -1;
1310                 }
1311                 if (backend->set_output_channels (get_output_channels())) {
1312                         error << string_compose (_("Cannot set output channels to %1"), get_output_channels()) << endmsg;
1313                         return -1;
1314                 }
1315         }
1316         if (change_latency) {
1317                 if (backend->set_systemic_input_latency (get_input_latency())) {
1318                         error << string_compose (_("Cannot set input latency to %1"), get_input_latency()) << endmsg;
1319                         return -1;
1320                 }
1321                 if (backend->set_systemic_output_latency (get_output_latency())) {
1322                         error << string_compose (_("Cannot set output latency to %1"), get_output_latency()) << endmsg;
1323                         return -1;
1324                 }
1325         }
1326                         
1327         if (start || (was_running && restart_required)) {
1328                 if (ARDOUR_UI::instance()->reconnect_to_engine()) {
1329                         return -1;
1330                 }
1331         }
1332         
1333         post_push ();
1334
1335         return 0;
1336 }
1337
1338 void
1339 EngineControl::post_push ()
1340 {
1341         /* get a pointer to the current state object, creating one if
1342          * necessary
1343          */
1344         
1345         if (_have_control) {
1346                 State* state = get_saved_state_for_currently_displayed_backend_and_device ();
1347                 
1348                 if (!state) {
1349                         state = save_state ();
1350                         assert (state);
1351                 }
1352                 
1353                 /* all off */
1354                 
1355                 for (StateList::iterator i = states.begin(); i != states.end(); ++i) {
1356                         (*i).active = false;
1357                 }
1358                 
1359                 /* mark this one active (to be used next time the dialog is
1360                  * shown)
1361                  */
1362                 
1363                 state->active = true;
1364                 
1365                 manage_control_app_sensitivity ();
1366         }
1367
1368         /* schedule a redisplay of MIDI ports */
1369         
1370         Glib::signal_timeout().connect (sigc::bind_return (sigc::mem_fun (*this, &EngineControl::refresh_midi_display), false), 1000);
1371 }
1372
1373
1374 float
1375 EngineControl::get_rate () const
1376 {
1377         float r = atof (sample_rate_combo.get_active_text ());
1378         /* the string may have been translated with an abbreviation for
1379          * thousands, so use a crude heuristic to fix this.
1380          */
1381         if (r < 1000.0) {
1382                 r *= 1000.0;
1383         }
1384         return r;
1385 }
1386         
1387
1388 uint32_t
1389 EngineControl::get_buffer_size () const
1390 {
1391         string txt = buffer_size_combo.get_active_text ();
1392         uint32_t samples;
1393
1394         if (sscanf (txt.c_str(), "%d", &samples) != 1) {
1395                 throw exception ();
1396         }
1397
1398         return samples;
1399 }
1400
1401 uint32_t
1402 EngineControl::get_input_channels() const
1403 {
1404         return (uint32_t) input_channels_adjustment.get_value();
1405 }
1406
1407 uint32_t
1408 EngineControl::get_output_channels() const
1409 {
1410         return (uint32_t) output_channels_adjustment.get_value();
1411 }
1412
1413 uint32_t
1414 EngineControl::get_input_latency() const
1415 {
1416         return (uint32_t) input_latency_adjustment.get_value();
1417 }
1418
1419 uint32_t
1420 EngineControl::get_output_latency() const
1421 {
1422         return (uint32_t) output_latency_adjustment.get_value();
1423 }
1424
1425 string
1426 EngineControl::get_backend () const
1427 {
1428         return backend_combo.get_active_text ();
1429 }
1430
1431 string
1432 EngineControl::get_driver () const
1433 {
1434         return driver_combo.get_active_text ();
1435 }
1436
1437 string
1438 EngineControl::get_device_name () const
1439 {
1440         return device_combo.get_active_text ();
1441 }
1442
1443 void
1444 EngineControl::control_app_button_clicked ()
1445 {
1446         boost::shared_ptr<ARDOUR::AudioBackend> backend = ARDOUR::AudioEngine::instance()->current_backend();
1447         
1448         if (!backend) {
1449                 return;
1450         }
1451         
1452         backend->launch_control_app ();
1453 }
1454
1455 void
1456 EngineControl::manage_control_app_sensitivity ()
1457 {
1458         boost::shared_ptr<ARDOUR::AudioBackend> backend = ARDOUR::AudioEngine::instance()->current_backend();
1459         
1460         if (!backend) {
1461                 return;
1462         }
1463         
1464         string appname = backend->control_app_name();
1465
1466         if (appname.empty()) {
1467                 control_app_button.set_sensitive (false);
1468         } else {
1469                 control_app_button.set_sensitive (true);
1470         }
1471 }
1472
1473 void
1474 EngineControl::set_desired_sample_rate (uint32_t sr)
1475 {
1476         _desired_sample_rate = sr;
1477         device_changed ();
1478 }
1479
1480 void
1481 EngineControl::on_switch_page (GtkNotebookPage*, guint page_num)
1482 {
1483         if (page_num == 0) {
1484                 cancel_button->set_sensitive (true);
1485                 ok_button->set_sensitive (true);
1486                 apply_button->set_sensitive (true);
1487         } else {
1488                 cancel_button->set_sensitive (false);
1489                 ok_button->set_sensitive (false);
1490                 apply_button->set_sensitive (false);
1491         }
1492
1493         if (page_num == 1) {
1494                 /* MIDI tab */
1495                 refresh_midi_display ();
1496         }
1497
1498         if (page_num == 2) {
1499                 /* latency tab */
1500
1501                 if (!ARDOUR::AudioEngine::instance()->running()) {
1502                         
1503                         PBD::Unwinder<uint32_t> protect_ignore_changes (ignore_changes, ignore_changes + 1);
1504                         
1505                         /* save any existing latency values */
1506                         
1507                         uint32_t il = (uint32_t) input_latency.get_value ();
1508                         uint32_t ol = (uint32_t) input_latency.get_value ();
1509
1510                         /* reset to zero so that our new test instance of JACK
1511                            will be clean of any existing latency measures.
1512                         */
1513                         
1514                         input_latency.set_value (0);
1515                         output_latency.set_value (0);
1516                         
1517                         /* reset control */
1518
1519                         input_latency.set_value (il);
1520                         output_latency.set_value (ol);
1521
1522                 } 
1523
1524                 if (ARDOUR::AudioEngine::instance()->prepare_for_latency_measurement()) {
1525                         disable_latency_tab ();
1526                 }
1527
1528                 enable_latency_tab ();
1529
1530         } else {
1531                 ARDOUR::AudioEngine::instance()->stop_latency_detection();
1532         }
1533 }
1534
1535 /* latency measurement */
1536
1537 bool
1538 EngineControl::check_latency_measurement ()
1539 {
1540         MTDM* mtdm = ARDOUR::AudioEngine::instance()->mtdm ();
1541
1542         if (mtdm->resolve () < 0) {
1543                 lm_results.set_markup (string_compose ("<span foreground=\"red\">%1</span>", _("No signal detected ")));
1544                 return true;
1545         }
1546
1547         if (mtdm->err () > 0.3) {
1548                 mtdm->invert ();
1549                 mtdm->resolve ();
1550         }
1551
1552         char buf[128];
1553         ARDOUR::framecnt_t const sample_rate = ARDOUR::AudioEngine::instance()->sample_rate();
1554
1555         if (sample_rate == 0) {
1556                 lm_results.set_text (_("Disconnected from audio engine"));
1557                 ARDOUR::AudioEngine::instance()->stop_latency_detection ();
1558                 return false;
1559         }
1560
1561         uint32_t frames_total = mtdm->del();
1562         uint32_t extra = frames_total - ARDOUR::AudioEngine::instance()->latency_signal_delay();
1563
1564         snprintf (buf, sizeof (buf), "%u samples %10.3lf ms", extra, extra * 1000.0f/sample_rate);
1565
1566         bool solid = true;
1567
1568         if (mtdm->err () > 0.2) {
1569                 strcat (buf, " ??");
1570                 solid = false;
1571         }
1572
1573         if (mtdm->inv ()) {
1574                 strcat (buf, " (Inv)");
1575                 solid = false;
1576         }
1577
1578         if (solid) {
1579                 lm_measure_button.set_active (false);
1580                 lm_use_button.set_sensitive (true);
1581                 strcat (buf, " (set)");
1582                 have_lm_results = true;
1583         }
1584         
1585         lm_results.set_text (buf);
1586
1587         return true;
1588 }
1589
1590 void
1591 EngineControl::start_latency_detection ()
1592 {
1593         ARDOUR::AudioEngine::instance()->set_latency_input_port (lm_input_channel_combo.get_active_text());
1594         ARDOUR::AudioEngine::instance()->set_latency_output_port (lm_output_channel_combo.get_active_text());
1595         ARDOUR::AudioEngine::instance()->start_latency_detection ();
1596         lm_results.set_text (_("Detecting ..."));
1597         latency_timeout = Glib::signal_timeout().connect (mem_fun (*this, &EngineControl::check_latency_measurement), 250);
1598         lm_start_stop_label.set_text (_("Cancel measurement"));
1599         have_lm_results = false;
1600         lm_input_channel_combo.set_sensitive (false);
1601         lm_output_channel_combo.set_sensitive (false);
1602 }
1603
1604 void
1605 EngineControl::end_latency_detection ()
1606 {
1607         ARDOUR::AudioEngine::instance()->stop_latency_detection ();
1608         latency_timeout.disconnect ();
1609         lm_start_stop_label.set_text (_("Measure latency"));
1610         if (!have_lm_results) {
1611                 lm_results.set_markup ("<i>No measurement results yet</i>");
1612         }
1613         lm_input_channel_combo.set_sensitive (true);
1614         lm_output_channel_combo.set_sensitive (true);
1615 }
1616
1617 void
1618 EngineControl::latency_button_toggled ()
1619 {
1620         if (lm_measure_button.get_active ()) {
1621                 start_latency_detection ();
1622         } else {
1623                 end_latency_detection ();
1624         }
1625 }
1626
1627 void
1628 EngineControl::use_latency_button_clicked ()
1629 {
1630         MTDM* mtdm = ARDOUR::AudioEngine::instance()->mtdm ();
1631
1632         if (!mtdm) {
1633                 return;
1634         }
1635
1636         uint32_t frames_total = mtdm->del();
1637         uint32_t extra = frames_total - ARDOUR::AudioEngine::instance()->latency_signal_delay();
1638         uint32_t one_way = extra/2;
1639
1640         input_latency_adjustment.set_value (one_way);
1641         output_latency_adjustment.set_value (one_way);
1642 }
1643
1644 bool
1645 EngineControl::on_delete_event (GdkEventAny* ev)
1646 {
1647         if (notebook.get_current_page() == 2) {
1648                 /* currently on latency tab - be sure to clean up */
1649                 end_latency_detection ();
1650         }
1651         return ArdourDialog::on_delete_event (ev);
1652 }
1653
1654 void
1655 EngineControl::engine_running ()
1656 {
1657         boost::shared_ptr<ARDOUR::AudioBackend> backend = ARDOUR::AudioEngine::instance()->current_backend();
1658         assert (backend);
1659
1660         buffer_size_combo.set_active_text (bufsize_as_string (backend->buffer_size()));
1661         sample_rate_combo.set_active_text (rate_as_string (backend->sample_rate()));
1662
1663         if (backend->can_change_buffer_size_when_running()) {
1664                 buffer_size_combo.set_sensitive (true);
1665         } else {
1666                 buffer_size_combo.set_sensitive (false);
1667         }
1668
1669         if (backend->can_change_sample_rate_when_running()) {
1670                 sample_rate_combo.set_sensitive (true);
1671         } else {
1672                 sample_rate_combo.set_sensitive (false);
1673         }
1674
1675         connect_disconnect_button.set_label (string_compose (_("Disconnect from %1"), backend->name()));
1676
1677         started_at_least_once = true;
1678 }
1679
1680 void
1681 EngineControl::engine_stopped ()
1682 {
1683         boost::shared_ptr<ARDOUR::AudioBackend> backend = ARDOUR::AudioEngine::instance()->current_backend();
1684         assert (backend);
1685
1686         buffer_size_combo.set_sensitive (false);
1687         connect_disconnect_button.set_label (string_compose (_("Connect to %1"), backend->name()));
1688
1689         sample_rate_combo.set_sensitive (true);
1690         buffer_size_combo.set_sensitive (true);
1691 }
1692         
1693 void
1694 EngineControl::connect_disconnect_click() 
1695 {
1696         if (ARDOUR::AudioEngine::instance()->running()) {
1697                 ARDOUR_UI::instance()->disconnect_from_engine ();
1698         } else {
1699                 ARDOUR_UI::instance()->reconnect_to_engine ();
1700         }
1701 }