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