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