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