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