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