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