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