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