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