MIDI branch becomes trunk
[ardour.git] / gtk2_ardour / export_dialog.cc
1 /*
2     Copyright (C) 1999-2005 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
21 #include <unistd.h>
22 #include <utility>
23 #include <sys/stat.h>
24 #include <fstream>
25
26 #include <samplerate.h>
27
28 #include <pbd/convert.h>
29 #include <pbd/xml++.h>
30
31 #include <gtkmm2ext/utils.h>
32 #include <gtkmm2ext/window_title.h>
33
34 #include <ardour/export.h>
35 #include <ardour/sndfile_helpers.h>
36 #include <ardour/audio_track.h>
37 #include <ardour/audioregion.h>
38 #include <ardour/audioengine.h>
39 #include <ardour/gdither.h>
40 #include <ardour/utils.h>
41
42 #include "export_dialog.h"
43 #include "ardour_ui.h"
44 #include "public_editor.h"
45 #include "keyboard.h"
46
47 #include "i18n.h"
48
49 #define FRAME_NAME "BaseFrame"
50
51 using namespace std;
52 using namespace ARDOUR;
53 using namespace PBD;
54 using namespace sigc;
55 using namespace Gtk;
56 using namespace Gtkmm2ext;
57
58 using PBD::internationalize;
59
60 static const gchar *sample_rates[] = {
61         N_("22.05kHz"),
62         N_("44.1kHz"),
63         N_("48kHz"),
64         N_("88.2kHz"),
65         N_("96kHz"),
66         N_("192kHz"),
67         0
68 };
69
70 static const gchar *src_quality[] = {
71         N_("best"),
72         N_("fastest"),
73         N_("linear"),
74         N_("better"),
75         N_("intermediate"),
76         0
77 };
78
79 static const gchar *dither_types[] = {
80         N_("None"),
81         N_("Rectangular"),
82         N_("Shaped Noise"),
83         N_("Triangular"),
84         0
85 };
86
87 static const gchar* channel_strings[] = {
88         N_("stereo"), 
89         N_("mono"), 
90         0
91 };
92
93 static const gchar* cue_file_types[] = {
94         N_("None"), 
95         N_("CUE"),
96         N_("TOC"),
97         0
98 };
99
100 ExportDialog::ExportDialog(PublicEditor& e)
101         : ArdourDialog ("export dialog"),
102           editor (e),
103           format_table (9, 2),
104           format_frame (_("Format")),
105           cue_file_label (_("CD Marker File Type"), 1.0, 0.5),
106           channel_count_label (_("Channels"), 1.0, 0.5),
107           header_format_label (_("File Type"), 1.0, 0.5),
108           bitdepth_format_label (_("Sample Format"), 1.0, 0.5),
109           endian_format_label (_("Sample Endianness"), 1.0, 0.5),
110           sample_rate_label (_("Sample Rate"), 1.0, 0.5),
111           src_quality_label (_("Conversion Quality"), 1.0, 0.5),
112           dither_type_label (_("Dither Type"), 1.0, 0.5),
113           cuefile_only_checkbox (_("Export CD Marker File Only")),
114           file_browse_button (_("Browse")),
115           track_selector_button (_("Specific tracks ..."))
116 {
117         guint32 n;
118         guint32 len;
119         guint32 maxlen;
120
121         session = 0;
122         track_and_master_selection_allowed = true;
123         channel_count_selection_allowed = true;
124         export_cd_markers_allowed = true;
125
126         WindowTitle title(Glib::get_application_name());
127         title += _("Export");
128         
129         set_title (title.get_string());
130         set_wmclass (X_("ardour_export"), "Ardour");
131         set_name ("ExportWindow");
132         add_events (Gdk::KEY_PRESS_MASK|Gdk::KEY_RELEASE_MASK);
133
134         spec.running = false;
135
136         file_entry.set_name ("ExportFileNameEntry");
137
138         master_list = ListStore::create (exp_cols);
139         master_selector.set_model (master_list);
140
141         master_selector.set_name ("ExportTrackSelector");
142         master_selector.set_size_request (-1, 100);
143         master_selector.append_column(_("Output"), exp_cols.output);
144         master_selector.append_column_editable(_("Left"), exp_cols.left);
145         master_selector.append_column_editable(_("Right"), exp_cols.right);
146         master_selector.get_column(0)->set_min_width(100);
147         
148         master_selector.get_column(1)->set_min_width(40);
149         master_selector.get_column(1)->set_sizing(Gtk::TREE_VIEW_COLUMN_AUTOSIZE);
150         master_selector.get_column(2)->set_min_width(40);
151         master_selector.get_column(2)->set_sizing(Gtk::TREE_VIEW_COLUMN_AUTOSIZE);
152         master_selector.get_selection()->set_mode (Gtk::SELECTION_NONE);
153
154         track_list = ListStore::create (exp_cols);
155         track_selector.set_model (track_list);
156
157         track_selector.set_name ("ExportTrackSelector");
158         track_selector.set_size_request (-1, 130);
159         track_selector.append_column(_("Output"), exp_cols.output);
160         track_selector.append_column_editable(_("Left"), exp_cols.left);
161         track_selector.append_column_editable(_("Right"), exp_cols.right);
162
163         track_selector.get_column(0)->set_min_width(100);
164         track_selector.get_column(1)->set_min_width(40);
165         track_selector.get_column(1)->set_sizing(Gtk::TREE_VIEW_COLUMN_AUTOSIZE);
166         track_selector.get_column(2)->set_min_width(40);
167         track_selector.get_column(2)->set_sizing(Gtk::TREE_VIEW_COLUMN_AUTOSIZE);
168         track_selector.get_selection()->set_mode (Gtk::SELECTION_NONE);
169
170         progress_bar.set_name ("ExportProgress");
171
172         format_frame.add (format_table);
173         format_frame.set_name (FRAME_NAME);
174
175         track_scroll.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
176         master_scroll.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
177
178         get_vbox()->pack_start (file_frame, false, false);
179
180         hpacker.set_spacing (5);
181         hpacker.set_border_width (5);
182         hpacker.pack_start (format_frame, false, false);
183
184         master_scroll.add (master_selector);
185         track_scroll.add (track_selector);
186
187         master_scroll.set_size_request (220, 100);
188         track_scroll.set_size_request (220, 100);
189                 
190         /* we may hide some of these later */
191         track_vpacker.pack_start (master_scroll);
192         track_vpacker.pack_start (track_scroll);
193         track_vpacker.pack_start (track_selector_button, Gtk::PACK_EXPAND_PADDING);
194
195         hpacker.pack_start (track_vpacker);
196
197         get_vbox()->pack_start (hpacker);
198         
199         track_selector_button.set_name ("EditorGTKButton");
200         track_selector_button.signal_clicked().connect (mem_fun(*this, &ExportDialog::track_selector_button_click));
201
202         get_vbox()->pack_start (progress_bar, false, false);
203
204         Gtkmm2ext::set_size_request_to_display_given_text (file_entry, X_("Kg/quite/a/reasonable/size/for/files/i/think"), 5, 8);
205
206         file_hbox.set_spacing (5);
207         file_hbox.set_border_width (5);
208         file_hbox.pack_start (file_entry, true, true);
209         file_hbox.pack_start (file_browse_button, false, false);
210
211         file_frame.add (file_hbox);
212         file_frame.set_border_width (5);
213         file_frame.set_name (FRAME_NAME);
214
215         /* pop_strings needs to be created on the stack because set_popdown_strings()
216            takes a reference. 
217         */
218
219         vector<string> pop_strings = I18N(sample_rates);
220         Gtkmm2ext::set_popdown_strings (sample_rate_combo, pop_strings);
221         sample_rate_combo.set_active_text (pop_strings.front());
222         pop_strings = I18N(src_quality);
223         Gtkmm2ext::set_popdown_strings (src_quality_combo, pop_strings);
224         src_quality_combo.set_active_text (pop_strings.front());
225         pop_strings = I18N(dither_types);
226         Gtkmm2ext::set_popdown_strings (dither_type_combo, pop_strings);
227         dither_type_combo.set_active_text (pop_strings.front());
228         pop_strings = I18N(channel_strings);
229         Gtkmm2ext::set_popdown_strings (channel_count_combo, pop_strings);
230         channel_count_combo.set_active_text (pop_strings.front());
231         pop_strings = I18N((const char **) sndfile_header_formats_strings);
232         Gtkmm2ext::set_popdown_strings (header_format_combo, pop_strings);
233         header_format_combo.set_active_text (pop_strings.front());
234         pop_strings = I18N((const char **) sndfile_bitdepth_formats_strings);
235         Gtkmm2ext::set_popdown_strings (bitdepth_format_combo, pop_strings);
236         bitdepth_format_combo.set_active_text (pop_strings.front());
237         pop_strings = I18N((const char **) sndfile_endian_formats_strings);
238         Gtkmm2ext::set_popdown_strings (endian_format_combo, pop_strings);
239         endian_format_combo.set_active_text (pop_strings.front());
240         pop_strings = I18N(cue_file_types);
241         Gtkmm2ext::set_popdown_strings (cue_file_combo, pop_strings);
242         cue_file_combo.set_active_text (pop_strings.front());
243
244         /* this will re-sensitized as soon as a non RIFF/WAV
245            header format is chosen.
246         */
247
248         endian_format_combo.set_sensitive (false);
249
250         /* determine longest strings at runtime */
251
252         maxlen = 0;
253         const char *longest = X_("gl"); /* translators: one ascender, one descender */
254         string longest_str;
255
256         for (n = 0; n < SNDFILE_HEADER_FORMATS; ++n) {
257                 if ((len = strlen (sndfile_header_formats_strings[n])) > maxlen) {
258                         maxlen = len;
259                         longest = sndfile_header_formats_strings[n];
260                 }
261         }
262
263         for (n = 0; n < SNDFILE_BITDEPTH_FORMATS; ++n) {
264                 if ((len = strlen (sndfile_bitdepth_formats_strings[n])) > maxlen) {
265                         maxlen = len;
266                         longest = sndfile_bitdepth_formats_strings[n];
267                 }
268         }
269
270         for (n = 0; n < SNDFILE_ENDIAN_FORMATS; ++n) {
271                 if ((len = strlen (sndfile_endian_formats_strings[n])) > maxlen) {
272                         maxlen = len;
273                         longest = sndfile_endian_formats_strings[n];
274                 }
275         }
276
277         longest_str = longest;
278
279         /* force ascender + descender */
280
281         longest_str[0] = 'g';
282         longest_str[1] = 'l';
283
284         //Gtkmm2ext::set_size_request_to_display_given_text (header_format_combo, longest_str.c_str(), 5+FUDGE, 5);
285
286         // TRANSLATORS: "slereg" is "stereo" with ascender and descender substituted
287         //Gtkmm2ext::set_size_request_to_display_given_text (channel_count_combo, _("slereg"), 5+FUDGE, 5);
288
289 /*      header_format_combo.set_focus_on_click (true);
290         bitdepth_format_combo.set_focus_on_click (true);
291         endian_format_combo.set_focus_on_click (true);
292         channel_count_combo.set_focus_on_click (true);
293         src_quality_combo.set_focus_on_click (true);
294         dither_type_combo.set_focus_on_click (true);
295         sample_rate_combo.set_focus_on_click (true);
296         cue_file_combo.set_focus_on_click (true);
297 */
298         dither_type_label.set_name ("ExportFormatLabel");
299         sample_rate_label.set_name ("ExportFormatLabel");
300         src_quality_label.set_name ("ExportFormatLabel");
301         channel_count_label.set_name ("ExportFormatLabel");
302         header_format_label.set_name ("ExportFormatLabel");
303         bitdepth_format_label.set_name ("ExportFormatLabel");
304         endian_format_label.set_name ("ExportFormatLabel");
305         cue_file_label.set_name ("ExportFormatLabel");
306
307         header_format_combo.set_name ("ExportFormatDisplay");
308         bitdepth_format_combo.set_name ("ExportFormatDisplay");
309         endian_format_combo.set_name ("ExportFormatDisplay");
310         channel_count_combo.set_name ("ExportFormatDisplay");
311         dither_type_combo.set_name ("ExportFormatDisplay");
312         src_quality_combo.set_name ("ExportFormatDisplay");
313         sample_rate_combo.set_name ("ExportFormatDisplay");
314         cue_file_combo.set_name ("ExportFormatDisplay");
315
316         cuefile_only_checkbox.set_name ("ExportCheckbox");
317
318         format_table.set_homogeneous (false);
319         format_table.set_border_width (5);
320         format_table.set_col_spacings (5);
321         format_table.set_row_spacings (5);
322
323         format_table.attach (channel_count_label, 0, 1, 0, 1);
324         format_table.attach (channel_count_combo, 1, 2, 0, 1);
325         
326         format_table.attach (header_format_label, 0, 1, 1, 2);
327         format_table.attach (header_format_combo, 1, 2, 1, 2);
328
329         format_table.attach (bitdepth_format_label, 0, 1, 2, 3);
330         format_table.attach (bitdepth_format_combo, 1, 2, 2, 3);
331
332         format_table.attach (endian_format_label, 0, 1, 3, 4);
333         format_table.attach (endian_format_combo, 1, 2, 3, 4);
334
335         format_table.attach (sample_rate_label, 0, 1, 4, 5);
336         format_table.attach (sample_rate_combo, 1, 2, 4, 5);
337
338         format_table.attach (src_quality_label, 0, 1, 5, 6);
339         format_table.attach (src_quality_combo, 1, 2, 5, 6);
340
341         format_table.attach (dither_type_label, 0, 1, 6, 7);
342         format_table.attach (dither_type_combo, 1, 2, 6, 7);
343
344         format_table.attach (cue_file_label, 0, 1, 7, 8);
345         format_table.attach (cue_file_combo, 1, 2, 7, 8);
346         format_table.attach (cuefile_only_checkbox, 0, 2, 8, 9);
347
348         file_entry.set_name ("ExportFileDisplay");
349
350         signal_delete_event().connect (mem_fun(*this, &ExportDialog::window_closed));
351
352         cancel_button = add_button (Stock::CANCEL, RESPONSE_CANCEL);
353         cancel_button->signal_clicked().connect (mem_fun(*this, &ExportDialog::end_dialog));
354         ok_button = add_button (_("Export"), RESPONSE_ACCEPT);
355         ok_button->signal_clicked().connect (mem_fun(*this, &ExportDialog::do_export));
356         
357         file_browse_button.set_name ("EditorGTKButton");
358         file_browse_button.signal_clicked().connect (mem_fun(*this, &ExportDialog::browse));
359
360         channel_count_combo.signal_changed().connect (mem_fun(*this, &ExportDialog::channels_chosen));
361         bitdepth_format_combo.signal_changed().connect (mem_fun(*this, &ExportDialog::bitdepth_chosen));
362         header_format_combo.signal_changed().connect (mem_fun(*this, &ExportDialog::header_chosen));
363         sample_rate_combo.signal_changed().connect (mem_fun(*this, &ExportDialog::sample_rate_chosen));
364         cue_file_combo.signal_changed().connect (mem_fun(*this, &ExportDialog::cue_file_type_chosen));
365 }
366
367 ExportDialog::~ExportDialog()
368 {
369 }
370
371 void
372 ExportDialog::do_not_allow_track_and_master_selection()
373 {
374         track_and_master_selection_allowed = false;
375         track_vpacker.set_no_show_all();
376 }
377
378 void
379 ExportDialog::do_not_allow_channel_count_selection()
380 {
381         channel_count_selection_allowed = false;
382         channel_count_combo.set_no_show_all();
383         channel_count_label.set_no_show_all();
384 }
385
386 void
387 ExportDialog::do_not_allow_export_cd_markers()
388 {
389         export_cd_markers_allowed = false;
390         cue_file_label.set_no_show_all();
391         cue_file_combo.set_no_show_all();
392         cuefile_only_checkbox.set_no_show_all();
393 }
394
395 void
396 ExportDialog::connect_to_session (Session *s)
397 {
398         session = s;
399         session->GoingAway.connect (mem_fun(*this, &Window::hide_all));
400
401         switch (session->frame_rate()) {
402         case 22050:
403                 sample_rate_combo.set_active_text (_("22.05kHz"));
404                 break;
405         case 44100:
406                 sample_rate_combo.set_active_text (_("44.1kHz"));
407                 break;
408         case 48000:
409                 sample_rate_combo.set_active_text (_("48kHz"));
410                 break;
411         case 88200:
412                 sample_rate_combo.set_active_text (_("88.2kHz"));
413                 break;
414         case 96000:
415                 sample_rate_combo.set_active_text (_("96kHz"));
416                 break;
417         case 192000:
418                 sample_rate_combo.set_active_text (_("192kHz"));
419                 break;
420         default:
421                 sample_rate_combo.set_active_text (_("44.1kHz"));
422                 break;
423         }
424
425         src_quality_combo.set_sensitive (false);
426
427         set_state();
428 }
429
430 void
431 ExportDialog::set_state()
432 {
433         XMLNode* node = session->instant_xml(X_("ExportDialog"), session->path());
434         XMLProperty* prop;
435
436         if (node) {
437
438                 if ((prop = node->property (X_("sample_rate"))) != 0) {
439                         sample_rate_combo.set_active_text(prop->value());
440                 }
441                 if ((prop = node->property (X_("src_quality"))) != 0) {
442                         src_quality_combo.set_active_text(prop->value());
443                 }
444                 if ((prop = node->property (X_("dither_type"))) != 0) {
445                         dither_type_combo.set_active_text(prop->value());
446                 }
447                 if ((prop = node->property (X_("channel_count"))) != 0) {
448                         channel_count_combo.set_active_text(prop->value());
449                 }
450                 if ((prop = node->property (X_("header_format"))) != 0) {
451                         header_format_combo.set_active_text(prop->value());
452                 }
453                 if ((prop = node->property (X_("bitdepth_format"))) != 0) {
454                         bitdepth_format_combo.set_active_text(prop->value());
455                 }
456                 if ((prop = node->property (X_("endian_format"))) != 0) {
457                         endian_format_combo.set_active_text(prop->value());
458                 }
459                 if ((prop = node->property (X_("filename"))) != 0) {
460                         file_entry.set_text(prop->value());
461                 }
462                 if ((prop = node->property (X_("cue_file_type"))) != 0) {
463                         cue_file_combo.set_active_text(prop->value());
464                 }
465         }
466
467         header_chosen ();
468         bitdepth_chosen();
469         channels_chosen();
470         sample_rate_chosen();
471
472         if (session->master_out()) {
473                 track_scroll.hide ();
474         } else {
475                 master_scroll.hide ();
476                 track_selector_button.hide ();
477         }
478
479         if (!node) {
480                 return;
481         }
482
483         if (session->master_out()) {
484                 XMLNode* master = find_named_node(*node, (X_("Master")));
485                 int nchns;
486
487                 if (!master) {
488                         
489                         /* default is to use all */
490                         if (channel_count_combo.get_active_text() == _("mono")) {
491                                 nchns = 1;
492                         } else {
493                                 nchns = 2;
494                         }
495
496                         TreeModel::Children rows = master_selector.get_model()->children();
497                         for (uint32_t r = 0; r < session->master_out()->n_outputs().get(DataType::AUDIO); ++r) {
498                                 if (nchns == 2) {
499                                         if (r % 2) {
500                                                 rows[r][exp_cols.right] = true;
501                                         } else {
502                                                 rows[r][exp_cols.left] = true;
503                                         }
504                                 } else {
505                                         rows[r][exp_cols.left] = true;
506                                 }
507                         }
508
509                 } else {
510                         /* XXX use XML state */
511                 }
512         }
513
514         XMLNode* tracks = find_named_node(*node, (X_("Tracks")));
515         if (!tracks) {
516                 return;
517         }
518         
519         XMLNodeList track_list = tracks->children(X_("Track"));
520         TreeModel::Children rows = track_selector.get_model()->children();
521         TreeModel::Children::iterator ri = rows.begin();
522         TreeModel::Row row;
523
524         for (XMLNodeIterator it = track_list.begin(); it != track_list.end(); ++it, ++ri) {
525                 if (ri == rows.end()){
526                         break;
527                 }
528
529                 XMLNode* track = *it;
530                 row = *ri;
531
532                 if ((prop = track->property(X_("channel1"))) != 0) {
533                         if (prop->value() == X_("on")) {
534                                 row[exp_cols.left] = true;
535                         } else {
536                                 row[exp_cols.left] = false;
537                         }
538                 }
539
540                 if ((prop = track->property(X_("channel2"))) != 0) {
541                         if (prop->value() == X_("on")) {
542                                 row[exp_cols.right] = true;
543                         } else {
544                                 row[exp_cols.right] = false;
545                         }
546                 }
547         }
548 }
549
550 void
551 ExportDialog::save_state()
552 {
553         if (!session) {
554                 return;
555         }
556
557         XMLNode* node = new XMLNode(X_("ExportDialog"));
558
559         node->add_property(X_("sample_rate"), sample_rate_combo.get_active_text());
560         node->add_property(X_("src_quality"), src_quality_combo.get_active_text());
561         node->add_property(X_("dither_type"), dither_type_combo.get_active_text());
562         node->add_property(X_("channel_count"), channel_count_combo.get_active_text());
563         node->add_property(X_("header_format"), header_format_combo.get_active_text());
564         node->add_property(X_("bitdepth_format"), bitdepth_format_combo.get_active_text());
565         node->add_property(X_("endian_format"), endian_format_combo.get_active_text());
566         node->add_property(X_("filename"), file_entry.get_text());
567         node->add_property(X_("cue_file_type"), cue_file_combo.get_active_text());
568
569         XMLNode* tracks = new XMLNode(X_("Tracks"));
570
571         TreeModel::Children rows = track_selector.get_model()->children();
572         TreeModel::Row row;
573         for (TreeModel::Children::iterator ri = rows.begin(); ri != rows.end(); ++ri) {
574                 XMLNode* track = new XMLNode(X_("Track"));
575
576                 row = *ri;
577                 track->add_property(X_("channel1"), row[exp_cols.left] ? X_("on") : X_("off"));
578                 track->add_property(X_("channel2"), row[exp_cols.right] ? X_("on") : X_("off"));
579
580                 tracks->add_child_nocopy(*track);
581         }
582         node->add_child_nocopy(*tracks);
583         
584         session->add_instant_xml(*node, session->path());
585 }
586
587 void
588 ExportDialog::set_range (nframes_t start, nframes_t end)
589 {
590         spec.start_frame = start;
591         spec.end_frame = end;
592 }
593
594 gint
595 ExportDialog::progress_timeout ()
596 {
597         progress_bar.set_fraction (spec.progress);
598         return TRUE;
599 }
600
601 void
602 frames_to_cd_frames_string (char* buf, nframes_t when, nframes_t fr)
603 {
604
605   long unsigned int remainder;
606   int mins, secs, frames;
607
608         mins = when / (60 * fr);
609         remainder = when - (mins * 60 * fr);
610         secs = remainder / fr;
611         remainder -= secs * fr;
612         frames = remainder / (fr / 75);
613         sprintf (buf, " %02d:%02d:%02d", mins, secs, frames);
614
615 }
616
617 struct LocationSortByStart {
618     bool operator() (Location *a, Location *b) {
619             return a->start() < b->start();
620     }
621 };
622
623 void
624 ExportDialog::export_toc_file (Locations::LocationList& locations, const string& path)
625 {
626         if(!export_cd_markers_allowed){
627                 return;
628         }
629         
630     string filepath = path + ".toc";
631         ofstream out (filepath.c_str());
632         long unsigned int last_end_time = spec.start_frame, last_start_time = spec.start_frame;
633         int numtracks = 0;
634         gchar buf[18];
635
636         if (!out) {
637                 error << string_compose(_("Editor: cannot open \"%1\" as export file for CD toc file"), filepath) << endmsg;
638                 return;
639         }
640         out << "CD_DA" << endl;
641         out << "CD_TEXT {" << endl << "  LANGUAGE_MAP {" << endl << "    0 : EN" << endl << "  }" << endl;
642         out << "  LANGUAGE 0 {" << endl << "    TITLE \"" << session->name() << "\"" << endl << "  }" << endl << "}" << endl;
643
644         Locations::LocationList::iterator i;
645         Locations::LocationList temp;
646
647         for (i = locations.begin(); i != locations.end(); ++i) {
648           if ((*i)->start() >= spec.start_frame && (*i)->end() <= spec.end_frame && (*i)->is_cd_marker() && !(*i)->is_end()) {
649             temp.push_back (*i);
650             if (!(*i)->is_mark()) {
651               numtracks ++;
652             }
653           }
654         }
655
656         if (numtracks == 0 ) {
657                     /* the user supplied no track markers.
658                        we now treat the session as one track.*/
659
660                     out << endl << "TRACK AUDIO" << endl;
661                    
662                     out << "COPY" << endl;
663
664                     out << "NO PRE_EMPHASIS" << endl;
665    
666                     /* XXX add session properties for catalog etc.
667                        (so far only the session name is used) */
668                     
669                     out << "CD_TEXT {" << endl << "  LANGUAGE 0 {" << endl << "     TITLE \"" << session->name() << "\"" << endl;
670                     out << "  }" << endl << "}" << endl;
671
672                     out << "FILE \"" << path << "\" ";
673                     out << "00:00:00 " ;
674                     frames_to_cd_frames_string (buf, spec.end_frame - spec.start_frame, session->frame_rate());
675                     out << buf << endl;
676                     out << "START 00:00:00" << endl;
677
678                     last_start_time = spec.start_frame;
679                     last_end_time = spec.end_frame;
680         } 
681
682         if (temp.size()) {
683                 LocationSortByStart cmp;
684                 temp.sort (cmp);
685
686                 for (i = temp.begin(); i != temp.end(); ++i) {
687         
688                       if (!(*i)->is_mark()) {
689                         /*this is a track */
690                         out << endl << "TRACK AUDIO" << endl;
691
692                         if ((*i)->cd_info.find("scms") != (*i)->cd_info.end())  {
693                           out << "NO ";
694                         }
695                         out << "COPY" << endl;
696
697                         if ((*i)->cd_info.find("preemph") != (*i)->cd_info.end())  {
698                           out << "PRE_EMPHASIS" << endl;
699                         } else {
700                           out << "NO PRE_EMPHASIS" << endl;
701                         }
702
703                         if ((*i)->cd_info.find("isrc") != (*i)->cd_info.end())  {
704                           out << "ISRC \"" << (*i)->cd_info["isrc"] << "\"" << endl;
705                         }
706
707                         out << "CD_TEXT {" << endl << "  LANGUAGE 0 {" << endl << "     TITLE \"" << (*i)->name() << "\"" << endl;
708                         if ((*i)->cd_info.find("performer") != (*i)->cd_info.end()) {
709                           out << "     PERFORMER \"" << (*i)->cd_info["performer"]  << "\"" << endl;
710                         }
711                         if ((*i)->cd_info.find("string_composer") != (*i)->cd_info.end()) {
712                           out  << "     COMPOSER \"" << (*i)->cd_info["string_composer"] << "\"" << endl;
713                         }
714
715                         if ((*i)->cd_info.find("isrc") != (*i)->cd_info.end()) {                          
716                           out  << "     ISRC \"";
717                           out << (*i)->cd_info["isrc"].substr(0,2) << "-";
718                           out << (*i)->cd_info["isrc"].substr(2,3) << "-";
719                           out << (*i)->cd_info["isrc"].substr(5,2) << "-";
720                           out << (*i)->cd_info["isrc"].substr(7,5) << "\"" << endl;
721                         }
722
723                         out << "  }" << endl << "}" << endl;
724
725                         frames_to_cd_frames_string (buf, last_end_time - spec.start_frame, session->frame_rate());
726                         out << "FILE \"" << path << "\" " << buf;
727
728                         frames_to_cd_frames_string (buf, (*i)->end() - last_end_time, session->frame_rate());
729                         out << buf << endl;
730
731                         frames_to_cd_frames_string (buf, (*i)->start() - last_end_time, session->frame_rate());
732                         out << "START" << buf << endl;
733                         
734                         last_start_time = (*i)->start();
735                         last_end_time = (*i)->end();
736                  
737
738                       } else  if ((*i)->start() < last_end_time) {
739                         /* this is an index within a track */
740                         
741                         frames_to_cd_frames_string (buf, (*i)->start() - last_start_time, session->frame_rate());
742                         out << "INDEX" << buf << endl;
743                       }
744                 }
745         }
746         
747 }
748
749 void
750 ExportDialog::export_cue_file (Locations::LocationList& locations, const string& path)
751 {
752         if(!export_cd_markers_allowed){
753                 return;
754         }
755         
756     string filepath = path + ".cue";
757         ofstream out (filepath.c_str());
758         gchar buf[18];
759         long unsigned int last_track_end = spec.start_frame;
760         int numtracks = 0, tracknum = 0, indexnum = 0;
761
762         if (!out) {
763                 error << string_compose(_("Editor: cannot open \"%1\" as export file for CD cue file"), filepath) << endmsg;
764                 return;
765         }
766
767         Locations::LocationList::iterator i;
768         Locations::LocationList temp;
769
770         for (i = locations.begin(); i != locations.end(); ++i) {
771                 if ((*i)->start() >= spec.start_frame && (*i)->end() <= spec.end_frame && (*i)->is_cd_marker() && !(*i)->is_end()) {
772                         temp.push_back (*i);
773                         if (!(*i)->is_mark()) {
774                                 numtracks++;
775                         }
776                 }
777         }
778         
779         out << "REM Cue file generated by Ardour" << endl;
780         out << "TITLE \"" << session->name() << "\"" << endl;
781
782         if ((header_format_combo.get_active_text() == N_("WAV"))) {
783                   out << "FILE " << path  << " WAVE" << endl;
784         } else {
785                   out << "FILE " << path  << ' ' << (header_format_combo.get_active_text()) << endl;
786         }
787
788         if (numtracks == 0) {
789                     /* the user has supplied no track markers.
790                        the entire export is treated as one track. 
791                     */
792
793                   numtracks++;
794                   tracknum++;
795                   indexnum = 0;
796                   out << endl << "TRACK " << tracknum << " AUDIO" << endl;
797                   out << "FLAGS " ;
798                   
799                   out << "DCP " << endl;                   
800                   
801                   /* use the session name*/
802                   
803                   if (session->name() != "") {
804                     out << "TITLE \"" << session->name() << "\"" << endl;
805                   }           
806                   
807                   /* no pregap in this case */
808
809                   out << "INDEX 00 00:00:00" << endl;
810                   indexnum++;
811                   out << "INDEX 01 00:00:00" << endl;
812                   indexnum++;
813                   last_track_end = spec.end_frame;
814         }
815
816         if (temp.size()) {
817                 LocationSortByStart cmp;
818                 temp.sort (cmp);
819
820                 for ( i = temp.begin(); i != temp.end(); ++i) {
821
822                     if (!(*i)->is_mark() && ((*i)->start() >= last_track_end)) {
823                       /* this is a track and it doesn't start inside another one*/
824                       
825                       tracknum++;
826                       indexnum = 0;
827                       out << endl << "TRACK " << tracknum << " AUDIO" << endl;
828                       out << "FLAGS " ;
829                       
830                       if ((*i)->cd_info.find("scms") != (*i)->cd_info.end())  {
831                         out << "SCMS ";
832                       } else {
833                         out << "DCP ";
834                       }
835                       
836                       if ((*i)->cd_info.find("preemph") != (*i)->cd_info.end())  {
837                         out << "PRE";
838                       }
839                       out << endl;
840                       
841                       if ((*i)->cd_info.find("isrc") != (*i)->cd_info.end())  {
842                         out << "ISRC " << (*i)->cd_info["isrc"] << endl;
843                         
844                       }
845                       if ((*i)->name() != "") {
846                         out << "TITLE \"" << (*i)->name() << "\"" << endl;
847                       }       
848                       
849                       if ((*i)->cd_info.find("performer") != (*i)->cd_info.end()) {
850                         out << "PERFORMER \"" <<  (*i)->cd_info["performer"] << "\"" << endl;
851                       }
852                       
853                       if ((*i)->cd_info.find("string_composer") != (*i)->cd_info.end()) {
854                         out << "SONGWRITER \"" << (*i)->cd_info["string_composer"]  << "\"" << endl;
855                       }
856                         snprintf (buf, sizeof(buf), "INDEX %02d", indexnum);
857                         out << buf;
858                         frames_to_cd_frames_string (buf, last_track_end - spec.start_frame, session->frame_rate());
859                         out << buf << endl;
860                         indexnum++;
861                         last_track_end = (*i)->end();
862                     } 
863                     if ((tracknum > 0) && ((*i)->start() < last_track_end)) {
864                       /*this is an index and it lies within a track*/
865                       snprintf (buf, sizeof(buf), "INDEX %02d", indexnum);
866                       out << buf;
867                       frames_to_cd_frames_string (buf,(*i)->start() - spec.start_frame, session->frame_rate());
868                       out << buf << endl;
869                       indexnum++;
870                     }
871                 }
872         }
873         
874 }
875         
876 void
877 ExportDialog::do_export_cd_markers (const string& path,const string& cuefile_type)
878 {
879         if (cuefile_type == _("TOC")) {
880                 session->locations()->apply (*this, &ExportDialog::export_toc_file, path);      
881         } else {
882                 session->locations()->apply (*this, &ExportDialog::export_cue_file, path);
883         }
884 }
885
886
887 void
888 ExportDialog::do_export ()
889 {
890         string filepath = file_entry.get_text();
891         
892         if(!is_filepath_valid(filepath)){
893                 return;
894         }
895
896         if (export_cd_markers_allowed) {
897                 if (cue_file_combo.get_active_text () != _("None")) {
898                         do_export_cd_markers (file_entry.get_text(), cue_file_combo.get_active_text ());
899                 }
900
901                 if (cuefile_only_checkbox.get_active()) {
902                         end_dialog ();
903                         return;
904                 }
905         }
906
907         ok_button->set_sensitive(false);
908         save_state();
909
910         set_modal (true);
911         
912         // read user input into spec
913         initSpec(filepath);
914         
915         progress_connection = Glib::signal_timeout().connect (mem_fun(*this, &ExportDialog::progress_timeout), 100);
916         cancel_label.set_text (_("Stop Export"));
917
918         export_audio_data();
919         
920         progress_connection.disconnect ();
921         end_dialog ();
922 }
923         
924 void
925 ExportDialog::end_dialog ()
926 {
927         if (spec.running) {
928                 spec.stop = true;
929
930                 while (spec.running) {
931                         if (gtk_events_pending()) {
932                                 gtk_main_iteration ();
933                         } else {
934                                 usleep (10000);
935                         }
936                 }
937         }
938
939         session->finalize_audio_export ();
940
941         hide_all ();
942
943         set_modal (false);
944         ok_button->set_sensitive(true);
945 }
946
947 void
948 ExportDialog::start_export ()
949 {
950         if (session == 0) {
951                 return;
952         }
953
954         /* If the filename hasn't been set before, use the
955            current session's export directory as a default
956            location for the export.  
957         */
958         
959         if (file_entry.get_text().length() == 0) {
960                 string dir = session->export_dir();
961                 string::size_type last_slash;
962                 
963                 if ((last_slash = dir.find_last_of ('/')) != string::npos && last_slash != 0) {
964                         dir = dir.substr (0, last_slash+1);
965                 }
966
967                 if (!wants_dir()) {
968                         dir = dir + "export.wav";
969                 }
970                 
971                 file_entry.set_text (dir);
972         }
973         
974         progress_bar.set_fraction (0);
975         cancel_label.set_text (_("Cancel"));
976
977         show_all ();
978
979         if (session->master_out()) {
980                 track_scroll.hide ();
981         } else {
982                 master_scroll.hide ();
983                 track_selector_button.hide ();
984         }
985 }
986
987 void
988 ExportDialog::header_chosen ()
989 {
990         if (sndfile_header_format_from_string (header_format_combo.get_active_text ()) == SF_FORMAT_WAV) {
991                 endian_format_combo.set_sensitive (false);
992         } else {
993                 endian_format_combo.set_sensitive (true);
994         }
995 }
996
997 void
998 ExportDialog::bitdepth_chosen ()
999 {
1000         int format = sndfile_bitdepth_format_from_string (bitdepth_format_combo.get_active_text ());    
1001         switch (format) {
1002         case SF_FORMAT_PCM_24:
1003         case SF_FORMAT_PCM_32:
1004         case SF_FORMAT_FLOAT:
1005                 dither_type_combo.set_sensitive (false);
1006                 break;
1007
1008         default:
1009                 dither_type_combo.set_sensitive (true);
1010                 break;
1011         }
1012 }
1013
1014 void
1015 ExportDialog::cue_file_type_chosen ()
1016 {
1017         if (cue_file_combo.get_active_text () != "None") {
1018                 cuefile_only_checkbox.set_sensitive (true);
1019         } else {
1020                 cuefile_only_checkbox.set_active (false);
1021                 cuefile_only_checkbox.set_sensitive (false);
1022         }
1023 }
1024
1025 void
1026 ExportDialog::sample_rate_chosen ()
1027 {
1028         string sr_str = sample_rate_combo.get_active_text();
1029         nframes_t rate;
1030
1031         if (sr_str == N_("22.05kHz")) {
1032                 rate = 22050;
1033         } else if (sr_str == _("44.1kHz")) {
1034                 rate = 44100;
1035         } else if (sr_str == _("48kHz")) {
1036                 rate = 48000;
1037         } else if (sr_str == _("88.2kHz")) {
1038                 rate = 88200;
1039         } else if (sr_str == _("96kHz")) {
1040                 rate = 96000;
1041         } else if (sr_str == _("192kHz")) {
1042                 rate = 192000;
1043         } else {
1044                 rate = session->frame_rate();
1045         }
1046                 
1047         if (rate != session->frame_rate()) {
1048                 src_quality_combo.set_sensitive (true);
1049         } else {
1050                 src_quality_combo.set_sensitive (false);
1051         }
1052 }
1053
1054 void
1055 ExportDialog::channels_chosen ()
1056 {
1057         bool mono;
1058
1059         mono = (channel_count_combo.get_active_text() == _("mono"));
1060
1061         if (mono) {
1062                 track_selector.get_column(2)->set_visible(false);
1063                 track_selector.get_column(1)->set_title(_("Export"));
1064
1065                 if (session->master_out()) {
1066                         master_selector.get_column(2)->set_visible(false);
1067                         master_selector.get_column(1)->set_title(_("Export"));
1068                 }
1069
1070         } else {
1071                 track_selector.get_column(2)->set_visible(true);
1072                 track_selector.get_column(1)->set_title(_("Left"));
1073
1074                 if (session->master_out()) {
1075                         master_selector.get_column(2)->set_visible(true);
1076                         master_selector.get_column(1)->set_title(_("Left"));
1077                 }
1078         }
1079
1080         fill_lists();
1081 }
1082
1083 void
1084 ExportDialog::fill_lists ()
1085 {
1086         track_list->clear();
1087         master_list->clear();
1088         
1089         boost::shared_ptr<Session::RouteList> routes = session->get_routes ();
1090
1091         for (Session::RouteList::iterator ri = routes->begin(); ri != routes->end(); ++ri) {
1092                 
1093                 boost::shared_ptr<Route> route = (*ri);
1094                 
1095                 if (route->hidden()) {
1096                         continue;
1097                 }
1098
1099                 for (uint32_t i=0; i < route->n_outputs().get(DataType::AUDIO); ++i) {
1100                         string name;
1101                         if (route->n_outputs().get(DataType::AUDIO) == 1) {
1102                                 name = route->name();
1103                         } else {
1104                                 name = string_compose("%1: out-%2", route->name(), i+1);
1105                         }
1106
1107                         if (route == session->master_out()) {
1108                                 TreeModel::iterator iter = master_list->append();
1109                                 TreeModel::Row row = *iter;
1110                                 row[exp_cols.output] = name;
1111                                 row[exp_cols.left] = false;
1112                                 row[exp_cols.right] = false;
1113                                 row[exp_cols.port] = route->output (i);
1114                         } else {
1115                                 TreeModel::iterator iter = track_list->append();
1116                                 TreeModel::Row row = *iter;
1117                                 row[exp_cols.output] = name;
1118                                 row[exp_cols.left] = false;
1119                                 row[exp_cols.right] = false;
1120                                 row[exp_cols.port] = route->output (i);
1121                         }
1122                 }
1123         }
1124 }
1125
1126
1127 bool
1128 ExportDialog::is_filepath_valid(string &filepath)
1129 {
1130         // sanity check file name first
1131
1132         struct stat statbuf;
1133   
1134         if (filepath.empty()) {
1135                 string txt = _("Please enter a valid filename.");
1136                 MessageDialog msg (*this, txt, false, MESSAGE_ERROR, BUTTONS_OK, true);
1137                 msg.run();
1138                 return false;
1139         }
1140         
1141         // check if file exists already and warn
1142
1143         if (stat (filepath.c_str(), &statbuf) == 0) {
1144                 if (S_ISDIR (statbuf.st_mode)) {
1145                         string txt = _("Please specify a complete filename for the audio file.");
1146                         MessageDialog msg (*this, txt, false, MESSAGE_ERROR, BUTTONS_OK, true);
1147                         msg.run();
1148                         return false;
1149                 }
1150                 else {
1151                         string txt = _("File already exists, do you want to overwrite it?");
1152                         MessageDialog msg (*this, txt, false, MESSAGE_QUESTION, BUTTONS_YES_NO, true);
1153                         if ((ResponseType) msg.run() == Gtk::RESPONSE_NO) {
1154                                 return false;
1155                         }
1156                 }
1157         }
1158         
1159         // directory needs to exist and be writable
1160
1161         string dirpath = Glib::path_get_dirname (filepath);
1162         if (::access (dirpath.c_str(), W_OK) != 0) {
1163                 string txt = _("Cannot write file in: ") + dirpath;
1164                 MessageDialog msg (*this, txt, false, MESSAGE_ERROR, BUTTONS_OK, true);
1165                 msg.run();
1166                 return false;
1167         }
1168         
1169         return true;
1170 }
1171
1172 void
1173 ExportDialog::initSpec(string &filepath)
1174 {
1175         spec.path = filepath;
1176         spec.progress = 0;
1177         spec.running = true;
1178         spec.stop = false;
1179         spec.port_map.clear();
1180         
1181         if (channel_count_combo.get_active_text() == _("mono")) {
1182                 spec.channels = 1;
1183         } else {
1184                 spec.channels = 2;
1185         }
1186
1187         spec.format = 0;
1188
1189         spec.format |= sndfile_header_format_from_string (header_format_combo.get_active_text ());
1190         
1191         if ((spec.format & SF_FORMAT_WAV) == 0) {
1192                 /* RIFF/WAV specifies endianess */
1193                 spec.format |= sndfile_endian_format_from_string (endian_format_combo.get_active_text ());
1194         }
1195
1196         spec.format |= sndfile_bitdepth_format_from_string (bitdepth_format_combo.get_active_text ());
1197
1198         string sr_str = sample_rate_combo.get_active_text();
1199         if (sr_str == N_("22.05kHz")) {
1200                 spec.sample_rate = 22050;
1201         } else if (sr_str == _("44.1kHz")) {
1202                 spec.sample_rate = 44100;
1203         } else if (sr_str == _("48kHz")) {
1204                 spec.sample_rate = 48000;
1205         } else if (sr_str == _("88.2kHz")) {
1206                 spec.sample_rate = 88200;
1207         } else if (sr_str == _("96kHz")) {
1208                 spec.sample_rate = 96000;
1209         } else if (sr_str == _("192kHz")) {
1210                 spec.sample_rate = 192000;
1211         } else {
1212                 spec.sample_rate = session->frame_rate();
1213         }
1214         
1215         string src_str = src_quality_combo.get_active_text();
1216         if (src_str == _("fastest")) {
1217                 spec.src_quality = SRC_ZERO_ORDER_HOLD;
1218         } else if (src_str == _("linear")) {
1219                 spec.src_quality = SRC_LINEAR;
1220         } else if (src_str == _("better")) {
1221                 spec.src_quality = SRC_SINC_FASTEST;
1222         } else if (src_str == _("intermediate")) {
1223                 spec.src_quality = SRC_SINC_MEDIUM_QUALITY;
1224         } else {
1225                 spec.src_quality = SRC_SINC_BEST_QUALITY;
1226         }
1227
1228         string dither_str = dither_type_combo.get_active_text();
1229         if (dither_str == _("None")) {
1230                 spec.dither_type = GDitherNone;
1231         } else if (dither_str == _("Rectangular")) {
1232                 spec.dither_type = GDitherRect;
1233         } else if (dither_str == _("Triangular")) {
1234                 spec.dither_type = GDitherTri;
1235         } else {
1236                 spec.dither_type = GDitherShaped;
1237         } 
1238
1239         write_track_and_master_selection_to_spec();
1240 }
1241
1242
1243 void
1244 ExportDialog::write_track_and_master_selection_to_spec()
1245 {
1246         if(!track_and_master_selection_allowed){
1247                 return;
1248         }
1249
1250         uint32_t chan=0;
1251         Port *last_port = 0;
1252                 
1253         TreeModel::Children rows = master_selector.get_model()->children();
1254         TreeModel::Children::iterator ri;
1255         TreeModel::Row row;
1256         for (ri = rows.begin(); ri != rows.end(); ++ri) {
1257                 row = *ri;
1258                 Port* port = row[exp_cols.port];
1259                 
1260                 if (last_port != port) {
1261                         chan = 0;
1262                 }
1263                 
1264                 if (row[exp_cols.left]) {
1265                         spec.port_map[0].push_back (std::pair<Port*,uint32_t>(port, chan));
1266                 } 
1267                 
1268                 if (spec.channels == 2) {
1269                         if (row[exp_cols.right]) {
1270                                 spec.port_map[1].push_back (std::pair<Port*,uint32_t>(port, chan));
1271                         }
1272                 }
1273         }
1274         
1275         chan = 0;
1276         rows = track_selector.get_model()->children();
1277
1278         for (ri = rows.begin(); ri != rows.end(); ++ri) {
1279                 row = *ri;
1280                 
1281                 Port* port = row[exp_cols.port];
1282                 
1283                 if (last_port != port) {
1284                         chan = 0;
1285                 }
1286                 
1287                 if (row[exp_cols.left]) {
1288                         spec.port_map[0].push_back (std::pair<Port*,uint32_t>(port, chan));
1289                 } 
1290                 
1291                 if (spec.channels == 2) {
1292                         if (row[exp_cols.right]) {
1293                                 spec.port_map[1].push_back (std::pair<Port*,uint32_t>(port, chan));
1294                         }
1295                         
1296                 }
1297                 
1298                 last_port = port;
1299                 ++chan;
1300         }
1301 }
1302
1303
1304 gint
1305 ExportDialog::window_closed (GdkEventAny *ignored)
1306 {
1307         end_dialog ();
1308         return TRUE;
1309 }
1310
1311 void
1312 ExportDialog::browse ()
1313 {
1314         FileChooserDialog dialog("Export to file", browse_action());
1315         dialog.set_transient_for(*this);
1316         dialog.set_filename (file_entry.get_text());
1317
1318         dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
1319         dialog.add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK);
1320   
1321         int result = dialog.run();
1322
1323         if (result == Gtk::RESPONSE_OK) {
1324                 string filename = dialog.get_filename();
1325         
1326                 if (filename.length()) {
1327                         file_entry.set_text (filename);
1328                 }
1329         }
1330 }
1331
1332 void
1333 ExportDialog::track_selector_button_click ()
1334 {
1335         if (track_scroll.is_visible ()) {
1336                 track_scroll.hide ();
1337         } else {
1338                 track_scroll.show_all ();
1339         }
1340 }