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