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