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