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