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