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