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