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