new color management design starts to take shape (canvas color only for now)
[ardour.git] / gtk2_ardour / export_dialog.cc
1 /*
2     Copyright (C) 1999-2005 Paul Davis 
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18     $Id$
19
20 */
21
22 #include <unistd.h>
23 #include <utility>
24 #include <sys/stat.h>
25
26 #include <fstream>
27
28 #include <samplerate.h>
29 #include <pbd/pthread_utils.h>
30 #include <pbd/xml++.h>
31 #include <pbd/dirname.h>
32
33 #include <gtkmm2ext/utils.h>
34 #include <ardour/export.h>
35 #include <ardour/sndfile_helpers.h>
36 #include <ardour/audio_track.h>
37 #include <ardour/audioregion.h>
38 #include <ardour/audioengine.h>
39 #include <ardour/gdither.h>
40 #include <ardour/utils.h>
41
42 #include "export_dialog.h"
43 #include "ardour_ui.h"
44 #include "public_editor.h"
45 #include "keyboard.h"
46 #include "ardour_message.h"
47
48 #include "i18n.h"
49
50 #define FRAME_NAME "BaseFrame"
51
52 using namespace std;
53
54 using namespace ARDOUR;
55 using namespace sigc;
56 using namespace Gtk;
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, AudioRegion* r)
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         audio_region = r;
121
122         session = 0;
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         file_selector = 0;
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         if (!audio_region) {
181
182                 master_scroll.add (master_selector);
183                 track_scroll.add (track_selector);
184
185                 master_scroll.set_size_request (220, 100);
186                 track_scroll.set_size_request (220, 100);
187
188                 
189                 
190                 /* we may hide some of these later */
191                 track_vpacker.pack_start (master_scroll);
192                 track_vpacker.pack_start (track_scroll);
193                 track_vpacker.pack_start (track_selector_button, Gtk::PACK_EXPAND_PADDING);
194
195                 hpacker.pack_start (track_vpacker);
196         }
197
198         get_vbox()->pack_start (hpacker);
199         
200         track_selector_button.set_name ("EditorGTKButton");
201         track_selector_button.signal_clicked().connect (mem_fun(*this, &ExportDialog::track_selector_button_click));
202
203         get_vbox()->pack_start (progress_bar, false, false);
204
205         Gtkmm2ext::set_size_request_to_display_given_text (file_entry, X_("Kg/quite/a/reasonable/size/for/files/i/think"), 5, 8);
206
207         file_hbox.set_spacing (5);
208         file_hbox.set_border_width (5);
209         file_hbox.pack_start (file_entry, true, true);
210         file_hbox.pack_start (file_browse_button, false, false);
211
212         file_frame.add (file_hbox);
213         file_frame.set_border_width (5);
214         file_frame.set_name (FRAME_NAME);
215
216         /* pop_strings needs to be created on the stack because set_popdown_strings()
217            takes a reference. 
218         */
219
220         vector<string> pop_strings = internationalize(sample_rates);
221         Gtkmm2ext::set_popdown_strings (sample_rate_combo, pop_strings);
222         sample_rate_combo.set_active_text (pop_strings.front());
223         pop_strings = internationalize(src_quality);
224         Gtkmm2ext::set_popdown_strings (src_quality_combo, pop_strings);
225         src_quality_combo.set_active_text (pop_strings.front());
226         pop_strings = internationalize(dither_types);
227         Gtkmm2ext::set_popdown_strings (dither_type_combo, pop_strings);
228         dither_type_combo.set_active_text (pop_strings.front());
229         pop_strings = internationalize(channel_strings);
230         Gtkmm2ext::set_popdown_strings (channel_count_combo, pop_strings);
231         channel_count_combo.set_active_text (pop_strings.front());
232         pop_strings = internationalize((const char **) sndfile_header_formats_strings);
233         Gtkmm2ext::set_popdown_strings (header_format_combo, pop_strings);
234         header_format_combo.set_active_text (pop_strings.front());
235         pop_strings = internationalize((const char **) sndfile_bitdepth_formats_strings);
236         Gtkmm2ext::set_popdown_strings (bitdepth_format_combo, pop_strings);
237         bitdepth_format_combo.set_active_text (pop_strings.front());
238         pop_strings = internationalize((const char **) sndfile_endian_formats_strings);
239         Gtkmm2ext::set_popdown_strings (endian_format_combo, pop_strings);
240         endian_format_combo.set_active_text (pop_strings.front());
241         pop_strings = internationalize(cue_file_types);
242         Gtkmm2ext::set_popdown_strings (cue_file_combo, pop_strings);
243         cue_file_combo.set_active_text (pop_strings.front());
244
245         /* this will re-sensitized as soon as a non RIFF/WAV
246            header format is chosen.
247         */
248
249         endian_format_combo.set_sensitive (false);
250
251         /* determine longest strings at runtime */
252
253         maxlen = 0;
254         const char *longest = "gl";
255         string longest_str;
256
257         for (n = 0; n < SNDFILE_HEADER_FORMATS; ++n) {
258                 if ((len = strlen (sndfile_header_formats_strings[n])) > maxlen) {
259                         maxlen = len;
260                         longest = sndfile_header_formats_strings[n];
261                 }
262         }
263
264         for (n = 0; n < SNDFILE_BITDEPTH_FORMATS; ++n) {
265                 if ((len = strlen (sndfile_bitdepth_formats_strings[n])) > maxlen) {
266                         maxlen = len;
267                         longest = sndfile_bitdepth_formats_strings[n];
268                 }
269         }
270
271         for (n = 0; n < SNDFILE_ENDIAN_FORMATS; ++n) {
272                 if ((len = strlen (sndfile_endian_formats_strings[n])) > maxlen) {
273                         maxlen = len;
274                         longest = sndfile_endian_formats_strings[n];
275                 }
276         }
277
278         longest_str = longest;
279
280         /* force ascender + descender */
281
282         longest_str[0] = 'g';
283         longest_str[1] = 'l';
284
285         //Gtkmm2ext::set_size_request_to_display_given_text (header_format_combo, longest_str.c_str(), 5+FUDGE, 5);
286
287         // TRANSLATORS: "slereg" is "stereo" with ascender and descender substituted
288         //Gtkmm2ext::set_size_request_to_display_given_text (channel_count_combo, _("slereg"), 5+FUDGE, 5);
289
290 /*      header_format_combo.set_focus_on_click (true);
291         bitdepth_format_combo.set_focus_on_click (true);
292         endian_format_combo.set_focus_on_click (true);
293         channel_count_combo.set_focus_on_click (true);
294         src_quality_combo.set_focus_on_click (true);
295         dither_type_combo.set_focus_on_click (true);
296         sample_rate_combo.set_focus_on_click (true);
297         cue_file_combo.set_focus_on_click (true);
298 */
299         dither_type_label.set_name ("ExportFormatLabel");
300         sample_rate_label.set_name ("ExportFormatLabel");
301         src_quality_label.set_name ("ExportFormatLabel");
302         channel_count_label.set_name ("ExportFormatLabel");
303         header_format_label.set_name ("ExportFormatLabel");
304         bitdepth_format_label.set_name ("ExportFormatLabel");
305         endian_format_label.set_name ("ExportFormatLabel");
306         cue_file_label.set_name ("ExportFormatLabel");
307
308         header_format_combo.set_name ("ExportFormatDisplay");
309         bitdepth_format_combo.set_name ("ExportFormatDisplay");
310         endian_format_combo.set_name ("ExportFormatDisplay");
311         channel_count_combo.set_name ("ExportFormatDisplay");
312         dither_type_combo.set_name ("ExportFormatDisplay");
313         src_quality_combo.set_name ("ExportFormatDisplay");
314         sample_rate_combo.set_name ("ExportFormatDisplay");
315         cue_file_combo.set_name ("ExportFormatDisplay");
316
317         cuefile_only_checkbox.set_name ("ExportCheckbox");
318
319         format_table.set_homogeneous (false);
320         format_table.set_border_width (5);
321         format_table.set_col_spacings (5);
322         format_table.set_row_spacings (5);
323
324         if (!audio_region) {
325                 format_table.attach (channel_count_label, 0, 1, 0, 1);
326                 format_table.attach (channel_count_combo, 1, 2, 0, 1);
327         }
328
329         format_table.attach (header_format_label, 0, 1, 1, 2);
330         format_table.attach (header_format_combo, 1, 2, 1, 2);
331
332         format_table.attach (bitdepth_format_label, 0, 1, 2, 3);
333         format_table.attach (bitdepth_format_combo, 1, 2, 2, 3);
334
335         format_table.attach (endian_format_label, 0, 1, 3, 4);
336         format_table.attach (endian_format_combo, 1, 2, 3, 4);
337
338         format_table.attach (sample_rate_label, 0, 1, 4, 5);
339         format_table.attach (sample_rate_combo, 1, 2, 4, 5);
340
341         format_table.attach (src_quality_label, 0, 1, 5, 6);
342         format_table.attach (src_quality_combo, 1, 2, 5, 6);
343
344         format_table.attach (dither_type_label, 0, 1, 6, 7);
345         format_table.attach (dither_type_combo, 1, 2, 6, 7);
346
347         format_table.attach (cue_file_label, 0, 1, 7, 8);
348         format_table.attach (cue_file_combo, 1, 2, 7, 8);
349         format_table.attach (cuefile_only_checkbox, 0, 2, 8, 9);
350
351         file_entry.set_name ("ExportFileDisplay");
352
353         signal_delete_event().connect (mem_fun(*this, &ExportDialog::window_closed));
354
355         cancel_button = add_button (Stock::CANCEL, RESPONSE_CANCEL);
356         cancel_button->signal_clicked().connect (mem_fun(*this, &ExportDialog::end_dialog));
357         ok_button = add_button (Stock::OK, RESPONSE_ACCEPT);
358         ok_button->signal_clicked().connect (mem_fun(*this, &ExportDialog::do_export));
359         
360         file_browse_button.set_name ("EditorGTKButton");
361         file_browse_button.signal_clicked().connect (mem_fun(*this, &ExportDialog::initiate_browse));
362
363         channel_count_combo.signal_changed().connect (mem_fun(*this, &ExportDialog::channels_chosen));
364         bitdepth_format_combo.signal_changed().connect (mem_fun(*this, &ExportDialog::bitdepth_chosen));
365         header_format_combo.signal_changed().connect (mem_fun(*this, &ExportDialog::header_chosen));
366         sample_rate_combo.signal_changed().connect (mem_fun(*this, &ExportDialog::sample_rate_chosen));
367         cue_file_combo.signal_changed().connect (mem_fun(*this, &ExportDialog::cue_file_type_chosen));
368 }
369
370 ExportDialog::~ExportDialog()
371 {
372         if (file_selector) {
373                 delete file_selector;
374         }
375 }
376
377 void
378 ExportDialog::connect_to_session (Session *s)
379 {
380         session = s;
381         session->going_away.connect (mem_fun(*this, &Window::hide_all));
382
383         switch (session->frame_rate()) {
384         case 22050:
385                 sample_rate_combo.set_active_text (N_("22.05kHz"));
386                 break;
387         case 44100:
388                 sample_rate_combo.set_active_text (N_("44.1kHz"));
389                 break;
390         case 48000:
391                 sample_rate_combo.set_active_text (N_("48kHz"));
392                 break;
393         case 88200:
394                 sample_rate_combo.set_active_text (N_("88.2kHz"));
395                 break;
396         case 96000:
397                 sample_rate_combo.set_active_text (N_("96kHz"));
398                 break;
399         case 192000:
400                 sample_rate_combo.set_active_text (N_("192kHz"));
401                 break;
402         default:
403                 sample_rate_combo.set_active_text (N_("44.1kHz"));
404                 break;
405         }
406
407         src_quality_combo.set_sensitive (false);
408
409         set_state();
410 }
411
412 void
413 ExportDialog::set_state()
414 {
415         XMLNode* node = session->instant_xml(X_("ExportDialog"), session->path());
416         XMLProperty* prop;
417
418         if (node) {
419
420                 if ((prop = node->property (X_("sample_rate"))) != 0) {
421                         sample_rate_combo.set_active_text(prop->value());
422                 }
423                 if ((prop = node->property (X_("src_quality"))) != 0) {
424                         src_quality_combo.set_active_text(prop->value());
425                 }
426                 if ((prop = node->property (X_("dither_type"))) != 0) {
427                         dither_type_combo.set_active_text(prop->value());
428                 }
429                 if ((prop = node->property (X_("channel_count"))) != 0) {
430                         channel_count_combo.set_active_text(prop->value());
431                 }
432                 if ((prop = node->property (X_("header_format"))) != 0) {
433                         header_format_combo.set_active_text(prop->value());
434                 }
435                 if ((prop = node->property (X_("bitdepth_format"))) != 0) {
436                         bitdepth_format_combo.set_active_text(prop->value());
437                 }
438                 if ((prop = node->property (X_("endian_format"))) != 0) {
439                         endian_format_combo.set_active_text(prop->value());
440                 }
441                 if ((prop = node->property (X_("filename"))) != 0) {
442                         file_entry.set_text(prop->value());
443                 }
444                 if ((prop = node->property (X_("cue_file_type"))) != 0) {
445                         cue_file_combo.set_active_text(prop->value());
446                 }
447         }
448
449         header_chosen ();
450         bitdepth_chosen();
451         channels_chosen();
452         sample_rate_chosen();
453
454         if (session->master_out()) {
455                 track_scroll.hide ();
456         } else {
457                 master_scroll.hide ();
458                 track_selector_button.hide ();
459         }
460
461         if (!node) {
462                 return;
463         }
464
465         if (session->master_out()) {
466                 XMLNode* master = find_named_node(*node, (X_("Master")));
467                 int nchns;
468
469                 if (!master) {
470                         
471                         /* default is to use all */
472                         if (channel_count_combo.get_active_text() == _("mono")) {
473                                 nchns = 1;
474                         } else {
475                                 nchns = 2;
476                         }
477
478                         TreeModel::Children rows = master_selector.get_model()->children();
479                         for (uint32_t r = 0; r < session->master_out()->n_outputs(); ++r) {
480                                 if (nchns == 2) {
481                                         if (r % 2) {
482                                                 rows[r][exp_cols.right] = true;
483                                         } else {
484                                                 rows[r][exp_cols.left] = true;
485                                         }
486                                 } else {
487                                         rows[r][exp_cols.left] = true;
488                                 }
489                         }
490
491                 } else {
492                         /* XXX use XML state */
493                 }
494         }
495
496         XMLNode* tracks = find_named_node(*node, (X_("Tracks")));
497         if (!tracks) {
498                 return;
499         }
500         
501         XMLNodeList track_list = tracks->children(X_("Track"));
502         TreeModel::Children rows = track_selector.get_model()->children();
503         TreeModel::Children::iterator ri = rows.begin();
504         TreeModel::Row row;
505
506         for (XMLNodeIterator it = track_list.begin(); it != track_list.end(); ++it, ++ri) {
507                 if (ri == rows.end()){
508                         break;
509                 }
510
511                 XMLNode* track = *it;
512                 row = *ri;
513
514                 if ((prop = track->property(X_("channel1"))) != 0) {
515                         if (prop->value() == X_("on")) {
516                                 row[exp_cols.left] = true;
517                         } else {
518                                 row[exp_cols.left] = false;
519                         }
520                 }
521
522                 if ((prop = track->property(X_("channel2"))) != 0) {
523                         if (prop->value() == X_("on")) {
524                                 row[exp_cols.right] = true;
525                         } else {
526                                 row[exp_cols.right] = false;
527                         }
528                 }
529         }
530 }
531
532 void
533 ExportDialog::save_state()
534 {
535         if (!session) {
536                 return;
537         }
538
539         XMLNode* node = new XMLNode(X_("ExportDialog"));
540
541         node->add_property(X_("sample_rate"), sample_rate_combo.get_active_text());
542         node->add_property(X_("src_quality"), src_quality_combo.get_active_text());
543         node->add_property(X_("dither_type"), dither_type_combo.get_active_text());
544         node->add_property(X_("channel_count"), channel_count_combo.get_active_text());
545         node->add_property(X_("header_format"), header_format_combo.get_active_text());
546         node->add_property(X_("bitdepth_format"), bitdepth_format_combo.get_active_text());
547         node->add_property(X_("endian_format"), endian_format_combo.get_active_text());
548         node->add_property(X_("filename"), file_entry.get_text());
549         node->add_property(X_("cue_file_type"), cue_file_combo.get_active_text());
550
551         XMLNode* tracks = new XMLNode(X_("Tracks"));
552
553         TreeModel::Children rows = track_selector.get_model()->children();
554         TreeModel::Row row;
555         for (TreeModel::Children::iterator ri = rows.begin(); ri != rows.end(); ++ri) {
556                 XMLNode* track = new XMLNode(X_("Track"));
557
558                 row = *ri;
559                 track->add_property(X_("channel1"), row[exp_cols.left] ? X_("on") : X_("off"));
560                 track->add_property(X_("channel1"), row[exp_cols.right] ? X_("on") : X_("off"));
561
562                 tracks->add_child_nocopy(*track);
563         }
564         node->add_child_nocopy(*tracks);
565         
566         session->add_instant_xml(*node, session->path());
567 }
568
569 void
570 ExportDialog::set_range (jack_nframes_t start, jack_nframes_t end)
571 {
572         spec.start_frame = start;
573         spec.end_frame = end;
574
575         if (!audio_region) {
576                 // XXX: this is a hack until we figure out what is really wrong
577                 session->request_locate (spec.start_frame, false);
578         }
579 }
580
581 gint
582 ExportDialog::progress_timeout ()
583 {
584         progress_bar.set_fraction (spec.progress/100);
585         return TRUE;
586 }
587
588 void*
589 ExportDialog::_export_region_thread (void *arg)
590 {
591         PBD::ThreadCreated (pthread_self(), X_("Export Region"));
592
593         static_cast<ExportDialog*>(arg)->export_region ();
594         return 0;
595 }
596
597 void
598 ExportDialog::export_region ()
599 {
600         audio_region->exportme (*session, spec);
601 }
602
603 void
604 frames_to_cd_frames_string (char* buf, jack_nframes_t when, jack_nframes_t fr)
605 {
606
607   long unsigned int remainder;
608   int mins, secs, frames;
609
610         mins = when / (60 * fr);
611         remainder = when - (mins * 60 * fr);
612         secs = remainder / fr;
613         remainder -= secs * fr;
614         frames = remainder / (fr / 75);
615         sprintf (buf, " %02d:%02d:%02d", mins, secs, frames);
616
617 }
618
619 struct LocationSortByStart {
620     bool operator() (Location *a, Location *b) {
621             return a->start() < b->start();
622     }
623 };
624
625 void
626 ExportDialog::export_toc_file (Locations::LocationList& locations, const string& path)
627 {
628         
629         string filepath = path + ".toc";
630         ofstream out (filepath.c_str());
631         long unsigned int last_end_time = spec.start_frame, last_start_time = spec.start_frame;
632         int numtracks = 0;
633         gchar buf[18];
634
635         if (!out) {
636                 error << string_compose(_("Editor: cannot open \"%1\" as export file for CD toc file"), filepath) << endmsg;
637                 return;
638         }
639         out << "CD_DA" << endl;
640         out << "CD_TEXT {" << endl << "  LANGUAGE_MAP {" << endl << "    0 : EN" << endl << "  }" << endl;
641         out << "  LANGUAGE 0 {" << endl << "    TITLE \"" << session->name() << "\"" << endl << "  }" << endl << "}" << endl;
642
643         Locations::LocationList::iterator i;
644         Locations::LocationList temp;
645
646         for (i = locations.begin(); i != locations.end(); ++i) {
647           if ((*i)->start() >= spec.start_frame && (*i)->end() <= spec.end_frame && (*i)->is_cd_marker() && !(*i)->is_end()) {
648             temp.push_back (*i);
649             if (!(*i)->is_mark()) {
650               numtracks ++;
651             }
652           }
653         }
654
655         if (numtracks == 0 ) {
656                     /* the user supplied no track markers.
657                        we now treat the session as one track.*/
658
659                     out << endl << "TRACK AUDIO" << endl;
660                    
661                     out << "COPY" << endl;
662
663                     out << "NO PRE_EMPHASIS" << endl;
664    
665                     /* XXX add session properties for catalog etc.
666                        (so far only the session name is used) */
667                     
668                     out << "CD_TEXT {" << endl << "  LANGUAGE 0 {" << endl << "     TITLE \"" << session->name() << "\"" << endl;
669                     out << "  }" << endl << "}" << endl;
670
671                     out << "FILE \"" << path << "\" ";
672                     out << "00:00:00 " ;
673                     frames_to_cd_frames_string (buf, spec.end_frame - spec.start_frame, session->frame_rate());
674                     out << buf << endl;
675                     out << "START 00:00:00" << endl;
676
677                     last_start_time = spec.start_frame;
678                     last_end_time = spec.end_frame;
679         } 
680
681         if (temp.size()) {
682                 LocationSortByStart cmp;
683                 temp.sort (cmp);
684
685                 for (i = temp.begin(); i != temp.end(); ++i) {
686         
687                       if (!(*i)->is_mark()) {
688                         /*this is a track */
689                         out << endl << "TRACK AUDIO" << endl;
690
691                         if ((*i)->cd_info.find("scms") != (*i)->cd_info.end())  {
692                           out << "NO ";
693                         }
694                         out << "COPY" << endl;
695
696                         if ((*i)->cd_info.find("preemph") != (*i)->cd_info.end())  {
697                           out << "PRE_EMPHASIS" << endl;
698                         } else {
699                           out << "NO PRE_EMPHASIS" << endl;
700                         }
701
702                         if ((*i)->cd_info.find("isrc") != (*i)->cd_info.end())  {
703                           out << "ISRC \"" << (*i)->cd_info["isrc"] << "\"" << endl;
704                         }
705
706                         out << "CD_TEXT {" << endl << "  LANGUAGE 0 {" << endl << "     TITLE \"" << (*i)->name() << "\"" << endl;
707                         if ((*i)->cd_info.find("performer") != (*i)->cd_info.end()) {
708                           out << "     PERFORMER \"" << (*i)->cd_info["performer"]  << "\"" << endl;
709                         }
710                         if ((*i)->cd_info.find("string_composer") != (*i)->cd_info.end()) {
711                           out  << "     COMPOSER \"" << (*i)->cd_info["string_composer"] << "\"" << endl;
712                         }
713
714                         if ((*i)->cd_info.find("isrc") != (*i)->cd_info.end()) {                          
715                           out  << "     ISRC \"";
716                           out << (*i)->cd_info["isrc"].substr(0,2) << "-";
717                           out << (*i)->cd_info["isrc"].substr(2,3) << "-";
718                           out << (*i)->cd_info["isrc"].substr(5,2) << "-";
719                           out << (*i)->cd_info["isrc"].substr(7,5) << "\"" << endl;
720                         }
721
722                         out << "  }" << endl << "}" << endl;
723
724                         frames_to_cd_frames_string (buf, last_end_time - spec.start_frame, session->frame_rate());
725                         out << "FILE \"" << path << "\" " << buf;
726
727                         frames_to_cd_frames_string (buf, (*i)->end() - last_end_time, session->frame_rate());
728                         out << buf << endl;
729
730                         frames_to_cd_frames_string (buf, (*i)->start() - last_end_time, session->frame_rate());
731                         out << "START" << buf << endl;
732                         
733                         last_start_time = (*i)->start();
734                         last_end_time = (*i)->end();
735                  
736
737                       } else  if ((*i)->start() < last_end_time) {
738                         /* this is an index within a track */
739                         
740                         frames_to_cd_frames_string (buf, (*i)->start() - last_start_time, session->frame_rate());
741                         out << "INDEX" << buf << endl;
742                       }
743                 }
744         }
745         
746 }
747
748 void
749 ExportDialog::export_cue_file (Locations::LocationList& locations, const string& path)
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         // sanity check file name first
886         string filepath = file_entry.get_text();
887         struct stat statbuf;
888   
889         if (filepath.empty()) {
890                 // warning dialog
891                 string txt = _("Please enter a valid filename.");
892                 MessageDialog msg (*this, txt, false, MESSAGE_ERROR, BUTTONS_OK, true);
893                 msg.run();
894                 return;
895         }
896         
897         // check if file exists already and warn
898         if (stat (filepath.c_str(), &statbuf) == 0) {
899                 if (S_ISDIR (statbuf.st_mode)) {
900                         string txt = _("Please specify a complete filename for the audio file.");
901                         MessageDialog msg (*this, txt, false, MESSAGE_ERROR, BUTTONS_OK, true);
902                         msg.run();
903                         return;
904                 }
905                 else {
906                         string txt = _("File already exists, do you want to overwrite it?");
907                         MessageDialog msg (*this, txt, false, MESSAGE_QUESTION, BUTTONS_YES_NO, true);
908                         //ArdourMessage msg (this, X_("exportoverwrite"), txt, true, false, Gtk::BUTTONS_YES_NO);
909                         if ((ResponseType) msg.run() == Gtk::RESPONSE_NO) {
910                                 return;
911                         }
912                 }
913         }
914         
915         // directory needs to exist and be writable
916         string dirpath = PBD::dirname (filepath);
917         if (::access (dirpath.c_str(), W_OK) != 0) {
918                 string txt = _("Cannot write file in: ") + dirpath;
919                 MessageDialog msg (*this, txt, false, MESSAGE_ERROR, BUTTONS_OK, true);
920                 msg.run();
921                 return;
922         }
923         
924         if (cue_file_combo.get_active_text () != _("None")) {
925                 do_export_cd_markers (file_entry.get_text(), cue_file_combo.get_active_text ());
926         }
927
928         if (cuefile_only_checkbox.get_active()) {
929                 end_dialog ();
930                 return;
931         }
932
933         ok_button->set_sensitive(false);
934         save_state();
935
936         set_modal (true);
937         
938         spec.path = filepath;
939         spec.progress = 0;
940         spec.running = true;
941         spec.stop = false;
942         spec.port_map.clear();
943         
944         if (channel_count_combo.get_active_text() == _("mono")) {
945                 spec.channels = 1;
946         } else {
947                 spec.channels = 2;
948         }
949
950         spec.format = 0;
951
952         spec.format |= sndfile_header_format_from_string (header_format_combo.get_active_text ());
953         
954         if ((spec.format & SF_FORMAT_WAV) == 0) {
955                 /* RIFF/WAV specifies endianess */
956                 spec.format |= sndfile_endian_format_from_string (endian_format_combo.get_active_text ());
957         }
958
959         spec.format |= sndfile_bitdepth_format_from_string (bitdepth_format_combo.get_active_text ());
960
961         string sr_str = sample_rate_combo.get_active_text();
962         if (sr_str == N_("22.05kHz")) {
963                 spec.sample_rate = 22050;
964         } else if (sr_str == N_("44.1kHz")) {
965                 spec.sample_rate = 44100;
966         } else if (sr_str == N_("48kHz")) {
967                 spec.sample_rate = 48000;
968         } else if (sr_str == N_("88.2kHz")) {
969                 spec.sample_rate = 88200;
970         } else if (sr_str == N_("96kHz")) {
971                 spec.sample_rate = 96000;
972         } else if (sr_str == N_("192kHz")) {
973                 spec.sample_rate = 192000;
974         } else {
975                 spec.sample_rate = session->frame_rate();
976         }
977         
978         string src_str = src_quality_combo.get_active_text();
979         if (src_str == _("fastest")) {
980                 spec.src_quality = SRC_ZERO_ORDER_HOLD;
981         } else if (src_str == _("linear")) {
982                 spec.src_quality = SRC_LINEAR;
983         } else if (src_str == _("better")) {
984                 spec.src_quality = SRC_SINC_FASTEST;
985         } else if (src_str == _("intermediate")) {
986                 spec.src_quality = SRC_SINC_MEDIUM_QUALITY;
987         } else {
988                 spec.src_quality = SRC_SINC_BEST_QUALITY;
989         }
990
991         string dither_str = dither_type_combo.get_active_text();
992         if (dither_str == _("None")) {
993                 spec.dither_type = GDitherNone;
994         } else if (dither_str == _("Rectangular")) {
995                 spec.dither_type = GDitherRect;
996         } else if (dither_str == _("Triangular")) {
997                 spec.dither_type = GDitherTri;
998         } else {
999                 spec.dither_type = GDitherShaped;
1000         } 
1001
1002         if (!audio_region) {
1003
1004                 uint32_t chan=0;
1005                 Port *last_port = 0;
1006                 
1007                 TreeModel::Children rows = master_selector.get_model()->children();
1008                 TreeModel::Children::iterator ri;
1009                 TreeModel::Row row;
1010                 for (ri = rows.begin(); ri != rows.end(); ++ri) {
1011                         row = *ri;
1012                         Port* port = row[exp_cols.port];
1013                         
1014                         if (last_port != port) {
1015                                 chan = 0;
1016                         }
1017                         
1018                         if (row[exp_cols.left]) {
1019                                 spec.port_map[0].push_back (std::pair<Port*,uint32_t>(port, chan));
1020                         } 
1021                         
1022                         if (spec.channels == 2) {
1023                                 if (row[exp_cols.right]) {
1024                                         spec.port_map[1].push_back (std::pair<Port*,uint32_t>(port, chan));
1025                                 }
1026                         }
1027                 }
1028
1029                 chan = 0;
1030
1031                 rows = track_selector.get_model()->children();
1032                 for (ri = rows.begin(); ri != rows.end(); ++ri) {
1033                         row = *ri;
1034                         
1035                         Port* port = row[exp_cols.port];
1036                         
1037                         if (last_port != port) {
1038                                 chan = 0;
1039                         }
1040                         
1041                         if (row[exp_cols.left]) {
1042                                 spec.port_map[0].push_back (std::pair<Port*,uint32_t>(port, chan));
1043                         } 
1044                         
1045                         if (spec.channels == 2) {
1046                                 if (row[exp_cols.right]) {
1047                                         spec.port_map[1].push_back (std::pair<Port*,uint32_t>(port, chan));
1048                                 }
1049                                 
1050                         }
1051                         
1052                         last_port = port;
1053                         ++chan;
1054                 }
1055         }
1056
1057         progress_connection = Glib::signal_timeout().connect (mem_fun(*this, &ExportDialog::progress_timeout), 100);
1058         cancel_label.set_text (_("Stop Export"));
1059
1060         if (!audio_region) {
1061                 if (session->start_audio_export (spec)) {
1062                         goto out;
1063                 }
1064         } else {
1065                 pthread_t thr;
1066                 pthread_create_and_store ("region export", &thr, 0, ExportDialog::_export_region_thread, this);
1067         }
1068
1069         gtk_main_iteration ();
1070         while (spec.running) {
1071                 if (gtk_events_pending()) {
1072                         gtk_main_iteration ();
1073                 } else {
1074                         usleep (10000);
1075                 }
1076         }
1077         
1078   out:
1079         progress_connection.disconnect ();
1080         end_dialog ();
1081 }
1082         
1083
1084 void
1085 ExportDialog::end_dialog ()
1086 {
1087
1088         if (spec.running) {
1089                 spec.stop = true;
1090
1091                 while (spec.running) {
1092                         if (gtk_events_pending()) {
1093                                 gtk_main_iteration ();
1094                         } else {
1095                                 usleep (10000);
1096                         }
1097                 }
1098         }
1099
1100         session->engine().freewheel (false);
1101
1102         hide_all ();
1103
1104         if (file_selector) {
1105                 file_selector->hide_all ();
1106         }
1107
1108         set_modal (false);
1109         ok_button->set_sensitive(true);
1110 }
1111
1112 void
1113 ExportDialog::start_export ()
1114 {
1115         if (session == 0) {
1116                 return;
1117         }
1118
1119         /* If it the filename hasn't been set before, use the
1120            directory above the current session as a default
1121            location for the export.  
1122         */
1123         
1124         if (file_entry.get_text().length() == 0) {
1125                 string dir = session->path();
1126                 string::size_type last_slash;
1127                 
1128                 if ((last_slash = dir.find_last_of ('/')) != string::npos) {
1129                         dir = dir.substr (0, last_slash+1);
1130                 }
1131
1132                 dir = dir + "export.wav";
1133                 
1134                 file_entry.set_text (dir);
1135         }
1136         
1137         progress_bar.set_fraction (0);
1138         cancel_label.set_text (_("Cancel"));
1139
1140         show_all ();
1141
1142         if (session->master_out()) {
1143                 track_scroll.hide ();
1144         } else {
1145                 master_scroll.hide ();
1146                 track_selector_button.hide ();
1147         }
1148 }
1149
1150 void
1151 ExportDialog::header_chosen ()
1152 {
1153         if (sndfile_header_format_from_string (header_format_combo.get_active_text ()) == SF_FORMAT_WAV) {
1154                 endian_format_combo.set_sensitive (false);
1155         } else {
1156                 endian_format_combo.set_sensitive (true);
1157         }
1158 }
1159
1160 void
1161 ExportDialog::bitdepth_chosen ()
1162 {
1163         int format = sndfile_bitdepth_format_from_string (bitdepth_format_combo.get_active_text ());    
1164         switch (format) {
1165         case SF_FORMAT_PCM_24:
1166         case SF_FORMAT_PCM_32:
1167         case SF_FORMAT_FLOAT:
1168                 dither_type_combo.set_sensitive (false);
1169                 break;
1170
1171         default:
1172                 dither_type_combo.set_sensitive (true);
1173                 break;
1174         }
1175 }
1176
1177 void
1178 ExportDialog::cue_file_type_chosen ()
1179 {
1180         if (cue_file_combo.get_active_text () != "None") {
1181                 cuefile_only_checkbox.set_sensitive (true);
1182         } else {
1183                 cuefile_only_checkbox.set_active (false);
1184                 cuefile_only_checkbox.set_sensitive (false);
1185         }
1186 }
1187
1188 void
1189 ExportDialog::sample_rate_chosen ()
1190 {
1191         string sr_str = sample_rate_combo.get_active_text();
1192         jack_nframes_t rate;
1193
1194         if (sr_str == N_("22.05kHz")) {
1195                 rate = 22050;
1196         } else if (sr_str == N_("44.1kHz")) {
1197                 rate = 44100;
1198         } else if (sr_str == N_("48kHz")) {
1199                 rate = 48000;
1200         } else if (sr_str == N_("88.2kHz")) {
1201                 rate = 88200;
1202         } else if (sr_str == N_("96kHz")) {
1203                 rate = 96000;
1204         } else if (sr_str == N_("192kHz")) {
1205                 rate = 192000;
1206         } else {
1207                 rate = session->frame_rate();
1208         }
1209                 
1210         if (rate != session->frame_rate()) {
1211                 src_quality_combo.set_sensitive (true);
1212         } else {
1213                 src_quality_combo.set_sensitive (false);
1214         }
1215 }
1216
1217 void
1218 ExportDialog::channels_chosen ()
1219 {
1220         bool mono;
1221
1222         mono = (channel_count_combo.get_active_text() == _("mono"));
1223
1224         if (mono) {
1225                 track_selector.get_column(2)->set_visible(false);
1226                 track_selector.get_column(1)->set_title(_("Export"));
1227
1228                 if (session->master_out()) {
1229                         master_selector.get_column(2)->set_visible(false);
1230                         master_selector.get_column(1)->set_title(_("Export"));
1231                 }
1232
1233         } else {
1234                 track_selector.get_column(2)->set_visible(true);
1235                 track_selector.get_column(1)->set_title(_("Left"));
1236
1237                 if (session->master_out()) {
1238                         master_selector.get_column(2)->set_visible(true);
1239                         master_selector.get_column(1)->set_title(_("Left"));
1240                 }
1241         }
1242
1243         fill_lists();
1244 }
1245
1246 void
1247 ExportDialog::fill_lists ()
1248 {
1249         track_list->clear();
1250         master_list->clear();
1251         
1252         Session::RouteList routes = session->get_routes ();
1253
1254         for (Session::RouteList::iterator ri = routes.begin(); ri != routes.end(); ++ri) {
1255
1256                 Route* route = (*ri);
1257                 
1258                 if (route->hidden()) {
1259                         continue;
1260                 }
1261
1262                 for (uint32_t i=0; i < route->n_outputs(); ++i) {
1263                         string name;
1264                         if (route->n_outputs() == 1) {
1265                                 name = route->name();
1266                         } else {
1267                                 name = string_compose("%1: out-%2", route->name(), i+1);
1268                         }
1269
1270                         if (route == session->master_out()) {
1271                                 TreeModel::iterator iter = master_list->append();
1272                                 TreeModel::Row row = *iter;
1273                                 row[exp_cols.output] = name;
1274                                 row[exp_cols.left] = false;
1275                                 row[exp_cols.right] = false;
1276                                 row[exp_cols.port] = route->output (i);
1277                         } else {
1278                                 TreeModel::iterator iter = track_list->append();
1279                                 TreeModel::Row row = *iter;
1280                                 row[exp_cols.output] = name;
1281                                 row[exp_cols.left] = false;
1282                                 row[exp_cols.right] = false;
1283                                 row[exp_cols.port] = route->output (i);
1284                         }
1285                 }
1286         }
1287 }
1288
1289 gint
1290 ExportDialog::window_closed (GdkEventAny *ignored)
1291 {
1292         end_dialog ();
1293         return TRUE;
1294 }
1295 void
1296 ExportDialog::initiate_browse ()
1297 {
1298         if (file_selector == 0) {
1299                 file_selector = new FileSelection;
1300                 file_selector->set_modal (true);
1301
1302                 file_selector->get_cancel_button()->signal_clicked().connect (bind (mem_fun(*this, &ExportDialog::finish_browse), -1));
1303                 file_selector->get_ok_button()->signal_clicked().connect (bind (mem_fun(*this, &ExportDialog::finish_browse), 1));
1304         }
1305         file_selector->set_filename (file_entry.get_text());
1306         file_selector->show_all ();
1307 }
1308
1309 void
1310 ExportDialog::finish_browse (int status)
1311 {
1312         if (file_selector) {
1313                 if (status > 0) {
1314                         string result = file_selector->get_filename();
1315                         
1316                         if (result.length()) {
1317                                 file_entry.set_text (result);
1318                         }
1319                 }
1320                 file_selector->hide_all();
1321         }
1322 }
1323
1324 void
1325 ExportDialog::track_selector_button_click ()
1326 {
1327         if (track_scroll.is_visible ()) {
1328                 track_scroll.hide ();
1329         } else {
1330                 track_scroll.show_all ();
1331         }
1332 }