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