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