move utility functions into a dedicated namespace
[ardour.git] / gtk2_ardour / export_video_dialog.cc
1 /*
2     Copyright (C) 2010 Paul Davis
3     Author: Robin Gareus <robin@gareus.org>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20 #include <cstdio>
21 #include <string>
22 #include <sstream>
23 #include <iomanip>
24
25 #include <unistd.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <fcntl.h>
29
30 #include <sigc++/bind.h>
31
32 #include <glib/gstdio.h>
33
34 #include "pbd/error.h"
35 #include "pbd/convert.h"
36 #include "gtkmm2ext/utils.h"
37 #include "ardour/session_directory.h"
38 #include "ardour/profile.h"
39 #include "ardour/template_utils.h"
40 #include "ardour/session.h"
41 #include "ardour_ui.h"
42 #include "gui_thread.h"
43
44 #include "ardour/export_handler.h"
45 #include "ardour/export_status.h"
46 #include "ardour/export_timespan.h"
47 #include "ardour/export_channel_configuration.h"
48 #include "ardour/export_format_specification.h"
49 #include "ardour/export_filename.h"
50 #include "ardour/route.h"
51 #include "ardour/session_metadata.h"
52 #include "ardour/broadcast_info.h"
53
54 #include "opts.h"
55 #include "export_video_dialog.h"
56 #include "utils_videotl.h"
57 #include "i18n.h"
58
59 using namespace Gtk;
60 using namespace std;
61 using namespace PBD;
62 using namespace ARDOUR;
63 using namespace VideoUtils;
64
65 ExportVideoDialog::ExportVideoDialog (Session* s, TimeSelection &tme, bool range)
66         : ArdourDialog (_("Export Video File "))
67         , export_range (tme)
68         , outfn_path_label (_("File:"), Gtk::ALIGN_LEFT)
69         , outfn_browse_button (_("Browse"))
70         , invid_path_label (_("Video:"), Gtk::ALIGN_LEFT)
71         , invid_browse_button (_("Browse"))
72         , transcode_button (_("Export"))
73         , abort_button (_("Abort"))
74         , scale_checkbox (_("Scale Video (W x H):"))
75         , width_adjustment (768, 128, 1920, 1, 16, 0)
76         , width_spinner (width_adjustment)
77         , height_adjustment (576, 128, 1920, 1, 16, 0)
78         , height_spinner (height_adjustment)
79         , aspect_checkbox (_("Set Aspect Ratio:"))
80         , normalize_checkbox (_("Normalize Audio"))
81         , twopass_checkbox (_("2 Pass Encoding"))
82         , optimizations_checkbox (_("Codec Optimizations:"))
83         , optimizations_label ("-")
84         , deinterlace_checkbox (_("Deinterlace"))
85         , bframes_checkbox (_("Use [2] B-frames (MPEG 2 or 4 only)"))
86         , fps_checkbox (_("Override FPS (Default is to retain FPS from the input video file):"))
87         , meta_checkbox (_("Include Session Metadata"))
88 #if 1 /* tentative debug mode */
89         , debug_checkbox (_("Debug Mode: Print ffmpeg command and output to stdout."))
90 #endif
91 {
92         set_session (s);
93
94         set_name ("ExportVideoDialog");
95         set_modal (true);
96         set_skip_taskbar_hint (true);
97         set_resizable (false);
98
99         Gtk::Label* l;
100         vbox = manage (new VBox);
101         VBox* options_box = manage (new VBox);
102         HBox* path_hbox;
103
104         /* check if ffmpeg can be found */
105         transcoder = new TranscodeFfmpeg("");
106         if (!transcoder->ffexec_ok()) {
107                 l = manage (new Label (_("No ffprobe or ffmpeg executables could be found on this system. Video Export is not possible until you install those tools. See the Log window for more information."), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
108                 l->set_line_wrap();
109                 vbox->pack_start (*l, false, false, 8);
110                 get_vbox()->pack_start (*vbox, false, false);
111                 add_button (Stock::OK, RESPONSE_CANCEL);
112                 show_all_children ();
113                 return;
114         }
115         delete transcoder; transcoder = 0;
116
117         l = manage (new Label (_("<b>Output:</b>"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
118         l->set_use_markup ();
119         vbox->pack_start (*l, false, false, 4);
120
121         path_hbox = manage (new HBox);
122         path_hbox->pack_start (outfn_path_label, false, false, 3);
123         path_hbox->pack_start (outfn_path_entry, true, true, 3);
124         path_hbox->pack_start (outfn_browse_button, false, false, 3);
125         vbox->pack_start (*path_hbox, false, false, 2);
126
127         l = manage (new Label (_("<b>Input:</b>"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
128         l->set_use_markup ();
129         vbox->pack_start (*l, false, false, 4);
130
131         path_hbox = manage (new HBox);
132         path_hbox->pack_start (invid_path_label, false, false, 3);
133         path_hbox->pack_start (invid_path_entry, true, true, 3);
134         path_hbox->pack_start (invid_browse_button, false, false, 3);
135         vbox->pack_start (*path_hbox, false, false, 2);
136
137         path_hbox = manage (new HBox);
138         l = manage (new Label (_("Audio:"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
139         path_hbox->pack_start (*l, false, false, 3);
140         l = manage (new Label (_("Master Bus"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
141         path_hbox->pack_start (*l, false, false, 2);
142         vbox->pack_start (*path_hbox, false, false, 2);
143
144         insnd_combo.set_name ("PaddedButton");
145         insnd_combo.append_text (string_compose (_("from the %1 session's start to the session's end"), PROGRAM_NAME));
146
147         frameoffset_t av_offset = ARDOUR_UI::instance()->video_timeline->get_offset();
148         if (av_offset < 0 ) {
149                 insnd_combo.append_text (_("from 00:00:00:00 to the video's end"));
150         } else {
151                 insnd_combo.append_text (_("from the video's start to the video's end"));
152         }
153         if (!export_range.empty()) {
154                 insnd_combo.append_text (_("Selected range"));  // TODO show export_range.start() -> export_range.end_frame()
155         }
156         if (range) {
157                 insnd_combo.set_active(2);
158         } else {
159                 insnd_combo.set_active(0);
160         }
161
162         outfn_path_entry.set_width_chars(38);
163         outfn_path_entry.set_text (_session->session_directory().export_path() + G_DIR_SEPARATOR +"export.avi");
164
165         XMLNode* node = _session->extra_xml (X_("Videotimeline"));
166         if (node) {
167                 bool filenameset = false;
168                 if (node->property(X_("OriginalVideoFile"))) {
169                         std::string filename = node->property(X_("OriginalVideoFile"))->value();
170                         if (Glib::file_test(filename, Glib::FILE_TEST_EXISTS)) {
171                                 invid_path_entry.set_text (filename);
172                                 filenameset = true;
173                         }
174                 }
175                 if (!filenameset
176                                 && node->property(X_("Filename"))
177                                 && node->property(X_("LocalFile"))
178                                 && node->property(X_("LocalFile"))->value() == X_("1")
179                                 ) {
180                         std::string filename = node->property(X_("Filename"))->value();
181                         if (filename.at(0) != G_DIR_SEPARATOR) {
182                                 filename = Glib::build_filename (_session->session_directory().video_path(), filename);
183                         }
184                         if (Glib::file_test(filename, Glib::FILE_TEST_EXISTS)) {
185                                 invid_path_entry.set_text (filename);
186                                 filenameset = true;
187                         }
188                 }
189                 if (!filenameset) {
190                         invid_path_entry.set_text (X_(""));
191                 }
192         }
193
194         l = manage (new Label (_("<b>Settings:</b>"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
195         l->set_use_markup ();
196         options_box->pack_start (*l, false, true, 4);
197
198         Table* t = manage (new Table (4, 12));
199         t->set_spacings (4);
200         int ty = 0;
201         options_box->pack_start (*t, true, true, 4);
202         l = manage (new Label (_("Range:"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
203         t->attach (*l, 0, 1, ty, ty+1);
204         t->attach (insnd_combo, 1, 4, ty, ty+1); ty++;
205         l = manage (new Label (_("Preset:"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
206         t->attach (*l, 0, 1, ty, ty+1);
207         t->attach (preset_combo, 1, 4, ty, ty+1); ty++;
208         l = manage (new Label (_("Video Codec:"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
209         t->attach (*l, 0, 1, ty, ty+1);
210         t->attach (video_codec_combo, 1, 2, ty, ty+1);
211         l = manage (new Label (_("Video KBit/s:"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
212         t->attach (*l, 2, 3, ty, ty+1);
213         t->attach (video_bitrate_combo, 3, 4, ty, ty+1); ty++;
214         l = manage (new Label (_("Audio Codec:"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
215         t->attach (*l, 0, 1, ty, ty+1);
216         t->attach (audio_codec_combo, 1, 2, ty, ty+1);
217         l = manage (new Label (_("Audio KBit/s:"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
218         t->attach (*l, 2, 3, ty, ty+1);
219         t->attach (audio_bitrate_combo, 3, 4, ty, ty+1); ty++;
220         l = manage (new Label (_("Audio Samplerate:"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
221         t->attach (*l, 0, 1, ty, ty+1);
222         t->attach (audio_samplerate_combo, 1, 2, ty, ty+1);
223         t->attach (normalize_checkbox, 2, 4, ty, ty+1); ty++;
224         t->attach (scale_checkbox, 0, 2, ty, ty+1);
225         t->attach (width_spinner, 2, 3, ty, ty+1);
226         t->attach (height_spinner, 3, 4, ty, ty+1); ty++;
227         t->attach (fps_checkbox, 0, 3, ty, ty+1);
228         t->attach (fps_combo, 3, 4, ty, ty+1); ty++;
229         t->attach (twopass_checkbox, 0, 2, ty, ty+1);
230         t->attach (aspect_checkbox, 2, 3, ty, ty+1);
231         t->attach (aspect_combo, 3, 4, ty, ty+1); ty++;
232         t->attach (bframes_checkbox, 0, 2, ty, ty+1);
233         t->attach (deinterlace_checkbox, 2, 4, ty, ty+1); ty++;
234         t->attach (meta_checkbox, 2, 4, ty, ty+1); ty++;
235         t->attach (optimizations_checkbox, 0, 1, ty, ty+1);
236         t->attach (optimizations_label, 1, 4, ty, ty+1); ty++;
237 #if 1 /* tentative debug mode */
238         t->attach (debug_checkbox, 0, 4, ty, ty+1); ty++;
239 #endif
240
241         preset_combo.set_name ("PaddedButton");
242         preset_combo.append_text("none");
243         preset_combo.append_text("dvd-mp2");
244         preset_combo.append_text("dvd-NTSC");
245         preset_combo.append_text("dvd-PAL");
246         preset_combo.append_text("flv");
247         preset_combo.append_text("mpeg4");
248         preset_combo.append_text("ogg");
249         preset_combo.append_text("you-tube");
250         preset_combo.set_active(0);
251
252         audio_codec_combo.set_name ("PaddedButton");
253         audio_codec_combo.append_text("ac3");
254         audio_codec_combo.append_text("aac");
255         audio_codec_combo.append_text("libmp3lame");
256         audio_codec_combo.append_text("libvorbis");
257         audio_codec_combo.append_text("mp2");
258         audio_codec_combo.append_text("pcm_s16le");
259         audio_codec_combo.set_active(2);
260
261         video_codec_combo.set_name ("PaddedButton");
262         video_codec_combo.append_text("flv");
263         video_codec_combo.append_text("libtheora");
264         video_codec_combo.append_text("mjpeg");
265         video_codec_combo.append_text("mpeg2video");
266         video_codec_combo.append_text("mpeg4");
267         video_codec_combo.append_text("h264");
268         video_codec_combo.append_text("vpx (webm)");
269         video_codec_combo.append_text("copy");
270         video_codec_combo.set_active(4);
271
272         audio_bitrate_combo.set_name ("PaddedButton");
273         audio_bitrate_combo.append_text("64k");
274         audio_bitrate_combo.append_text("128k");
275         audio_bitrate_combo.append_text("192k");
276         audio_bitrate_combo.append_text("256k");
277         audio_bitrate_combo.append_text("320k");
278         audio_bitrate_combo.set_active(2);
279
280         audio_samplerate_combo.set_name ("PaddedButton");
281         audio_samplerate_combo.append_text("22050");
282         audio_samplerate_combo.append_text("44100");
283         audio_samplerate_combo.append_text("48000");
284         audio_samplerate_combo.set_active(2);
285
286         video_bitrate_combo.set_name ("PaddedButton");
287         video_bitrate_combo.append_text("200k");
288         video_bitrate_combo.append_text("800k");
289         video_bitrate_combo.append_text("2000k");
290         video_bitrate_combo.append_text("5000k");
291         video_bitrate_combo.append_text("8000k");
292         video_bitrate_combo.append_text("retain");
293         video_bitrate_combo.set_active(3);
294
295         fps_combo.set_name ("PaddedButton");
296         fps_combo.append_text("23.976");
297         fps_combo.append_text("24");
298         fps_combo.append_text("24.976");
299         fps_combo.append_text("25");
300         fps_combo.append_text("29.97");
301         fps_combo.append_text("30");
302         fps_combo.append_text("59.94");
303         fps_combo.append_text("60");
304         float tcfps = _session->timecode_frames_per_second();
305         if      (fabs(tcfps - 23.976) < 0.01) { fps_combo.set_active(0); }
306         else if (fabs(tcfps - 24.0  ) < 0.01) { fps_combo.set_active(1); }
307         else if (fabs(tcfps - 24.976) < 0.01) { fps_combo.set_active(2); }
308         else if (fabs(tcfps - 25.0  ) < 0.01) { fps_combo.set_active(3); }
309         else if (fabs(tcfps - 29.97 ) < 0.01) { fps_combo.set_active(4); }
310         else if (fabs(tcfps - 30.0  ) < 0.01) { fps_combo.set_active(5); }
311         else if (fabs(tcfps - 59.94 ) < 0.01) { fps_combo.set_active(6); }
312         else if (fabs(tcfps - 60.0  ) < 0.01) { fps_combo.set_active(7); }
313         else { fps_combo.set_active(5); }
314
315         aspect_combo.set_name ("PaddedButton");
316         aspect_combo.append_text("4:3");
317         aspect_combo.append_text("16:9");
318         aspect_combo.set_active(1);
319
320         optimizations_checkbox.set_sensitive(false);
321         scale_checkbox_toggled();
322         aspect_checkbox_toggled();
323         fps_checkbox_toggled();
324         video_codec_combo_changed();
325
326         vbox->pack_start (*options_box, false, true, 4);
327         get_vbox()->set_spacing (4);
328         get_vbox()->pack_start (*vbox, false, false);
329
330         progress_box = manage (new VBox);
331         progress_box->pack_start (pbar, false, false);
332         progress_box->pack_start (abort_button, false, false);
333         get_vbox()->pack_start (*progress_box, false, false);
334
335         scale_checkbox.signal_toggled().connect (sigc::mem_fun (*this, &ExportVideoDialog::scale_checkbox_toggled));
336         aspect_checkbox.signal_toggled().connect (sigc::mem_fun (*this, &ExportVideoDialog::aspect_checkbox_toggled));
337         fps_checkbox.signal_toggled().connect (sigc::mem_fun (*this, &ExportVideoDialog::fps_checkbox_toggled));
338         preset_combo.signal_changed().connect (sigc::mem_fun (*this, &ExportVideoDialog::preset_combo_changed));
339         video_codec_combo.signal_changed().connect (sigc::mem_fun (*this, &ExportVideoDialog::video_codec_combo_changed));
340         outfn_browse_button.signal_clicked().connect (sigc::mem_fun (*this, &ExportVideoDialog::open_outfn_dialog));
341         invid_browse_button.signal_clicked().connect (sigc::mem_fun (*this, &ExportVideoDialog::open_invid_dialog));
342         transcode_button.signal_clicked().connect (sigc::mem_fun (*this, &ExportVideoDialog::launch_export));
343         abort_button.signal_clicked().connect (sigc::mem_fun (*this, &ExportVideoDialog::abort_clicked));
344
345         cancel_button = add_button (Stock::CANCEL, RESPONSE_CANCEL);
346         get_action_area()->pack_start (transcode_button, false, false);
347         show_all_children ();
348         progress_box->hide();
349 }
350
351 ExportVideoDialog::~ExportVideoDialog ()
352 {
353         if (transcoder) { delete transcoder; transcoder = 0;}
354 }
355
356 void
357 ExportVideoDialog::on_show ()
358 {
359         Dialog::on_show ();
360 }
361
362 void
363 ExportVideoDialog::abort_clicked ()
364 {
365         aborted = true;
366         if (transcoder) {
367                 transcoder->cancel();
368         }
369 }
370
371 void
372 ExportVideoDialog::update_progress (framecnt_t c, framecnt_t a)
373 {
374         if (a == 0 || c > a) {
375                 pbar.set_pulse_step(.1);
376                 pbar.pulse();
377         } else {
378                 double progress = (double)c / (double) a;
379                 progress = progress / ((twopass ? 2.0 : 1.0) + (normalize ? 2.0 : 1.0));
380                 if (normalize && twopass) progress += (firstpass ? .5 : .75);
381                 else if (normalize) progress += 2.0/3.0;
382                 else if (twopass) progress += (firstpass ? 1.0/3.0 : 2.0/3.0);
383                 else progress += .5;
384
385                 pbar.set_fraction (progress);
386         }
387 }
388
389
390 gint
391 ExportVideoDialog::audio_progress_display ()
392 {
393         std::string status_text;
394         double progress = 0.0;
395                 if (status->normalizing) {
396                         pbar.set_text (_("Normalizing audio"));
397                         progress = ((float) status->current_normalize_cycle) / status->total_normalize_cycles;
398                         progress = progress / (twopass ? 4.0 : 3.0) + (twopass ? .25 : 1.0/3.0);
399                 } else {
400                         pbar.set_text (_("Exporting audio"));
401                         progress = ((float) status->processed_frames_current_timespan) / status->total_frames_current_timespan;
402                         progress = progress / ((twopass ? 2.0 : 1.0) + (normalize ? 2.0 : 1.0));
403                 }
404                 if (progress < previous_progress) {
405                         // Work around gtk bug
406                         pbar.hide();
407                         pbar.show();
408                 }
409                 previous_progress = progress;
410                 pbar.set_fraction (progress);
411         return TRUE;
412 }
413
414 void
415 ExportVideoDialog::finished ()
416 {
417         if (aborted) {
418                 ::g_unlink(outfn_path_entry.get_text().c_str());
419                 ::g_unlink (insnd.c_str());
420                 Gtk::Dialog::response(RESPONSE_CANCEL);
421         } else if (twopass && firstpass) {
422                 firstpass = false;
423                 if (transcoder) { delete transcoder; transcoder = 0;}
424                 encode_pass(2);
425         } else {
426                 if (twopass_checkbox.get_active()) {
427                         std::string outfn = outfn_path_entry.get_text();
428                         std::string p2log = Glib::path_get_dirname (outfn) + G_DIR_SEPARATOR + "ffmpeg2pass";
429                         ::g_unlink (p2log.c_str());
430                 }
431                 ::g_unlink (insnd.c_str());
432                 Gtk::Dialog::response(RESPONSE_ACCEPT);
433         }
434 }
435
436 void
437 ExportVideoDialog::launch_export ()
438 {
439         std::string outfn = outfn_path_entry.get_text();
440         if (!confirm_video_outfn(outfn)) { return; }
441
442         vbox->hide();
443         cancel_button->hide();
444         transcode_button.hide();
445         pbar.set_size_request(300,-1);
446         pbar.set_text(_("Exporting Audio..."));
447         progress_box->show();
448         aborted = false;
449         twopass = twopass_checkbox.get_active();
450         firstpass = true;
451         normalize = normalize_checkbox.get_active();
452
453         /* export audio track */
454         ExportTimespanPtr tsp = _session->get_export_handler()->add_timespan();
455         boost::shared_ptr<ExportChannelConfiguration> ccp = _session->get_export_handler()->add_channel_config();
456         boost::shared_ptr<ARDOUR::ExportFilename> fnp = _session->get_export_handler()->add_filename();
457         boost::shared_ptr<AudioGrapher::BroadcastInfo> b;
458         XMLTree tree;
459         std::string vtl_samplerate = audio_samplerate_combo.get_active_text();
460         std::string vtl_normalize = normalize ? "true" : "false";
461         tree.read_buffer(std::string(
462 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
463 "<ExportFormatSpecification name=\"VTL-WAV-16\" id=\"3094591e-ccb9-4385-a93f-c9955ffeb1f0\">"
464 "  <Encoding id=\"F_WAV\" type=\"T_Sndfile\" extension=\"wav\" name=\"WAV\" has-sample-format=\"true\" channel-limit=\"256\"/>"
465 "  <SampleRate rate=\""+ vtl_samplerate +"\"/>"
466 "  <SRCQuality quality=\"SRC_SincBest\"/>"
467 "  <EncodingOptions>"
468 "    <Option name=\"sample-format\" value=\"SF_16\"/>"
469 "    <Option name=\"dithering\" value=\"D_None\"/>"
470 "    <Option name=\"tag-metadata\" value=\"true\"/>"
471 "    <Option name=\"tag-support\" value=\"false\"/>"
472 "    <Option name=\"broadcast-info\" value=\"false\"/>"
473 "  </EncodingOptions>"
474 "  <Processing>"
475 "    <Normalize enabled=\""+ vtl_normalize +"\" target=\"0\"/>"
476 "    <Silence>"
477 "      <Start>"
478 "        <Trim enabled=\"false\"/>"
479 "        <Add enabled=\"false\">"
480 "          <Duration format=\"Timecode\" hours=\"0\" minutes=\"0\" seconds=\"0\" frames=\"0\"/>"
481 "        </Add>"
482 "      </Start>"
483 "      <End>"
484 "        <Trim enabled=\"false\"/>"
485 "        <Add enabled=\"false\">"
486 "          <Duration format=\"Timecode\" hours=\"0\" minutes=\"0\" seconds=\"0\" frames=\"0\"/>"
487 "        </Add>"
488 "      </End>"
489 "    </Silence>"
490 "  </Processing>"
491 "</ExportFormatSpecification>"
492 ));
493         boost::shared_ptr<ExportFormatSpecification> fmp = _session->get_export_handler()->add_format(*tree.root());
494
495         /* set up range */
496         framepos_t start, end;
497         start = end = 0;
498         if (insnd_combo.get_active_row_number() == 1) {
499                 transcoder = new TranscodeFfmpeg(invid_path_entry.get_text());
500                 if (transcoder->probe_ok() && transcoder->get_fps() > 0) {
501                         end = transcoder->get_duration() * _session->nominal_frame_rate() / transcoder->get_fps();
502                 } else {
503                         warning << _("Export Video: Cannot query duration of video-file, using duration from timeline instead.") << endmsg;
504                         end = ARDOUR_UI::instance()->video_timeline->get_duration();
505                 }
506                 if (transcoder) {delete transcoder; transcoder = 0;}
507
508                 frameoffset_t av_offset = ARDOUR_UI::instance()->video_timeline->get_offset();
509 #if 0 /* DEBUG */
510                 printf("audio-range -- AV offset: %lld\n", av_offset);
511 #endif
512                 if (av_offset > 0) {
513                         start = av_offset;
514                 }
515                 end += av_offset;
516         }
517         else if (insnd_combo.get_active_row_number() == 2) {
518                 start = ARDOUR_UI::instance()->video_timeline->quantify_frames_to_apv(export_range.start());
519                 end   = ARDOUR_UI::instance()->video_timeline->quantify_frames_to_apv(export_range.end_frame());
520         }
521         if (end <= 0) {
522                 start = _session->current_start_frame();
523                 end   = _session->current_end_frame();
524         }
525 #if 0 /* DEBUG */
526         printf("audio export-range %lld -> %lld\n", start, end);
527 #endif
528
529         const frameoffset_t vstart = ARDOUR_UI::instance()->video_timeline->get_offset();
530         const frameoffset_t vend   = vstart + ARDOUR_UI::instance()->video_timeline->get_duration();
531
532         if ( (start >= end) || (end < vstart) || (start > vend)) {
533                 warning << _("Export Video: export-range does not include video.") << endmsg;
534                 Gtk::Dialog::response(RESPONSE_CANCEL);
535                 return;
536         }
537
538         tsp->set_range (start, end);
539         tsp->set_name ("mysession");
540         tsp->set_range_id ("session");
541
542         /* add master outs as default */
543         IO* master_out = _session->master_out()->output().get();
544         if (!master_out) {
545                 warning << _("Export Video: No Master Out Ports to Connect for Audio Export") << endmsg;
546                 Gtk::Dialog::response(RESPONSE_CANCEL);
547                 return;
548         }
549         for (uint32_t n = 0; n < master_out->n_ports().n_audio(); ++n) {
550                 PortExportChannel * channel = new PortExportChannel ();
551                 channel->add_port (master_out->audio (n));
552                 ExportChannelPtr chan_ptr (channel);
553                 ccp->register_channel (chan_ptr);
554         }
555
556         /* outfile */
557         fnp->set_timespan(tsp);
558         fnp->set_label("vtl");
559         fnp->include_label = true;
560         insnd = fnp->get_path(fmp);
561
562         /* do sound export */
563         _session->get_export_handler()->add_export_config (tsp, ccp, fmp, fnp, b);
564         _session->get_export_handler()->do_export();
565         status = _session->get_export_status ();
566
567         audio_progress_connection = Glib::signal_timeout().connect (sigc::mem_fun(*this, &ExportVideoDialog::audio_progress_display), 100);
568         previous_progress = 0.0;
569         while (status->running) {
570                 if (aborted) { status->abort(); }
571                 if (gtk_events_pending()) {
572                         gtk_main_iteration ();
573                 } else {
574                         Glib::usleep (10000);
575                 }
576         }
577         audio_progress_connection.disconnect();
578         status->finish ();
579         if (status->aborted()) {
580                 ::g_unlink (insnd.c_str());
581                 Gtk::Dialog::response(RESPONSE_CANCEL);
582                 return;
583         }
584         pbar.set_text (_("Encoding Video..."));
585         encode_pass(1);
586 }
587
588 void
589 ExportVideoDialog::encode_pass (int pass)
590 {
591         std::string outfn = outfn_path_entry.get_text();
592         std::string invid = invid_path_entry.get_text();
593
594         transcoder = new TranscodeFfmpeg(invid);
595         if (!transcoder->ffexec_ok()) {
596                 /* ffmpeg binary was not found. TranscodeFfmpeg prints a warning */
597                 ::g_unlink (insnd.c_str());
598                 Gtk::Dialog::response(RESPONSE_CANCEL);
599                 return;
600         }
601         if (!transcoder->probe_ok()) {
602                 /* video input file can not be read */
603                 warning << _("Export Video: Video input file cannot be read.") << endmsg;
604           ::g_unlink (insnd.c_str());
605           Gtk::Dialog::response(RESPONSE_CANCEL);
606           return;
607         }
608
609         std::string preset = preset_combo.get_active_text();
610         TranscodeFfmpeg::FFSettings ffs ; /* = transcoder->default_encoder_settings(); */
611         ffs.clear();
612
613         if (fps_checkbox.get_active()) {
614           ffs["-r"] = fps_combo.get_active_text();
615         }
616
617         if (scale_checkbox.get_active()) {
618                 ffs["-s"] = string_compose("%1x%2", width_spinner.get_value(), height_spinner.get_value());
619         }
620         ffs["-vcodec"] = video_codec_combo.get_active_text();
621         ffs["-acodec"] = audio_codec_combo.get_active_text();
622
623         if (video_bitrate_combo.get_active_text() == "retain" ) {
624                 ffs["-qscale"]  = "0";
625         } else {
626                 ffs["-b:v"]  = video_bitrate_combo.get_active_text();
627         }
628         ffs["-b:a"] = audio_bitrate_combo.get_active_text();
629
630         if (audio_codec_combo.get_active_text() == "aac" ) {
631                 ffs["-strict"] = "-2";
632         }
633
634         if (video_codec_combo.get_active_text() == "h264" ) {
635                 ffs["-vcodec"] = "libx264";
636         }
637         else if (video_codec_combo.get_active_text() == "vpx (webm)" ) {
638                 ffs["-vcodec"] = "libvpx";
639                 ffs["-g"] = "120";
640                 ffs["-qmin"] = "11";
641                 ffs["-qmax"] = "51";
642         }
643
644         if (optimizations_checkbox.get_active()) {
645           if (video_codec_combo.get_active_text() == "mpeg2video") {
646                         ffs["-mbd"] = "rd";
647                         ffs["-trellis"] = "2";
648                         ffs["-cmp"] = "2";
649                         ffs["-subcmp"] = "2";
650                 }
651                 else if (video_codec_combo.get_active_text() == "mpeg4") {
652                         ffs["-mbd"] = "rd";
653                         ffs["-flags"] = "+mv4+aic";
654                         ffs["-trellis"] = "2";
655                         ffs["-cmp"] = "2";
656                         ffs["-subcmp"] = "2";
657                         ffs["-g"] = "300";
658                 }
659                 else if (video_codec_combo.get_active_text() == "flv") {
660                         ffs["-mbd"] = "2";
661                         ffs["-cmp"] = "2";
662                         ffs["-subcmp"] = "2";
663                         ffs["-trellis"] = "2";
664                         ffs["-flags"] = "+aic+mv0+mv4";
665                         ffs["-g"] = "160";
666                 }
667         }
668
669         if (bframes_checkbox.get_active() && (
670                    video_codec_combo.get_active_text() == "mpeg2video"
671                 || video_codec_combo.get_active_text() == "mpeg4"
672                 )) {
673                 ffs["-bf"] = "2";
674         }
675
676         if (preset == "dvd-PAL") {
677                 ffs.clear(); /* ignore all prev settings */
678                 ffs["-target"] = "pal-dvd";
679                 ffs["-aspect"] = "4:3"; /* required for DVD - may be overridden below */
680         }
681         else if (preset == "dvd-NTSC") {
682                 ffs.clear(); /* ignore all prev settings */
683                 ffs["-target"] = "ntsc-dvd";
684                 ffs["-aspect"] = "4:3"; /* required for DVD - may be overridden below */
685         }
686
687         if (aspect_checkbox.get_active()) {
688                 ffs["-aspect"] = aspect_combo.get_active_text();
689         }
690         if (deinterlace_checkbox.get_active()) {
691                 ffs["-deinterlace"] = "-y"; // we use '-y' as dummy parameter for non key/value options
692         }
693
694         bool map = true;
695         if (pass == 1 && twopass) {
696                 pbar.set_text (_("Encoding Video.. Pass 1/2"));
697                 map = false;
698                 ffs["-pass"] = "1";
699                 ffs["-an"] = "-y";
700                 ffs["-passlogfile"] =  Glib::path_get_dirname (outfn) + G_DIR_SEPARATOR + "ffmpeg2pass";
701                 ffs["-f"] = get_file_extension(invid).empty()?"mov":get_file_extension(invid);
702 #ifdef PLATFORM_WINDOWS
703                 outfn = "NUL";
704 #else
705                 outfn = "/dev/null";
706 #endif
707         } else if (pass == 2) {
708                 pbar.set_text (_("Encoding Video.. Pass 2/2"));
709                 ffs["-pass"] = "2";
710                 ffs["-passlogfile"] =  Glib::path_get_dirname (outfn) + G_DIR_SEPARATOR + "ffmpeg2pass";
711         }
712
713         frameoffset_t av_offset = ARDOUR_UI::instance()->video_timeline->get_offset();
714         double duration_s  = 0;
715
716         if (insnd_combo.get_active_row_number() == 0) {
717                 /* session start to session end */
718                 framecnt_t duration_f = _session->current_end_frame() - _session->current_start_frame();
719                 duration_s = (double)duration_f / (double)_session->nominal_frame_rate();
720         } else if (insnd_combo.get_active_row_number() == 2) {
721                 /* selected range */
722                 duration_s = export_range.length() / (double)_session->nominal_frame_rate();
723         } else {
724                 /* video start to end */
725                 framecnt_t duration_f = ARDOUR_UI::instance()->video_timeline->get_duration();
726                 if (av_offset < 0 ) {
727                         duration_f += av_offset;
728                 }
729                 duration_s = (double)duration_f / (double)_session->nominal_frame_rate();
730         }
731
732         std::ostringstream osstream; osstream << duration_s;
733         ffs["-t"] = osstream.str();
734         if (fps_checkbox.get_active()) {
735                 transcoder->set_duration(duration_s * atof(fps_combo.get_active_text()));
736         } else {
737                 transcoder->set_duration(duration_s * transcoder->get_fps());
738         }
739
740         if (insnd_combo.get_active_row_number() == 0 || insnd_combo.get_active_row_number() == 2) {
741                 framepos_t start, snend;
742                 const frameoffset_t vid_duration = ARDOUR_UI::instance()->video_timeline->get_duration();
743                 if (insnd_combo.get_active_row_number() == 0) {
744                         start = _session->current_start_frame();
745                         snend = _session->current_end_frame();
746                 } else {
747                         start = export_range.start();
748                         snend = export_range.end_frame();
749                 }
750
751 #if 0 /* DEBUG */
752                 printf("AV offset: %lld Vid-len: %lld Vid-end: %lld || start:%lld || end:%lld\n",
753                                 av_offset, vid_duration, av_offset+vid_duration, start, snend); // XXX
754 #endif
755
756                 if (av_offset > start && av_offset + vid_duration < snend) {
757                         transcoder->set_leadinout((av_offset - start) / (double)_session->nominal_frame_rate(),
758                                 (snend - (av_offset + vid_duration)) / (double)_session->nominal_frame_rate());
759                 } else if (av_offset > start) {
760                         transcoder->set_leadinout((av_offset - start) / (double)_session->nominal_frame_rate(), 0);
761                 } else if (av_offset + vid_duration < snend) {
762                         transcoder->set_leadinout(0, (snend - (av_offset + vid_duration)) / (double)_session->nominal_frame_rate());
763                         transcoder->set_avoffset((av_offset - start) / (double)_session->nominal_frame_rate());
764                 }
765 #if 0
766                 else if (start > av_offset) {
767                         std::ostringstream osstream; osstream << ((start - av_offset) / (double)_session->nominal_frame_rate());
768                         ffs["-ss"] = osstream.str();
769                 }
770 #endif
771                 else {
772                         transcoder->set_avoffset((av_offset - start) / (double)_session->nominal_frame_rate());
773                 }
774
775         } else if (av_offset < 0) {
776                 /* from 00:00:00:00 to video-end */
777                 transcoder->set_avoffset(av_offset / (double)_session->nominal_frame_rate());
778         }
779
780         TranscodeFfmpeg::FFSettings meta = transcoder->default_meta_data();
781         if (meta_checkbox.get_active()) {
782                 ARDOUR::SessionMetadata * session_data = ARDOUR::SessionMetadata::Metadata();
783                 if (session_data->year() > 0 ) {
784                         std::ostringstream osstream; osstream << session_data->year();
785                         meta["year"] = osstream.str();
786                 }
787                 if (session_data->track_number() > 0 ) {
788                         std::ostringstream osstream; osstream << session_data->track_number();
789                         meta["track"] = osstream.str();
790                 }
791                 if (session_data->disc_number() > 0 ) {
792                         std::ostringstream osstream; osstream << session_data->disc_number();
793                         meta["disc"] = osstream.str();
794                 }
795                 if (!session_data->title().empty())     {meta["title"] = session_data->title();}
796                 if (!session_data->artist().empty())    {meta["author"] = session_data->artist();}
797                 if (!session_data->album_artist().empty()) {meta["album_artist"] = session_data->album_artist();}
798                 if (!session_data->album().empty())     {meta["album"] = session_data->album();}
799                 if (!session_data->genre().empty())     {meta["genre"] = session_data->genre();}
800                 if (!session_data->composer().empty())  {meta["composer"] = session_data->composer();}
801                 if (!session_data->comment().empty())   {meta["comment"] = session_data->comment();}
802                 if (!session_data->copyright().empty()) {meta["copyright"] = session_data->copyright();}
803                 if (!session_data->subtitle().empty())  {meta["description"] = session_data->subtitle();}
804         }
805
806 #if 1 /* tentative debug mode */
807         if (debug_checkbox.get_active()) {
808                 transcoder->set_debug(true);
809         }
810 #endif
811
812         transcoder->Progress.connect(*this, invalidator (*this), boost::bind (&ExportVideoDialog::update_progress , this, _1, _2), gui_context());
813         transcoder->Finished.connect(*this, invalidator (*this), boost::bind (&ExportVideoDialog::finished, this), gui_context());
814         if (!transcoder->encode(outfn, insnd, invid, ffs, meta, map)) {
815                 ARDOUR_UI::instance()->popup_error(_("Transcoding failed."));
816                 Gtk::Dialog::response(RESPONSE_CANCEL);
817                 return;
818         }
819 }
820
821 void
822 ExportVideoDialog::change_file_extension (std::string ext)
823 {
824         outfn_path_entry.set_text (
825                 strip_file_extension(outfn_path_entry.get_text()) + ext
826         );
827 }
828
829 void
830 ExportVideoDialog::scale_checkbox_toggled ()
831 {
832         width_spinner.set_sensitive(scale_checkbox.get_active());
833         height_spinner.set_sensitive(scale_checkbox.get_active());
834 }
835
836 void
837 ExportVideoDialog::fps_checkbox_toggled ()
838 {
839         fps_combo.set_sensitive(fps_checkbox.get_active());
840 }
841
842 void
843 ExportVideoDialog::aspect_checkbox_toggled ()
844 {
845         aspect_combo.set_sensitive(aspect_checkbox.get_active());
846 }
847
848 void
849 ExportVideoDialog::video_codec_combo_changed ()
850 {
851         if ((  video_codec_combo.get_active_text() == "mpeg4"
852              ||video_codec_combo.get_active_text() == "mpeg2video"
853                         ) && !(
854                preset_combo.get_active_text() == "dvd-PAL"
855              ||preset_combo.get_active_text() == "dvd-NTSC"
856            )) {
857                 bframes_checkbox.set_sensitive(true);
858                 optimizations_checkbox.set_sensitive(true);
859                 if (video_codec_combo.get_active_text() == "mpeg2video") {
860                         optimizations_label.set_text("-mbd rd -trellis 2 -cmp 2 -subcmp 2"); // mpeg2
861                 } else if (video_codec_combo.get_active_text() == "mpeg4") {
862                         optimizations_label.set_text("-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -g 300"); // mpeg4
863                 } else {
864                         optimizations_label.set_text("-mbd 2 -cmp 2 -subcmp 2 -trellis 2 -flags +aic+mv0+mv4 -g 160"); // flv
865                 }
866         } else {
867                 bframes_checkbox.set_sensitive(false);
868                 bframes_checkbox.set_active(false);
869                 optimizations_checkbox.set_sensitive(false);
870                 optimizations_checkbox.set_active(false);
871                 optimizations_label.set_text("-");
872         }
873 }
874
875 void
876 ExportVideoDialog::preset_combo_changed ()
877 {
878         std::string p = preset_combo.get_active_text();
879         scale_checkbox.set_sensitive(true);
880
881         if (p == "flv") {
882                 change_file_extension(".flv");
883                 audio_codec_combo.set_active(1);
884                 video_codec_combo.set_active(0);
885                 audio_bitrate_combo.set_active(1);
886                 video_bitrate_combo.set_active(1);
887                 audio_samplerate_combo.set_active(1);
888         }
889         else if (p == "you-tube") {
890                 change_file_extension(".avi");
891                 audio_codec_combo.set_active(2);
892                 video_codec_combo.set_active(5);
893                 audio_bitrate_combo.set_active(1);
894                 video_bitrate_combo.set_active(2);
895                 if (_session->nominal_frame_rate() == 48000 || _session->nominal_frame_rate() == 96000) {
896                         audio_samplerate_combo.set_active(2);
897                 } else {
898                         audio_samplerate_combo.set_active(1);
899                 }
900         }
901         else if (p == "ogg") {
902                 change_file_extension(".ogv");
903                 audio_codec_combo.set_active(3);
904                 video_codec_combo.set_active(1);
905                 audio_bitrate_combo.set_active(2);
906                 video_bitrate_combo.set_active(2);
907                 if (_session->nominal_frame_rate() == 48000 || _session->nominal_frame_rate() == 96000) {
908                         audio_samplerate_combo.set_active(2);
909                 } else {
910                         audio_samplerate_combo.set_active(1);
911                 }
912         }
913         else if (p == "dvd-mp2") {
914                 change_file_extension(".mpg");
915                 audio_codec_combo.set_active(4);
916                 video_codec_combo.set_active(3);
917                 audio_bitrate_combo.set_active(3);
918                 video_bitrate_combo.set_active(3);
919                 audio_samplerate_combo.set_active(2);
920         }
921         else if (p == "dvd-NTSC" || p == "dvd-PAL") {
922                 change_file_extension(".mpg");
923                 audio_codec_combo.set_active(5);
924                 video_codec_combo.set_active(3);
925                 audio_bitrate_combo.set_active(3);
926                 video_bitrate_combo.set_active(3);
927                 audio_samplerate_combo.set_active(2);
928
929                 scale_checkbox.set_active(false);
930                 scale_checkbox.set_sensitive(false);
931         }
932         else if (p == "mpeg4") {
933                 change_file_extension(".mp4");
934                 audio_codec_combo.set_active(0);
935                 video_codec_combo.set_active(4);
936                 audio_bitrate_combo.set_active(3);
937                 video_bitrate_combo.set_active(3);
938                 if (_session->nominal_frame_rate() == 48000 || _session->nominal_frame_rate() == 96000) {
939                         audio_samplerate_combo.set_active(2);
940                 } else {
941                         audio_samplerate_combo.set_active(1);
942                 }
943         }
944
945         if (p == "none") {
946                 audio_codec_combo.set_sensitive(true);
947                 video_codec_combo.set_sensitive(true);
948                 audio_bitrate_combo.set_sensitive(true);
949                 video_bitrate_combo.set_sensitive(true);
950                 audio_samplerate_combo.set_sensitive(true);
951         } else {
952                 audio_codec_combo.set_sensitive(false);
953                 video_codec_combo.set_sensitive(false);
954                 audio_bitrate_combo.set_sensitive(false);
955                 video_bitrate_combo.set_sensitive(false);
956                 audio_samplerate_combo.set_sensitive(false);
957         }
958
959         Gtk::Table *t = (Gtk::Table*) preset_combo.get_parent();
960         Gtk::Table_Helpers::TableList c = t->children();
961         Gtk::Table_Helpers::TableList::iterator it;
962         if (p == "dvd-PAL" || p == "dvd-NTSC") {
963                 for (it = c.begin(); it != c.end(); ++it) {
964                         int row = it->get_top_attach();
965                         if (row == 2 || row == 3 || row== 5 || row== 6 || row == 9) {
966                                 it->get_widget()->hide();
967                         }
968                 }
969         } else {
970                 for (it = c.begin(); it != c.end(); ++it) {
971                         int row = it->get_top_attach();
972                         if (row == 2 || row == 3 || row== 5 || row== 6 || row == 9) {
973                                 it->get_widget()->show();
974                         }
975                 }
976         }
977
978         video_codec_combo_changed();
979 }
980
981 void
982 ExportVideoDialog::open_outfn_dialog ()
983 {
984         Gtk::FileChooserDialog dialog(_("Save Exported Video File"), Gtk::FILE_CHOOSER_ACTION_SAVE);
985         dialog.set_filename (outfn_path_entry.get_text());
986
987         dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
988         dialog.add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK);
989
990         int result = dialog.run();
991
992         if (result == Gtk::RESPONSE_OK) {
993                 std::string filename = dialog.get_filename();
994
995                 if (filename.length()) {
996                         outfn_path_entry.set_text (filename);
997                 }
998         }
999 }
1000
1001 void
1002 ExportVideoDialog::open_invid_dialog ()
1003 {
1004         Gtk::FileChooserDialog dialog(_("Save Exported Video File"), Gtk::FILE_CHOOSER_ACTION_SAVE);
1005         dialog.set_filename (invid_path_entry.get_text());
1006
1007         dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
1008         dialog.add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK);
1009
1010         int result = dialog.run();
1011
1012         if (result == Gtk::RESPONSE_OK) {
1013                 std::string filename = dialog.get_filename();
1014
1015                 if (filename.length()) {
1016                         invid_path_entry.set_text (filename);
1017                 }
1018         }
1019 }