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