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