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