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