75986a72f59c3ce3f4c4287ea63260a01884bd43
[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
32 #include <glib/gstdio.h>
33
34 #include "pbd/error.h"
35 #include "pbd/convert.h"
36 #include "gtkmm2ext/keyboard.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 "opts.h"
56 #include "export_video_dialog.h"
57 #include "utils_videotl.h"
58 #include "i18n.h"
59
60 #ifdef COMPILER_MSVC
61 #define rintf(x) round((x) + 0.5)
62 #endif
63
64 using namespace Gtk;
65 using namespace std;
66 using namespace PBD;
67 using namespace ARDOUR;
68 using namespace VideoUtils;
69
70 ExportVideoDialog::ExportVideoDialog ()
71         : ArdourDialog (_("Export Video File "))
72         , _aborted(false)
73         , _twopass(false)
74         , _firstpass(false)
75         , _normalize(false)
76         , _previous_progress(0)
77         , _transcoder(0)
78         , _video_source_aspect_ratio(-1)
79         , _suspend_signals(false)
80         , outfn_path_label (_("File:"), Gtk::ALIGN_LEFT)
81         , outfn_browse_button (_("Browse"))
82         , invid_path_label (_("Video:"), Gtk::ALIGN_LEFT)
83         , invid_browse_button (_("Browse"))
84         , transcode_button (_("Export"))
85         , abort_button (_("Abort"))
86         , scale_checkbox (_("Scale Video (W x H):"))
87         , scale_aspect (_("Retain Aspect"))
88         , width_adjustment (768, 128, 1920, 1, 16, 0)
89         , width_spinner (width_adjustment)
90         , height_adjustment (576, 128, 1920, 1, 16, 0)
91         , height_spinner (height_adjustment)
92         , aspect_checkbox (_("Set Aspect Ratio:"))
93         , normalize_checkbox (_("Normalize Audio"))
94         , twopass_checkbox (_("2 Pass Encoding"))
95         , optimizations_checkbox (_("Codec Optimizations:"))
96         , optimizations_label ("-")
97         , deinterlace_checkbox (_("Deinterlace"))
98         , bframes_checkbox (_("Use [2] B-frames (MPEG 2 or 4 only)"))
99         , fps_checkbox (_("Override FPS (Default is to retain FPS from the input video file):"))
100         , meta_checkbox (_("Include Session Metadata"))
101 #if 1 /* tentative debug mode */
102         , debug_checkbox (_("Debug Mode: Print ffmpeg command and output to stdout."))
103 #endif
104 {
105         set_name ("ExportVideoDialog");
106         set_modal (true);
107         set_skip_taskbar_hint (true);
108         set_resizable (false);
109
110         Gtk::Label* l;
111         vbox = manage (new VBox);
112         VBox* options_box = manage (new VBox);
113         HBox* path_hbox;
114
115         /* check if ffmpeg can be found */
116         _transcoder = new TranscodeFfmpeg(X_(""));
117         if (!_transcoder->ffexec_ok()) {
118                 l = manage (new Label (_("No ffprobe or ffmpeg executables could be found on this system. Video Export is not possible until you install those tools. See the Log window for more information."), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
119                 l->set_line_wrap();
120                 vbox->pack_start (*l, false, false, 8);
121                 get_vbox()->pack_start (*vbox, false, false);
122                 add_button (Stock::OK, RESPONSE_CANCEL);
123                 show_all_children ();
124                 delete _transcoder; _transcoder = 0;
125                 return;
126         }
127         delete _transcoder; _transcoder = 0;
128
129         l = manage (new Label (_("<b>Output:</b> (file extension defines format)"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
130         l->set_use_markup ();
131         vbox->pack_start (*l, false, false, 4);
132
133         path_hbox = manage (new HBox);
134         path_hbox->pack_start (outfn_path_label, false, false, 3);
135         path_hbox->pack_start (outfn_path_entry, true, true, 3);
136         path_hbox->pack_start (outfn_browse_button, false, false, 3);
137         vbox->pack_start (*path_hbox, false, false, 2);
138
139         l = manage (new Label (_("<b>Input Video:</b>"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
140         l->set_use_markup ();
141         vbox->pack_start (*l, false, false, 4);
142
143         path_hbox = manage (new HBox);
144         path_hbox->pack_start (invid_path_label, false, false, 3);
145         path_hbox->pack_start (invid_path_entry, true, true, 3);
146         path_hbox->pack_start (invid_browse_button, false, false, 3);
147         vbox->pack_start (*path_hbox, false, false, 2);
148
149         path_hbox = manage (new HBox);
150         l = manage (new Label (_("Audio:"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
151         path_hbox->pack_start (*l, false, false, 3);
152         l = manage (new Label (_("Master Bus"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
153         path_hbox->pack_start (*l, false, false, 2);
154         vbox->pack_start (*path_hbox, false, false, 2);
155
156         insnd_combo.set_name ("PaddedButton");
157         insnd_combo.append_text (string_compose (_("from the %1 session's start to the session's end"), PROGRAM_NAME));
158         outfn_path_entry.set_width_chars(38);
159
160         l = manage (new Label (_("<b>Settings:</b>"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
161         l->set_use_markup ();
162         options_box->pack_start (*l, false, true, 4);
163
164         Table* t = manage (new Table (4, 12));
165         t->set_spacings (4);
166         int ty = 0;
167         options_box->pack_start (*t, true, true, 4);
168         l = manage (new Label (_("Range:"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
169         t->attach (*l, 0, 1, ty, ty+1);
170         t->attach (insnd_combo, 1, 4, ty, ty+1); ty++;
171         l = manage (new Label (_("Preset:"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
172         t->attach (*l, 0, 1, ty, ty+1);
173         t->attach (preset_combo, 1, 4, ty, ty+1); ty++;
174         l = manage (new Label (_("Video Codec:"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
175         t->attach (*l, 0, 1, ty, ty+1);
176         t->attach (video_codec_combo, 1, 2, ty, ty+1);
177         l = manage (new Label (_("Video KBit/s:"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
178         t->attach (*l, 2, 3, ty, ty+1);
179         t->attach (video_bitrate_combo, 3, 4, ty, ty+1); ty++;
180         l = manage (new Label (_("Audio Codec:"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
181         t->attach (*l, 0, 1, ty, ty+1);
182         t->attach (audio_codec_combo, 1, 2, ty, ty+1);
183         l = manage (new Label (_("Audio KBit/s:"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
184         t->attach (*l, 2, 3, ty, ty+1);
185         t->attach (audio_bitrate_combo, 3, 4, ty, ty+1); ty++;
186         l = manage (new Label (_("Audio Samplerate:"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
187         t->attach (*l, 0, 1, ty, ty+1);
188         t->attach (audio_samplerate_combo, 1, 2, ty, ty+1);
189         t->attach (normalize_checkbox, 2, 4, ty, ty+1); ty++;
190         t->attach (scale_checkbox, 0, 1, ty, ty+1);
191         t->attach (scale_aspect, 1, 2, ty, ty+1);
192         t->attach (width_spinner, 2, 3, ty, ty+1);
193         t->attach (height_spinner, 3, 4, ty, ty+1); ty++;
194         t->attach (fps_checkbox, 0, 3, ty, ty+1);
195         t->attach (fps_combo, 3, 4, ty, ty+1); ty++;
196         t->attach (twopass_checkbox, 0, 2, ty, ty+1);
197         t->attach (aspect_checkbox, 2, 3, ty, ty+1);
198         t->attach (aspect_combo, 3, 4, ty, ty+1); ty++;
199         t->attach (bframes_checkbox, 0, 2, ty, ty+1);
200         t->attach (deinterlace_checkbox, 2, 4, ty, ty+1); ty++;
201         t->attach (meta_checkbox, 2, 4, ty, ty+1); ty++;
202         t->attach (optimizations_checkbox, 0, 1, ty, ty+1);
203         t->attach (optimizations_label, 1, 4, ty, ty+1); ty++;
204 #if 1 /* tentative debug mode */
205         t->attach (debug_checkbox, 0, 4, ty, ty+1); ty++;
206 #endif
207
208         preset_combo.set_name ("PaddedButton");
209         preset_combo.append_text("none");
210         preset_combo.append_text("dvd-mp2");
211         preset_combo.append_text("dvd-NTSC");
212         preset_combo.append_text("dvd-PAL");
213         preset_combo.append_text("flv");
214         preset_combo.append_text("mpeg4");
215         preset_combo.append_text("mp4/h264/aac");
216         preset_combo.append_text("ogg");
217         preset_combo.append_text("webm");
218         preset_combo.append_text("you-tube");
219
220         audio_codec_combo.set_name ("PaddedButton");
221         audio_codec_combo.append_text(_("(default for format)"));
222         audio_codec_combo.append_text("ac3");
223         audio_codec_combo.append_text("aac");
224         audio_codec_combo.append_text("libmp3lame");
225         audio_codec_combo.append_text("libvorbis");
226         audio_codec_combo.append_text("mp2");
227         audio_codec_combo.append_text("pcm_s16le");
228
229         video_codec_combo.set_name ("PaddedButton");
230         video_codec_combo.append_text(_("(default for format)"));
231         video_codec_combo.append_text("flv");
232         video_codec_combo.append_text("libtheora");
233         video_codec_combo.append_text("mjpeg");
234         video_codec_combo.append_text("mpeg2video");
235         video_codec_combo.append_text("mpeg4");
236         video_codec_combo.append_text("h264");
237         video_codec_combo.append_text("vpx (webm)");
238         video_codec_combo.append_text("copy");
239
240         audio_bitrate_combo.set_name ("PaddedButton");
241         audio_bitrate_combo.append_text(_("(default)"));
242         audio_bitrate_combo.append_text("64k");
243         audio_bitrate_combo.append_text("128k");
244         audio_bitrate_combo.append_text("192k");
245         audio_bitrate_combo.append_text("256k");
246         audio_bitrate_combo.append_text("320k");
247
248         audio_samplerate_combo.set_name ("PaddedButton");
249         audio_samplerate_combo.append_text("22050");
250         audio_samplerate_combo.append_text("44100");
251         audio_samplerate_combo.append_text("48000");
252
253         video_bitrate_combo.set_name ("PaddedButton");
254         video_bitrate_combo.append_text(_("(default)"));
255         video_bitrate_combo.append_text(_("(retain)"));
256         video_bitrate_combo.append_text("200k");
257         video_bitrate_combo.append_text("800k");
258         video_bitrate_combo.append_text("2000k");
259         video_bitrate_combo.append_text("5000k");
260         video_bitrate_combo.append_text("8000k");
261
262         fps_combo.set_name ("PaddedButton");
263         fps_combo.append_text("23.976");
264         fps_combo.append_text("24");
265         fps_combo.append_text("24.976");
266         fps_combo.append_text("25");
267         fps_combo.append_text("29.97");
268         fps_combo.append_text("30");
269         fps_combo.append_text("59.94");
270         fps_combo.append_text("60");
271
272         aspect_combo.set_name ("PaddedButton");
273         aspect_combo.append_text("4:3");
274         aspect_combo.append_text("16:9");
275
276         vbox->pack_start (*options_box, false, true, 4);
277         get_vbox()->set_spacing (4);
278         get_vbox()->pack_start (*vbox, false, false);
279
280         progress_box = manage (new VBox);
281         progress_box->pack_start (pbar, false, false);
282         progress_box->pack_start (abort_button, false, false);
283         get_vbox()->pack_start (*progress_box, false, false);
284
285         scale_checkbox.signal_toggled().connect (sigc::mem_fun (*this, &ExportVideoDialog::scale_checkbox_toggled));
286         aspect_checkbox.signal_toggled().connect (sigc::mem_fun (*this, &ExportVideoDialog::aspect_checkbox_toggled));
287         fps_checkbox.signal_toggled().connect (sigc::mem_fun (*this, &ExportVideoDialog::fps_checkbox_toggled));
288         preset_combo.signal_changed().connect (sigc::mem_fun (*this, &ExportVideoDialog::preset_combo_changed));
289         video_codec_combo.signal_changed().connect (sigc::mem_fun (*this, &ExportVideoDialog::video_codec_combo_changed));
290         outfn_browse_button.signal_clicked().connect (sigc::mem_fun (*this, &ExportVideoDialog::open_outfn_dialog));
291         invid_browse_button.signal_clicked().connect (sigc::mem_fun (*this, &ExportVideoDialog::open_invid_dialog));
292         transcode_button.signal_clicked().connect (sigc::mem_fun (*this, &ExportVideoDialog::launch_export));
293         abort_button.signal_clicked().connect (sigc::mem_fun (*this, &ExportVideoDialog::abort_clicked));
294
295         invid_path_entry.signal_changed().connect (sigc::mem_fun (*this, &ExportVideoDialog::set_original_file_information));
296         width_spinner.signal_value_changed().connect (sigc::mem_fun (*this, &ExportVideoDialog::width_value_changed));
297         height_spinner.signal_value_changed().connect (sigc::mem_fun (*this, &ExportVideoDialog::height_value_changed));
298
299         cancel_button = add_button (Stock::CANCEL, RESPONSE_CANCEL);
300         get_action_area()->pack_start (transcode_button, false, false);
301         show_all_children ();
302         progress_box->hide();
303 }
304
305 ExportVideoDialog::~ExportVideoDialog ()
306 {
307         if (_transcoder) { delete _transcoder; _transcoder = 0;}
308 }
309
310 void
311 ExportVideoDialog::set_original_file_information()
312 {
313         assert(_transcoder == 0);
314         std::string infile = invid_path_entry.get_text();
315
316         if (scale_checkbox.get_active()) {
317                 // user may have set custom values already, don't touch.
318                 return;
319         }
320         if (infile == "" || !Glib::file_test(infile, Glib::FILE_TEST_EXISTS)) {
321                 return;
322         }
323
324         _transcoder = new TranscodeFfmpeg(infile);
325         if (_transcoder->probe_ok()) {
326                 _video_source_aspect_ratio = -1;
327                 width_spinner.set_value(_transcoder->get_width());
328                 height_spinner.set_value(_transcoder->get_height());
329                 _video_source_aspect_ratio = _transcoder->get_aspect();
330         }
331
332         delete _transcoder; _transcoder = 0;
333 }
334 void
335 ExportVideoDialog::apply_state (TimeSelection &tme, bool range)
336 {
337         _suspend_dirty = true; // TODO really just queue 'dirty' and mark session dirty on "Export"
338
339         export_range = tme;
340         _video_source_aspect_ratio = -1;
341
342         outfn_path_entry.set_text (_session->session_directory().export_path() + G_DIR_SEPARATOR +"export.avi");
343
344         // TODO remember setting for export-range.. somehow, (let explicit range override)
345         frameoffset_t av_offset = ARDOUR_UI::instance()->video_timeline->get_offset();
346         if (av_offset < 0 ) {
347                 insnd_combo.append_text (_("from 00:00:00:00 to the video's end"));
348         } else {
349                 insnd_combo.append_text (_("from the video's start to the video's end"));
350         }
351         if (!export_range.empty()) {
352                 insnd_combo.append_text (_("Selected range"));  // TODO show export_range.start() -> export_range.end_frame()
353         }
354         if (range) {
355                 insnd_combo.set_active(2);
356         } else {
357                 insnd_combo.set_active(0);
358         }
359
360         preset_combo.set_active(0);
361         audio_codec_combo.set_active(0);
362         video_codec_combo.set_active(0);
363         audio_bitrate_combo.set_active(0);
364         audio_samplerate_combo.set_active(2);
365         video_bitrate_combo.set_active(0);
366         aspect_combo.set_active(1);
367
368         scale_checkbox.set_active(false);
369         scale_aspect.set_active(true);
370         aspect_checkbox.set_active(false);
371         normalize_checkbox.set_active(false);
372         twopass_checkbox.set_active(false);
373         optimizations_checkbox.set_active(false);
374         deinterlace_checkbox.set_active(false);
375         bframes_checkbox.set_active(false);
376         fps_checkbox.set_active(false);
377         meta_checkbox.set_active(false);
378
379         float tcfps = _session->timecode_frames_per_second();
380
381         LocaleGuard lg (X_("C"));
382
383         XMLNode* node = _session->extra_xml (X_("Videotimeline"));
384         bool filenameset = false;
385         if (node) {
386                 if (node->property(X_("OriginalVideoFile"))) {
387                         std::string filename = node->property(X_("OriginalVideoFile"))->value();
388                         if (Glib::file_test(filename, Glib::FILE_TEST_EXISTS)) {
389                                 invid_path_entry.set_text (filename);
390                                 filenameset = true;
391                         }
392                 }
393                 if (!filenameset
394                                 && node->property(X_("Filename"))
395                                 && node->property(X_("LocalFile"))
396                                 && node->property(X_("LocalFile"))->value() == X_("1")
397                    )
398                 {
399                         std::string filename = node->property(X_("Filename"))->value();
400                         if (filename.at(0) != G_DIR_SEPARATOR)
401                         {
402                                 filename = Glib::build_filename (_session->session_directory().video_path(), filename);
403                         }
404                         if (Glib::file_test(filename, Glib::FILE_TEST_EXISTS))
405                         {
406                                 invid_path_entry.set_text (filename);
407                                 filenameset = true;
408                         }
409                 }
410         }
411         if (!filenameset) {
412                 invid_path_entry.set_text (X_(""));
413         }
414
415         node = _session->extra_xml (X_("Videoexport"));
416         if (node) {
417                 const XMLProperty* prop;
418                 prop = node->property (X_("ChangeGeometry"));
419                 if (prop) { scale_checkbox.set_active(atoi(prop->value())?true:false); }
420                 prop = node->property (X_("KeepAspect"));
421                 if (prop) { scale_aspect.set_active(atoi(prop->value())?true:false); }
422                 prop = node->property (X_("ChangeAspect"));
423                 if (prop) { aspect_checkbox.set_active(atoi(prop->value())?true:false); }
424                 prop = node->property (X_("NormalizeAudio"));
425                 if (prop) { normalize_checkbox.set_active(atoi(prop->value())?true:false); }
426                 prop = node->property (X_("TwoPassEncode"));
427                 if (prop) { twopass_checkbox.set_active(atoi(prop->value())?true:false); }
428                 prop = node->property (X_("CodecOptimzations"));
429                 if (prop) { optimizations_checkbox.set_active(atoi(prop->value())?true:false); }
430                 prop = node->property (X_("Deinterlace"));
431                 if (prop) { deinterlace_checkbox.set_active(atoi(prop->value())?true:false); }
432                 prop = node->property (X_("BFrames"));
433                 if (prop) { bframes_checkbox.set_active(atoi(prop->value())?true:false); }
434                 prop = node->property (X_("ChangeFPS"));
435                 if (prop) { fps_checkbox.set_active(atoi(prop->value())?true:false); }
436                 prop = node->property (X_("Metadata"));
437                 if (prop) { meta_checkbox.set_active(atoi(prop->value())?true:false); }
438
439                 prop = node->property (X_("Format"));
440                 if (prop && !prop->value().empty()) { change_file_extension( "." + prop->value()); }
441
442                 _suspend_signals = true;
443                 prop = node->property (X_("Width"));
444                 if (prop) { width_spinner.set_value(atoi(prop->value())); }
445                 prop = node->property (X_("Height"));
446                 if (prop) { height_spinner.set_value(atoi(prop->value())); }
447                 _suspend_signals = false;
448
449                 prop = node->property (X_("FPS"));
450                 if (prop && fps_checkbox.get_active()) { tcfps = atof(prop->value()); }
451
452                 prop = node->property (X_("Preset"));
453                 if (prop) { preset_combo.set_active_text(prop->value()); }
454                 prop = node->property (X_("VCodec"));
455                 if (prop) { video_codec_combo.set_active_text(prop->value()); }
456                 prop = node->property (X_("ACodec"));
457                 if (prop) { audio_codec_combo.set_active_text(prop->value()); }
458                 prop = node->property (X_("VBitrate"));
459                 if (prop) { video_bitrate_combo.set_active_text(prop->value()); }
460                 prop = node->property (X_("ABitrate"));
461                 if (prop) { audio_bitrate_combo.set_active_text(prop->value()); }
462                 prop = node->property (X_("AspectRatio"));
463                 if (prop) { aspect_combo.set_active_text(prop->value()); }
464                 prop = node->property (X_("SampleRate"));
465                 if (prop) { audio_samplerate_combo.set_active_text(prop->value()); }
466         }
467
468         if      (fabs(tcfps - 23.976) < 0.01) { fps_combo.set_active(0); }
469         else if (fabs(tcfps - 24.0  ) < 0.01) { fps_combo.set_active(1); }
470         else if (fabs(tcfps - 24.976) < 0.01) { fps_combo.set_active(2); }
471         else if (fabs(tcfps - 25.0  ) < 0.01) { fps_combo.set_active(3); }
472         else if (fabs(tcfps - 29.97 ) < 0.01) { fps_combo.set_active(4); }
473         else if (fabs(tcfps - 30.0  ) < 0.01) { fps_combo.set_active(5); }
474         else if (fabs(tcfps - 59.94 ) < 0.01) { fps_combo.set_active(6); }
475         else if (fabs(tcfps - 60.0  ) < 0.01) { fps_combo.set_active(7); }
476         else { fps_combo.set_active(5); }
477
478         set_original_file_information();
479
480         /* update sensitivity */
481         scale_checkbox_toggled();
482         aspect_checkbox_toggled();
483         fps_checkbox_toggled();
484         video_codec_combo_changed();
485
486         _suspend_dirty = false;
487
488         show_all_children ();
489         progress_box->hide();
490 }
491
492 XMLNode&
493 ExportVideoDialog::get_state ()
494 {
495         LocaleGuard lg (X_("C"));
496         XMLNode* node = new XMLNode (X_("Videoexport"));
497         node->add_property (X_("ChangeGeometry"), scale_checkbox.get_active() ? X_("1") : X_("0"));
498         node->add_property (X_("KeepAspect"), scale_aspect.get_active() ? X_("1") : X_("0"));
499         node->add_property (X_("ChangeAspect"), aspect_checkbox.get_active() ? X_("1") : X_("0"));
500         node->add_property (X_("NormalizeAudio"), normalize_checkbox.get_active() ? X_("1") : X_("0"));
501         node->add_property (X_("TwoPassEncode"), twopass_checkbox.get_active() ? X_("1") : X_("0"));
502         node->add_property (X_("CodecOptimzations"), optimizations_checkbox.get_active() ? X_("1") : X_("0"));
503         node->add_property (X_("Deinterlace"), deinterlace_checkbox.get_active() ? X_("1") : X_("0"));
504         node->add_property (X_("BFrames"), bframes_checkbox.get_active() ? X_("1") : X_("0"));
505         node->add_property (X_("ChangeFPS"), fps_checkbox.get_active() ? X_("1") : X_("0"));
506         node->add_property (X_("Metadata"), meta_checkbox.get_active() ? X_("1") : X_("0"));
507
508         node->add_property (X_("Format"), get_file_extension(outfn_path_entry.get_text()));
509
510         node->add_property (X_("Width"), width_spinner.get_value());
511         node->add_property (X_("Height"), height_spinner.get_value());
512
513         node->add_property (X_("Preset"), preset_combo.get_active_text());
514         node->add_property (X_("VCodec"), video_codec_combo.get_active_text());
515         node->add_property (X_("ACodec"), audio_codec_combo.get_active_text());
516         node->add_property (X_("VBitrate"), video_bitrate_combo.get_active_text());
517         node->add_property (X_("ABitrate"), audio_bitrate_combo.get_active_text());
518         node->add_property (X_("AspectRatio"), aspect_combo.get_active_text());
519         node->add_property (X_("SampleRate"), audio_samplerate_combo.get_active_text());
520         node->add_property (X_("FPS"), fps_combo.get_active_text());
521
522         return *node;
523 }
524
525 void
526 ExportVideoDialog::set_state (const XMLNode &)
527 {
528 }
529
530 void
531 ExportVideoDialog::on_show ()
532 {
533         Dialog::on_show ();
534 }
535
536 bool
537 ExportVideoDialog::on_focus_in_event (GdkEventFocus *ev)
538 {
539         Dialog::on_focus_in_event (ev);
540         Gtkmm2ext::Keyboard::magic_widget_grab_focus ();
541         return true;
542 }
543
544 bool
545 ExportVideoDialog::on_focus_out_event (GdkEventFocus *ev)
546 {
547         Dialog::on_focus_out_event (ev);
548         Gtkmm2ext::Keyboard::magic_widget_drop_focus ();
549         return true;
550 }
551
552 void
553 ExportVideoDialog::abort_clicked ()
554 {
555         _aborted = true;
556         if (_transcoder) {
557                 _transcoder->cancel();
558         }
559 }
560
561 void
562 ExportVideoDialog::update_progress (framecnt_t c, framecnt_t a)
563 {
564         if (a == 0 || c > a) {
565                 pbar.set_pulse_step(.1);
566                 pbar.pulse();
567         } else {
568                 double progress = (double)c / (double) a;
569                 progress = progress / ((_twopass ? 2.0 : 1.0) + (_normalize ? 2.0 : 1.0));
570                 if (_normalize && _twopass) progress += (_firstpass ? .5 : .75);
571                 else if (_normalize) progress += 2.0/3.0;
572                 else if (_twopass) progress += (_firstpass ? 1.0/3.0 : 2.0/3.0);
573                 else progress += .5;
574
575                 pbar.set_fraction (progress);
576         }
577 }
578
579
580 gint
581 ExportVideoDialog::audio_progress_display ()
582 {
583         std::string status_text;
584         double progress = 0.0;
585                 if (status->normalizing) {
586                         pbar.set_text (_("Normalizing audio"));
587                         progress = ((float) status->current_normalize_cycle) / status->total_normalize_cycles;
588                         progress = progress / (_twopass ? 4.0 : 3.0) + (_twopass ? .25 : 1.0/3.0);
589                 } else {
590                         pbar.set_text (_("Exporting audio"));
591                         progress = ((float) status->processed_frames_current_timespan) / status->total_frames_current_timespan;
592                         progress = progress / ((_twopass ? 2.0 : 1.0) + (_normalize ? 2.0 : 1.0));
593                 }
594                 if (progress < _previous_progress) {
595                         // Work around gtk bug
596                         pbar.hide();
597                         pbar.show();
598                 }
599                 _previous_progress = progress;
600                 pbar.set_fraction (progress);
601         return TRUE;
602 }
603
604 void
605 ExportVideoDialog::finished ()
606 {
607         if (_aborted) {
608                 ::g_unlink(outfn_path_entry.get_text().c_str());
609                 ::g_unlink (_insnd.c_str());
610                 delete _transcoder; _transcoder = 0;
611                 Gtk::Dialog::response(RESPONSE_CANCEL);
612         } else if (_twopass && _firstpass) {
613                 _firstpass = false;
614                 if (_transcoder) { delete _transcoder; _transcoder = 0;}
615                 encode_pass(2);
616         } else {
617                 if (twopass_checkbox.get_active()) {
618                         std::string outfn = outfn_path_entry.get_text();
619                         std::string p2log = Glib::path_get_dirname (outfn) + G_DIR_SEPARATOR + "ffmpeg2pass";
620                         ::g_unlink (p2log.c_str());
621                 }
622                 ::g_unlink (_insnd.c_str());
623                 delete _transcoder; _transcoder = 0;
624                 Gtk::Dialog::response(RESPONSE_ACCEPT);
625         }
626 }
627
628 void
629 ExportVideoDialog::launch_export ()
630 {
631         /* remember current settings.
632          * needed because apply_state() acts on both:
633          * "Videotimeline" and "Video Export" extra XML
634          * as well as current _session settings
635          */
636         _session->add_extra_xml (get_state());
637
638         std::string outfn = outfn_path_entry.get_text();
639         if (!confirm_video_outfn(outfn)) { return; }
640
641         vbox->hide();
642         cancel_button->hide();
643         transcode_button.hide();
644         pbar.set_size_request(300,-1);
645         pbar.set_text(_("Exporting Audio..."));
646         progress_box->show();
647         _aborted = false;
648         _twopass = twopass_checkbox.get_active();
649         _firstpass = true;
650         _normalize = normalize_checkbox.get_active();
651
652         /* export audio track */
653         ExportTimespanPtr tsp = _session->get_export_handler()->add_timespan();
654         boost::shared_ptr<ExportChannelConfiguration> ccp = _session->get_export_handler()->add_channel_config();
655         boost::shared_ptr<ARDOUR::ExportFilename> fnp = _session->get_export_handler()->add_filename();
656         boost::shared_ptr<AudioGrapher::BroadcastInfo> b;
657         XMLTree tree;
658         std::string vtl_samplerate = audio_samplerate_combo.get_active_text();
659         std::string vtl_normalize = _normalize ? "true" : "false";
660         tree.read_buffer(std::string(
661 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
662 "<ExportFormatSpecification name=\"VTL-WAV-16\" id=\"3094591e-ccb9-4385-a93f-c9955ffeb1f0\">"
663 "  <Encoding id=\"F_WAV\" type=\"T_Sndfile\" extension=\"wav\" name=\"WAV\" has-sample-format=\"true\" channel-limit=\"256\"/>"
664 "  <SampleRate rate=\""+ vtl_samplerate +"\"/>"
665 "  <SRCQuality quality=\"SRC_SincBest\"/>"
666 "  <EncodingOptions>"
667 "    <Option name=\"sample-format\" value=\"SF_16\"/>"
668 "    <Option name=\"dithering\" value=\"D_None\"/>"
669 "    <Option name=\"tag-metadata\" value=\"true\"/>"
670 "    <Option name=\"tag-support\" value=\"false\"/>"
671 "    <Option name=\"broadcast-info\" value=\"false\"/>"
672 "  </EncodingOptions>"
673 "  <Processing>"
674 "    <Normalize enabled=\""+ vtl_normalize +"\" target=\"0\"/>"
675 "    <Silence>"
676 "      <Start>"
677 "        <Trim enabled=\"false\"/>"
678 "        <Add enabled=\"false\">"
679 "          <Duration format=\"Timecode\" hours=\"0\" minutes=\"0\" seconds=\"0\" frames=\"0\"/>"
680 "        </Add>"
681 "      </Start>"
682 "      <End>"
683 "        <Trim enabled=\"false\"/>"
684 "        <Add enabled=\"false\">"
685 "          <Duration format=\"Timecode\" hours=\"0\" minutes=\"0\" seconds=\"0\" frames=\"0\"/>"
686 "        </Add>"
687 "      </End>"
688 "    </Silence>"
689 "  </Processing>"
690 "</ExportFormatSpecification>"
691 ));
692         boost::shared_ptr<ExportFormatSpecification> fmp = _session->get_export_handler()->add_format(*tree.root());
693
694         /* set up range */
695         framepos_t start, end;
696         start = end = 0;
697         if (insnd_combo.get_active_row_number() == 1) {
698                 _transcoder = new TranscodeFfmpeg(invid_path_entry.get_text());
699                 if (_transcoder->probe_ok() && _transcoder->get_fps() > 0) {
700                         end = _transcoder->get_duration() * _session->nominal_frame_rate() / _transcoder->get_fps();
701                 } else {
702                         warning << _("Export Video: Cannot query duration of video-file, using duration from timeline instead.") << endmsg;
703                         end = ARDOUR_UI::instance()->video_timeline->get_duration();
704                 }
705                 if (_transcoder) {delete _transcoder; _transcoder = 0;}
706
707                 frameoffset_t av_offset = ARDOUR_UI::instance()->video_timeline->get_offset();
708 #if 0 /* DEBUG */
709                 printf("audio-range -- AV offset: %lld\n", av_offset);
710 #endif
711                 if (av_offset > 0) {
712                         start = av_offset;
713                 }
714                 end += av_offset;
715         }
716         else if (insnd_combo.get_active_row_number() == 2) {
717                 start = ARDOUR_UI::instance()->video_timeline->quantify_frames_to_apv(export_range.start());
718                 end   = ARDOUR_UI::instance()->video_timeline->quantify_frames_to_apv(export_range.end_frame());
719         }
720         if (end <= 0) {
721                 start = _session->current_start_frame();
722                 end   = _session->current_end_frame();
723         }
724 #if 0 /* DEBUG */
725         printf("audio export-range %lld -> %lld\n", start, end);
726 #endif
727
728         const frameoffset_t vstart = ARDOUR_UI::instance()->video_timeline->get_offset();
729         const frameoffset_t vend   = vstart + ARDOUR_UI::instance()->video_timeline->get_duration();
730
731         if ( (start >= end) || (end < vstart) || (start > vend)) {
732                 warning << _("Export Video: export-range does not include video.") << endmsg;
733                 delete _transcoder; _transcoder = 0;
734                 Gtk::Dialog::response(RESPONSE_CANCEL);
735                 return;
736         }
737
738         tsp->set_range (start, end);
739         tsp->set_name ("mysession");
740         tsp->set_range_id ("session");
741
742         /* add master outs as default */
743         IO* master_out = _session->master_out()->output().get();
744         if (!master_out) {
745                 warning << _("Export Video: No Master Out Ports to Connect for Audio Export") << endmsg;
746                 delete _transcoder; _transcoder = 0;
747                 Gtk::Dialog::response(RESPONSE_CANCEL);
748                 return;
749         }
750         for (uint32_t n = 0; n < master_out->n_ports().n_audio(); ++n) {
751                 PortExportChannel * channel = new PortExportChannel ();
752                 channel->add_port (master_out->audio (n));
753                 ExportChannelPtr chan_ptr (channel);
754                 ccp->register_channel (chan_ptr);
755         }
756
757         /* outfile */
758         fnp->set_timespan(tsp);
759         fnp->set_label("vtl");
760         fnp->include_label = true;
761         _insnd = fnp->get_path(fmp);
762
763         /* do sound export */
764         fmp->set_soundcloud_upload(false);
765         _session->get_export_handler()->add_export_config (tsp, ccp, fmp, fnp, b);
766         _session->get_export_handler()->do_export();
767         status = _session->get_export_status ();
768
769         audio_progress_connection = Glib::signal_timeout().connect (sigc::mem_fun(*this, &ExportVideoDialog::audio_progress_display), 100);
770         _previous_progress = 0.0;
771         while (status->running) {
772                 if (_aborted) { status->abort(); }
773                 if (gtk_events_pending()) {
774                         gtk_main_iteration ();
775                 } else {
776                         Glib::usleep (10000);
777                 }
778         }
779         audio_progress_connection.disconnect();
780         status->finish ();
781         if (status->aborted()) {
782                 ::g_unlink (_insnd.c_str());
783                 delete _transcoder; _transcoder = 0;
784                 Gtk::Dialog::response(RESPONSE_CANCEL);
785                 return;
786         }
787         pbar.set_text (_("Encoding Video..."));
788         encode_pass(1);
789 }
790
791 void
792 ExportVideoDialog::encode_pass (int pass)
793 {
794         std::string outfn = outfn_path_entry.get_text();
795         std::string invid = invid_path_entry.get_text();
796
797         _transcoder = new TranscodeFfmpeg(invid);
798         if (!_transcoder->ffexec_ok()) {
799                 /* ffmpeg binary was not found. TranscodeFfmpeg prints a warning */
800                 ::g_unlink (_insnd.c_str());
801                 delete _transcoder; _transcoder = 0;
802                 Gtk::Dialog::response(RESPONSE_CANCEL);
803                 return;
804         }
805         if (!_transcoder->probe_ok()) {
806                 /* video input file can not be read */
807                 warning << _("Export Video: Video input file cannot be read.") << endmsg;
808                 ::g_unlink (_insnd.c_str());
809                 delete _transcoder; _transcoder = 0;
810                 Gtk::Dialog::response(RESPONSE_CANCEL);
811                 return;
812         }
813
814         std::string preset = preset_combo.get_active_text();
815         TranscodeFfmpeg::FFSettings ffs ; /* = transcoder->default_encoder_settings(); */
816         ffs.clear();
817
818         if (fps_checkbox.get_active()) {
819                 ffs["-r"] = fps_combo.get_active_text();
820                 _transcoder->set_fps(atof(fps_combo.get_active_text()));
821         }
822
823         if (scale_checkbox.get_active()) {
824                 ffs["-s"] = string_compose("%1x%2", width_spinner.get_value(), height_spinner.get_value());
825         }
826
827         if (video_codec_combo.get_active_text() != _("(default for format)")) {
828                 ffs["-vcodec"] = video_codec_combo.get_active_text();
829         }
830         if (audio_codec_combo.get_active_text() != _("(default for format)")) {
831                 ffs["-acodec"] = audio_codec_combo.get_active_text();
832         }
833
834         if (video_bitrate_combo.get_active_text() == _("(default)") ) {
835                 ;
836         }
837         else if (video_bitrate_combo.get_active_text() == _("(retain)") ) {
838                 ffs["-qscale"]  = "0";
839         } else {
840                 ffs["-b:v"]  = video_bitrate_combo.get_active_text();
841         }
842
843         if (audio_bitrate_combo.get_active_text() != _("(default)") ) {
844                 ffs["-b:a"] = audio_bitrate_combo.get_active_text();
845         }
846
847         if (audio_codec_combo.get_active_text() == "aac" ) {
848                 ffs["-strict"] = "-2";
849         }
850
851         if (video_codec_combo.get_active_text() == "h264" ) {
852                 ffs["-vcodec"] = "libx264";
853         }
854         else if (video_codec_combo.get_active_text() == "vpx (webm)" ) {
855                 ffs["-vcodec"] = "libvpx";
856                 ffs["-g"] = "120";
857                 ffs["-qmin"] = "11";
858                 ffs["-qmax"] = "51";
859         }
860
861         if (optimizations_checkbox.get_active()) {
862           if (video_codec_combo.get_active_text() == "mpeg2video") {
863                         ffs["-mbd"] = "rd";
864                         ffs["-trellis"] = "2";
865                         ffs["-cmp"] = "2";
866                         ffs["-subcmp"] = "2";
867                 }
868                 else if (video_codec_combo.get_active_text() == "mpeg4") {
869                         ffs["-mbd"] = "rd";
870                         ffs["-flags"] = "+mv4+aic";
871                         ffs["-trellis"] = "2";
872                         ffs["-cmp"] = "2";
873                         ffs["-subcmp"] = "2";
874                         ffs["-g"] = "300";
875                 }
876                 else if (video_codec_combo.get_active_text() == "flv") {
877                         ffs["-mbd"] = "2";
878                         ffs["-cmp"] = "2";
879                         ffs["-subcmp"] = "2";
880                         ffs["-trellis"] = "2";
881                         ffs["-flags"] = "+aic+mv0+mv4";
882                         ffs["-g"] = "160";
883                 }
884         }
885
886         if (bframes_checkbox.get_active() && (
887                    video_codec_combo.get_active_text() == "mpeg2video"
888                 || video_codec_combo.get_active_text() == "mpeg4"
889                 )) {
890                 ffs["-bf"] = "2";
891         }
892
893         if (preset == "dvd-PAL") {
894                 ffs.clear(); /* ignore all prev settings */
895                 ffs["-target"] = "pal-dvd";
896                 ffs["-aspect"] = "4:3"; /* required for DVD - may be overridden below */
897         }
898         else if (preset == "dvd-NTSC") {
899                 ffs.clear(); /* ignore all prev settings */
900                 ffs["-target"] = "ntsc-dvd";
901                 ffs["-aspect"] = "4:3"; /* required for DVD - may be overridden below */
902         }
903
904         if (aspect_checkbox.get_active()) {
905                 ffs["-aspect"] = aspect_combo.get_active_text();
906         }
907         if (deinterlace_checkbox.get_active()) {
908                 ffs["-deinterlace"] = "-y"; // we use '-y' as dummy parameter for non key/value options
909         }
910
911         bool map = true;
912         if (pass == 1 && _twopass) {
913                 pbar.set_text (_("Encoding Video.. Pass 1/2"));
914                 map = false;
915                 ffs["-pass"] = "1";
916                 ffs["-an"] = "-y";
917                 ffs["-passlogfile"] =  Glib::path_get_dirname (outfn) + G_DIR_SEPARATOR + "ffmpeg2pass";
918                 ffs["-f"] = get_file_extension(invid).empty()?"mov":get_file_extension(invid);
919 #ifdef PLATFORM_WINDOWS
920                 outfn = "NUL";
921 #else
922                 outfn = "/dev/null";
923 #endif
924         } else if (pass == 2) {
925                 pbar.set_text (_("Encoding Video.. Pass 2/2"));
926                 ffs["-pass"] = "2";
927                 ffs["-passlogfile"] =  Glib::path_get_dirname (outfn) + G_DIR_SEPARATOR + "ffmpeg2pass";
928         }
929
930         frameoffset_t av_offset = ARDOUR_UI::instance()->video_timeline->get_offset();
931         double duration_s  = 0;
932
933         if (insnd_combo.get_active_row_number() == 0) {
934                 /* session start to session end */
935                 framecnt_t duration_f = _session->current_end_frame() - _session->current_start_frame();
936                 duration_s = (double)duration_f / (double)_session->nominal_frame_rate();
937         } else if (insnd_combo.get_active_row_number() == 2) {
938                 /* selected range */
939                 duration_s = export_range.length() / (double)_session->nominal_frame_rate();
940         } else {
941                 /* video start to end */
942                 framecnt_t duration_f = ARDOUR_UI::instance()->video_timeline->get_duration();
943                 if (av_offset < 0 ) {
944                         duration_f += av_offset;
945                 }
946                 duration_s = (double)duration_f / (double)_session->nominal_frame_rate();
947         }
948
949         std::ostringstream osstream; osstream << duration_s;
950         ffs["-t"] = osstream.str();
951         _transcoder->set_duration(duration_s * _transcoder->get_fps());
952
953         if (insnd_combo.get_active_row_number() == 0 || insnd_combo.get_active_row_number() == 2) {
954                 framepos_t start, snend;
955                 const frameoffset_t vid_duration = ARDOUR_UI::instance()->video_timeline->get_duration();
956                 if (insnd_combo.get_active_row_number() == 0) {
957                         start = _session->current_start_frame();
958                         snend = _session->current_end_frame();
959                 } else {
960                         start = export_range.start();
961                         snend = export_range.end_frame();
962                 }
963
964 #if 0 /* DEBUG */
965                 printf("AV offset: %lld Vid-len: %lld Vid-end: %lld || start:%lld || end:%lld\n",
966                                 av_offset, vid_duration, av_offset+vid_duration, start, snend); // XXX
967 #endif
968
969                 if (av_offset > start && av_offset + vid_duration < snend) {
970                         _transcoder->set_leadinout((av_offset - start) / (double)_session->nominal_frame_rate(),
971                                 (snend - (av_offset + vid_duration)) / (double)_session->nominal_frame_rate());
972                 } else if (av_offset > start) {
973                         _transcoder->set_leadinout((av_offset - start) / (double)_session->nominal_frame_rate(), 0);
974                 } else if (av_offset + vid_duration < snend) {
975                         _transcoder->set_leadinout(0, (snend - (av_offset + vid_duration)) / (double)_session->nominal_frame_rate());
976                         _transcoder->set_avoffset((av_offset - start) / (double)_session->nominal_frame_rate());
977                 }
978 #if 0
979                 else if (start > av_offset) {
980                         std::ostringstream osstream; osstream << ((start - av_offset) / (double)_session->nominal_frame_rate());
981                         ffs["-ss"] = osstream.str();
982                 }
983 #endif
984                 else {
985                         _transcoder->set_avoffset((av_offset - start) / (double)_session->nominal_frame_rate());
986                 }
987
988         } else if (av_offset < 0) {
989                 /* from 00:00:00:00 to video-end */
990                 _transcoder->set_avoffset(av_offset / (double)_session->nominal_frame_rate());
991         }
992
993         TranscodeFfmpeg::FFSettings meta = _transcoder->default_meta_data();
994         if (meta_checkbox.get_active()) {
995                 ARDOUR::SessionMetadata * session_data = ARDOUR::SessionMetadata::Metadata();
996                 if (session_data->year() > 0 ) {
997                         std::ostringstream osstream; osstream << session_data->year();
998                         meta["year"] = osstream.str();
999                 }
1000                 if (session_data->track_number() > 0 ) {
1001                         std::ostringstream osstream; osstream << session_data->track_number();
1002                         meta["track"] = osstream.str();
1003                 }
1004                 if (session_data->disc_number() > 0 ) {
1005                         std::ostringstream osstream; osstream << session_data->disc_number();
1006                         meta["disc"] = osstream.str();
1007                 }
1008                 if (!session_data->title().empty())     {meta["title"] = session_data->title();}
1009                 if (!session_data->artist().empty())    {meta["author"] = session_data->artist();}
1010                 if (!session_data->album_artist().empty()) {meta["album_artist"] = session_data->album_artist();}
1011                 if (!session_data->album().empty())     {meta["album"] = session_data->album();}
1012                 if (!session_data->genre().empty())     {meta["genre"] = session_data->genre();}
1013                 if (!session_data->composer().empty())  {meta["composer"] = session_data->composer();}
1014                 if (!session_data->comment().empty())   {meta["comment"] = session_data->comment();}
1015                 if (!session_data->copyright().empty()) {meta["copyright"] = session_data->copyright();}
1016                 if (!session_data->subtitle().empty())  {meta["description"] = session_data->subtitle();}
1017         }
1018
1019 #if 1 /* tentative debug mode */
1020         if (debug_checkbox.get_active()) {
1021                 _transcoder->set_debug(true);
1022         }
1023 #endif
1024
1025         _transcoder->Progress.connect(*this, invalidator (*this), boost::bind (&ExportVideoDialog::update_progress , this, _1, _2), gui_context());
1026         _transcoder->Finished.connect(*this, invalidator (*this), boost::bind (&ExportVideoDialog::finished, this), gui_context());
1027         if (!_transcoder->encode(outfn, _insnd, invid, ffs, meta, map)) {
1028                 ARDOUR_UI::instance()->popup_error(_("Transcoding failed."));
1029                 delete _transcoder; _transcoder = 0;
1030                 Gtk::Dialog::response(RESPONSE_CANCEL);
1031                 return;
1032         }
1033 }
1034
1035 void
1036 ExportVideoDialog::change_file_extension (std::string ext)
1037 {
1038         if (ext == "") return;
1039         outfn_path_entry.set_text (
1040                 strip_file_extension(outfn_path_entry.get_text()) + ext
1041         );
1042 }
1043
1044 void
1045 ExportVideoDialog::width_value_changed ()
1046 {
1047         if (_suspend_signals) {
1048                 return;
1049         }
1050         if (_session && !_suspend_dirty) _session->set_dirty ();
1051         if (!scale_checkbox.get_active() || !scale_aspect.get_active()) {
1052                 return;
1053         }
1054         if (_video_source_aspect_ratio <= 0) {
1055                 return;
1056         }
1057         _suspend_signals = true;
1058         height_spinner.set_value(rintf(width_spinner.get_value() / _video_source_aspect_ratio));
1059         _suspend_signals = false;
1060 }
1061
1062 void
1063 ExportVideoDialog::height_value_changed ()
1064 {
1065         if (_suspend_signals) {
1066                 return;
1067         }
1068         if (_session && !_suspend_dirty) _session->set_dirty ();
1069         if (!scale_checkbox.get_active() || !scale_aspect.get_active()) {
1070                 return;
1071         }
1072         if (_video_source_aspect_ratio <= 0) {
1073                 return;
1074         }
1075         _suspend_signals = true;
1076         width_spinner.set_value(rintf(height_spinner.get_value() * _video_source_aspect_ratio));
1077         _suspend_signals = false;
1078 }
1079
1080 void
1081 ExportVideoDialog::scale_checkbox_toggled ()
1082 {
1083         scale_aspect.set_sensitive(scale_checkbox.get_active());
1084         width_spinner.set_sensitive(scale_checkbox.get_active());
1085         height_spinner.set_sensitive(scale_checkbox.get_active());
1086         if (_session && !_suspend_dirty) _session->set_dirty ();
1087 }
1088
1089 void
1090 ExportVideoDialog::fps_checkbox_toggled ()
1091 {
1092         fps_combo.set_sensitive(fps_checkbox.get_active());
1093         if (_session && !_suspend_dirty) _session->set_dirty ();
1094 }
1095
1096 void
1097 ExportVideoDialog::aspect_checkbox_toggled ()
1098 {
1099         aspect_combo.set_sensitive(aspect_checkbox.get_active());
1100         if (_session && !_suspend_dirty) _session->set_dirty ();
1101 }
1102
1103 void
1104 ExportVideoDialog::video_codec_combo_changed ()
1105 {
1106         if ((  video_codec_combo.get_active_text() == "mpeg4"
1107              ||video_codec_combo.get_active_text() == "mpeg2video"
1108                         ) && !(
1109                preset_combo.get_active_text() == "dvd-PAL"
1110              ||preset_combo.get_active_text() == "dvd-NTSC"
1111            )) {
1112                 bframes_checkbox.set_sensitive(true);
1113                 optimizations_checkbox.set_sensitive(true);
1114                 if (video_codec_combo.get_active_text() == "mpeg2video") {
1115                         optimizations_label.set_text("-mbd rd -trellis 2 -cmp 2 -subcmp 2"); // mpeg2
1116                 } else if (video_codec_combo.get_active_text() == "mpeg4") {
1117                         optimizations_label.set_text("-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -g 300"); // mpeg4
1118                 } else {
1119                         optimizations_label.set_text("-mbd 2 -cmp 2 -subcmp 2 -trellis 2 -flags +aic+mv0+mv4 -g 160"); // flv
1120                 }
1121         } else {
1122                 bframes_checkbox.set_sensitive(false);
1123                 bframes_checkbox.set_active(false);
1124                 optimizations_checkbox.set_sensitive(false);
1125                 optimizations_checkbox.set_active(false);
1126                 optimizations_label.set_text("-");
1127         }
1128         if (_session && !_suspend_dirty) _session->set_dirty ();
1129 }
1130
1131 void
1132 ExportVideoDialog::preset_combo_changed ()
1133 {
1134         std::string p = preset_combo.get_active_text();
1135         scale_checkbox.set_sensitive(true);
1136
1137         if (p == "flv") {
1138                 change_file_extension(".flv");
1139                 audio_codec_combo.set_active(2);
1140                 video_codec_combo.set_active(1);
1141                 audio_bitrate_combo.set_active(2);
1142                 video_bitrate_combo.set_active(3);
1143                 audio_samplerate_combo.set_active(1);
1144         }
1145         else if (p == "you-tube") {
1146                 change_file_extension(".avi");
1147                 audio_codec_combo.set_active(3);
1148                 video_codec_combo.set_active(6);
1149                 audio_bitrate_combo.set_active(2);
1150                 video_bitrate_combo.set_active(4);
1151                 if (_session->nominal_frame_rate() == 48000 || _session->nominal_frame_rate() == 96000) {
1152                         audio_samplerate_combo.set_active(2);
1153                 } else {
1154                         audio_samplerate_combo.set_active(1);
1155                 }
1156         }
1157         else if (p == "ogg") {
1158                 change_file_extension(".ogv");
1159                 audio_codec_combo.set_active(4);
1160                 video_codec_combo.set_active(2);
1161                 audio_bitrate_combo.set_active(3);
1162                 video_bitrate_combo.set_active(4);
1163                 if (_session->nominal_frame_rate() == 48000 || _session->nominal_frame_rate() == 96000) {
1164                         audio_samplerate_combo.set_active(2);
1165                 } else {
1166                         audio_samplerate_combo.set_active(1);
1167                 }
1168         }
1169         else if (p == "webm") {
1170                 change_file_extension(".webm");
1171                 audio_codec_combo.set_active(4);
1172                 video_codec_combo.set_active(7);
1173                 audio_bitrate_combo.set_active(3);
1174                 video_bitrate_combo.set_active(4);
1175                 if (_session->nominal_frame_rate() == 48000 || _session->nominal_frame_rate() == 96000) {
1176                         audio_samplerate_combo.set_active(2);
1177                 } else {
1178                         audio_samplerate_combo.set_active(1);
1179                 }
1180         }
1181         else if (p == "dvd-mp2") {
1182                 change_file_extension(".mpg");
1183                 audio_codec_combo.set_active(5);
1184                 video_codec_combo.set_active(4);
1185                 audio_bitrate_combo.set_active(4);
1186                 video_bitrate_combo.set_active(5);
1187                 audio_samplerate_combo.set_active(2);
1188         }
1189         else if (p == "dvd-NTSC" || p == "dvd-PAL") {
1190                 change_file_extension(".mpg");
1191                 audio_codec_combo.set_active(6);
1192                 video_codec_combo.set_active(4);
1193                 audio_bitrate_combo.set_active(4);
1194                 video_bitrate_combo.set_active(5);
1195                 audio_samplerate_combo.set_active(2);
1196
1197                 scale_checkbox.set_active(false);
1198                 scale_checkbox.set_sensitive(false);
1199         }
1200         else if (p == "mpeg4") {
1201                 change_file_extension(".mp4");
1202                 audio_codec_combo.set_active(1);
1203                 video_codec_combo.set_active(5);
1204                 audio_bitrate_combo.set_active(4);
1205                 video_bitrate_combo.set_active(5);
1206                 if (_session->nominal_frame_rate() == 48000 || _session->nominal_frame_rate() == 96000) {
1207                         audio_samplerate_combo.set_active(2);
1208                 } else {
1209                         audio_samplerate_combo.set_active(1);
1210                 }
1211         }
1212         else if (p == "mp4/h264/aac") {
1213                 change_file_extension(".mp4");
1214                 audio_codec_combo.set_active(2);
1215                 video_codec_combo.set_active(6);
1216                 audio_bitrate_combo.set_active(0);
1217                 video_bitrate_combo.set_active(0);
1218                 if (_session->nominal_frame_rate() == 48000 || _session->nominal_frame_rate() == 96000) {
1219                         audio_samplerate_combo.set_active(2);
1220                 } else {
1221                         audio_samplerate_combo.set_active(1);
1222                 }
1223         }
1224
1225         if (p == "none") {
1226                 audio_codec_combo.set_sensitive(true);
1227                 video_codec_combo.set_sensitive(true);
1228                 audio_bitrate_combo.set_sensitive(true);
1229                 video_bitrate_combo.set_sensitive(true);
1230                 audio_samplerate_combo.set_sensitive(true);
1231         } else {
1232                 audio_codec_combo.set_sensitive(false);
1233                 video_codec_combo.set_sensitive(false);
1234                 audio_bitrate_combo.set_sensitive(false);
1235                 video_bitrate_combo.set_sensitive(false);
1236                 audio_samplerate_combo.set_sensitive(false);
1237         }
1238
1239         Gtk::Table *t = (Gtk::Table*) preset_combo.get_parent();
1240         Gtk::Table_Helpers::TableList c = t->children();
1241         Gtk::Table_Helpers::TableList::iterator it;
1242         if (p == "dvd-PAL" || p == "dvd-NTSC") {
1243                 for (it = c.begin(); it != c.end(); ++it) {
1244                         int row = it->get_top_attach();
1245                         if (row == 2 || row == 3 || row== 5 || row== 6 || row == 9) {
1246                                 it->get_widget()->hide();
1247                         }
1248                 }
1249         } else {
1250                 for (it = c.begin(); it != c.end(); ++it) {
1251                         int row = it->get_top_attach();
1252                         if (row == 2 || row == 3 || row== 5 || row== 6 || row == 9) {
1253                                 it->get_widget()->show();
1254                         }
1255                 }
1256         }
1257
1258         video_codec_combo_changed();
1259 }
1260
1261 void
1262 ExportVideoDialog::open_outfn_dialog ()
1263 {
1264         Gtk::FileChooserDialog dialog(_("Save Exported Video File"), Gtk::FILE_CHOOSER_ACTION_SAVE);
1265         dialog.set_filename (outfn_path_entry.get_text());
1266
1267         dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
1268         dialog.add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK);
1269
1270         int result = dialog.run();
1271
1272         if (result == Gtk::RESPONSE_OK) {
1273                 std::string filename = dialog.get_filename();
1274
1275                 if (filename.length()) {
1276                         outfn_path_entry.set_text (filename);
1277                 }
1278         }
1279 }
1280
1281 void
1282 ExportVideoDialog::open_invid_dialog ()
1283 {
1284         Gtk::FileChooserDialog dialog(_("Save Exported Video File"), Gtk::FILE_CHOOSER_ACTION_SAVE);
1285         dialog.set_filename (invid_path_entry.get_text());
1286
1287         dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
1288         dialog.add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK);
1289
1290         int result = dialog.run();
1291
1292         if (result == Gtk::RESPONSE_OK) {
1293                 std::string filename = dialog.get_filename();
1294
1295                 if (filename.length()) {
1296                         invid_path_entry.set_text (filename);
1297                 }
1298         }
1299 }