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