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