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