2 Copyright (C) 2010-2013 Paul Davis
3 Author: Robin Gareus <robin@gareus.org>
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.
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.
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.
23 #include <sys/types.h>
25 #include "pbd/error.h"
26 #include "pbd/convert.h"
27 #include "pbd/file_utils.h"
28 #include "gui_thread.h"
30 #include "transcode_ffmpeg.h"
31 #include "utils_videotl.h"
33 #ifdef PLATFORM_WINDOWS
35 #include <shlobj.h> // CSIDL_*
36 #include "pbd/windows_special_dirs.h"
42 using namespace VideoUtils;
44 TranscodeFfmpeg::TranscodeFfmpeg (std::string f)
52 m_avoffset = m_lead_in = m_lead_out = 0;
53 m_width = m_height = 0;
56 #if 1 /* tentative debug mode */
60 #ifdef PLATFORM_WINDOWS
62 DWORD size = PATH_MAX;
64 const char *program_files = PBD::get_win_special_folder (CSIDL_PROGRAM_FILES);
67 std::string ff_file_path;
68 if (find_file (Searchpath(Glib::getenv("PATH")), X_("ffmpeg_harvid"), ff_file_path)) {
69 ffmpeg_exe = ff_file_path;
71 #ifdef PLATFORM_WINDOWS
72 else if ( (ERROR_SUCCESS == RegOpenKeyExA (HKEY_LOCAL_MACHINE, "Software\\RSS\\harvid", 0, KEY_READ, &key))
73 && (ERROR_SUCCESS == RegQueryValueExA (key, "Install_Dir", 0, NULL, reinterpret_cast<LPBYTE>(tmp), &size))
76 ffmpeg_exe = g_build_filename(Glib::locale_to_utf8(tmp).c_str(), X_("ffmpeg.exe"));
77 ffprobe_exe = g_build_filename(Glib::locale_to_utf8(tmp).c_str(), X_("ffprobe.exe"));
79 if (Glib::file_test(ffmpeg_exe, Glib::FILE_TEST_EXISTS)) {
82 else if (program_files && Glib::file_test(g_build_filename(program_files, "harvid", "ffmpeg.exe", 0), Glib::FILE_TEST_EXISTS)) {
83 ffmpeg_exe = g_build_filename(program_files, "harvid", "ffmpeg.exe", 0);
85 else if (program_files && Glib::file_test(g_build_filename(program_files, "ffmpeg", "ffmpeg.exe", 0), Glib::FILE_TEST_EXISTS)) {
86 ffmpeg_exe = g_build_filename(program_files, "harvid", "ffmpeg.exe", 0);
88 /* generic fallbacks to try */
89 else if (Glib::file_test(X_("C:\\Program Files\\harvid\\ffmpeg.exe"), Glib::FILE_TEST_EXISTS)) {
90 ffmpeg_exe = X_("C:\\Program Files\\harvid\\ffmpeg.exe");
92 else if (Glib::file_test(X_("C:\\Program Files\\ffmpeg\\ffmpeg.exe"), Glib::FILE_TEST_EXISTS)) {
93 ffmpeg_exe = X_("C:\\Program Files\\ffmpeg\\ffmpeg.exe");
99 if (find_file (Searchpath(Glib::getenv("PATH")), X_("ffprobe_harvid"), ff_file_path)) {
100 ffprobe_exe = ff_file_path;
102 #ifdef PLATFORM_WINDOWS
103 if (Glib::file_test(ffprobe_exe, Glib::FILE_TEST_EXISTS)) {
106 else if (program_files && Glib::file_test(g_build_filename(program_files, "harvid", "ffprobe.exe", 0), Glib::FILE_TEST_EXISTS)) {
107 ffmpeg_exe = g_build_filename(program_files, "harvid", "ffprobe.exe", 0);
109 else if (program_files && Glib::file_test(g_build_filename(program_files, "ffmpeg", "ffprobe.exe", 0), Glib::FILE_TEST_EXISTS)) {
110 ffmpeg_exe = g_build_filename(program_files, "harvid", "ffprobe.exe", 0);
112 /* generic fallbacks to try */
113 else if (Glib::file_test(X_("C:\\Program Files\\harvid\\ffprobe.exe"), Glib::FILE_TEST_EXISTS)) {
114 ffprobe_exe = X_("C:\\Program Files\\harvid\\ffprobe.exe");
116 else if (Glib::file_test(X_("C:\\Program Files\\ffmpeg\\ffprobe.exe"), Glib::FILE_TEST_EXISTS)) {
117 ffprobe_exe = X_("C:\\Program Files\\ffmpeg\\ffprobe.exe");
119 ffprobe_exe = X_("");
123 if (ffmpeg_exe.empty() || ffprobe_exe.empty()) {
124 warning << string_compose(
126 "No ffprobe or ffmpeg executables could be found on this system.\n"
127 "Video import and export is not possible until you install those tools.\n"
128 "%1 requires ffmpeg and ffprobe from ffmpeg.org - version 1.1 or newer.\n"
130 "The tools are included with the %1 releases from ardour.org "
131 "and also available with the video-server at http://x42.github.com/harvid/\n"
133 "Important: the files need to be installed in $PATH and named ffmpeg_harvid and ffprobe_harvid.\n"
134 "If you already have a suitable ffmpeg installation on your system, we recommend creating "
135 "symbolic links from ffmpeg to ffmpeg_harvid and from ffprobe to ffprobe_harvid.\n"
137 "see also http://manual.ardour.org/video-timeline/setup/"
138 ), PROGRAM_NAME) << endmsg;
143 if (infile.empty() || !probe()) {
149 TranscodeFfmpeg::~TranscodeFfmpeg ()
155 TranscodeFfmpeg::probe ()
159 argp=(char**) calloc(7,sizeof(char*));
160 argp[0] = strdup(ffprobe_exe.c_str());
161 argp[1] = strdup("-print_format");
162 argp[2] = strdup("csv=nk=0");
163 argp[3] = strdup("-show_format");
164 argp[4] = strdup("-show_streams");
165 argp[5] = strdup(infile.c_str());
167 ffcmd = new ARDOUR::SystemExec(ffprobe_exe, argp);
168 ffcmd->ReadStdout.connect_same_thread (*this, boost::bind (&TranscodeFfmpeg::ffprobeparse, this, _1 ,_2));
169 ffcmd->Terminated.connect_same_thread (*this, boost::bind (&TranscodeFfmpeg::ffexit, this));
170 if (ffcmd->start(1)) {
175 /* wait for ffprobe process to exit */
178 /* wait for interposer thread to copy all data.
179 * SystemExec::Terminated is emitted and ffcmd set to NULL */
180 int timeout = 300; // 1.5 sec
181 while (ffcmd && --timeout > 0) {
184 if (timeout == 0 || ffoutput.empty()) {
190 std::vector<std::vector<std::string> > lines;
191 ParseCSV(ffoutput, lines);
193 m_width = m_height = 0;
194 m_fps = m_aspect = 0;
200 #define PARSE_FRACTIONAL_FPS(VAR) \
202 std::string::size_type pos; \
204 pos = value.find_first_of('/'); \
205 if (pos != std::string::npos) { \
206 VAR = atof(value.substr(0, pos)) / atof(value.substr(pos+1)); \
210 for (std::vector<std::vector<std::string> >::iterator i = lines.begin(); i != lines.end(); ++i) {
211 if (i->at(0) == X_("format")) {
212 /* format,filename,#streams,format-name,format-long-name,start-time,duration,size,bitrate */
214 if (i->at(0) == X_("stream")) {
215 if (i->at(5) == X_("codec_type=video") && m_width == 0) {
217 for (std::vector<std::string>::iterator kv = i->begin(); kv != i->end(); ++kv) {
218 const size_t kvsep = kv->find('=');
219 if(kvsep == std::string::npos) continue;
220 std::string key = kv->substr(0, kvsep);
221 std::string value = kv->substr(kvsep + 1);
223 if (key == X_("index")) {
224 m_videoidx = atoi(value);
225 } else if (key == X_("width")) {
226 m_width = atoi(value);
227 } else if (key == X_("height")) {
228 m_height = atoi(value);
229 } else if (key == X_("codec_name")) {
230 if (!m_codec.empty()) m_codec += " ";
232 } else if (key == X_("codec_long_name")) {
233 if (!m_codec.empty()) m_codec += " ";
234 m_codec += "[" + value + "]";
235 } else if (key == X_("codec_tag_string")) {
236 if (!m_codec.empty()) m_codec += " ";
237 m_codec += "(" + value + ")";
238 } else if (key == X_("r_frame_rate")) {
239 PARSE_FRACTIONAL_FPS(m_fps)
240 } else if (key == X_("avg_frame_rate") && m_fps == 0) {
241 PARSE_FRACTIONAL_FPS(m_fps)
242 } else if (key == X_("time_base")) {
243 PARSE_FRACTIONAL_FPS(timebase)
244 } else if (key == X_("timecode") && m_duration == 0) {
245 int h,m,s; char f[7];
246 if (sscanf(i->at(16).c_str(), "%d:%d:%d:%s",&h,&m,&s,f) == 4) {
247 m_duration = (ARDOUR::framecnt_t) floor(m_fps * (
251 + atoi(f) / pow((double)10, (int)strlen(f))
254 } else if (key == X_("duration_ts") && m_fps == 0 && timebase !=0 ) {
255 m_duration = atof(value) * m_fps * timebase;
256 } else if (key == X_("duration") && m_fps != 0 && m_duration == 0) {
257 m_duration = atof(value) * m_fps;
258 } else if (key == X_("sample_aspect_ratio")) {
259 std::string::size_type pos;
260 pos = value.find_first_of(':');
261 if (pos != std::string::npos && atof(value.substr(pos+1)) != 0) {
263 m_sar.replace(pos, 1, "/");
265 } else if (key == X_("display_aspect_ratio")) {
266 std::string::size_type pos;
267 pos = value.find_first_of(':');
268 if (pos != std::string::npos && atof(value.substr(pos+1)) != 0) {
269 m_aspect = atof(value.substr(0, pos)) / atof(value.substr(pos+1));
275 m_aspect = (double)m_width / (double)m_height;
278 } else if (i->at(5) == X_("codec_type=audio")) { /* new ffprobe */
280 for (std::vector<std::string>::iterator kv = i->begin(); kv != i->end(); ++kv) {
281 const size_t kvsep = kv->find('=');
282 if(kvsep == std::string::npos) continue;
283 std::string key = kv->substr(0, kvsep);
284 std::string value = kv->substr(kvsep + 1);
286 if (key == X_("channels")) {
287 as.channels = atoi(value);
288 } else if (key == X_("index")) {
289 as.stream_id = value;
290 } else if (key == X_("codec_long_name")) {
291 if (!as.name.empty()) as.name += " ";
293 } else if (key == X_("codec_name")) {
294 if (!as.name.empty()) as.name += " ";
296 } else if (key == X_("sample_fmt")) {
297 if (!as.name.empty()) as.name += " ";
298 as.name += "FMT:" + value;
299 } else if (key == X_("sample_rate")) {
300 if (!as.name.empty()) as.name += " ";
301 as.name += "SR:" + value;
305 m_audio.push_back(as);
312 printf("FPS: %f\n", m_fps);
313 printf("Duration: %lu frames\n",(unsigned long)m_duration);
314 printf("W/H: %ix%i\n",m_width, m_height);
315 printf("aspect: %f\n",m_aspect);
316 printf("codec: %s\n",m_codec.c_str());
317 if (m_audio.size() > 0) {
318 for (AudioStreams::iterator it = m_audio.begin(); it < m_audio.end(); ++it) {
319 printf("audio: %s - %i channels\n",(*it).stream_id.c_str(), (*it).channels);
322 printf("audio: no audio streams in file.\n");
329 TranscodeFfmpeg::FFSettings
330 TranscodeFfmpeg::default_encoder_settings ()
332 TranscodeFfmpeg::FFSettings ffs;
334 ffs["-vcodec"] = "mpeg4";
335 ffs["-acodec"] = "ac3";
336 ffs["-b:v"] = "5000k";
337 ffs["-b:a"] = "160k";
341 TranscodeFfmpeg::FFSettings
342 TranscodeFfmpeg::default_meta_data ()
344 TranscodeFfmpeg::FFSettings ffm;
346 ffm["comment"] = "Created with ardour";
351 TranscodeFfmpeg::format_metadata (std::string key, std::string value)
353 size_t start_pos = 0;
354 std::string v1 = value;
355 while((start_pos = v1.find_first_not_of(
356 "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789(),.\"'",
357 start_pos)) != std::string::npos)
359 v1.replace(start_pos, 1, "_");
364 while((start_pos = v1.find("\"", start_pos)) != std::string::npos) {
365 v1.replace(start_pos, 1, "\\\"");
369 size_t len = key.length() + v1.length() + 4;
370 char *mds = (char*) calloc(len, sizeof(char));
371 snprintf(mds, len, "%s=\"%s\"", key.c_str(), v1.c_str());
376 TranscodeFfmpeg::encode (std::string outfile, std::string inf_a, std::string inf_v, TranscodeFfmpeg::FFSettings ffs, TranscodeFfmpeg::FFSettings meta, bool map)
378 #define MAX_FFMPEG_ENCODER_ARGS (100)
382 argp=(char**) calloc(MAX_FFMPEG_ENCODER_ARGS,sizeof(char*));
383 argp[a++] = strdup(ffmpeg_exe.c_str());
384 if (m_avoffset < 0 || m_avoffset > 0) {
385 std::ostringstream osstream; osstream << m_avoffset;
386 argp[a++] = strdup("-itsoffset");
387 argp[a++] = strdup(osstream.str().c_str());
389 argp[a++] = strdup("-i");
390 argp[a++] = strdup(inf_v.c_str());
392 argp[a++] = strdup("-i");
393 argp[a++] = strdup(inf_a.c_str());
395 for(TranscodeFfmpeg::FFSettings::const_iterator it = ffs.begin(); it != ffs.end(); ++it) {
396 argp[a++] = strdup(it->first.c_str());
397 argp[a++] = strdup(it->second.c_str());
399 for(TranscodeFfmpeg::FFSettings::const_iterator it = meta.begin(); it != meta.end(); ++it) {
400 argp[a++] = strdup("-metadata");
401 argp[a++] = format_metadata(it->first.c_str(), it->second.c_str());
405 m_lead_in = rint (m_lead_in * m_fps) / m_fps;
406 m_lead_out = rint (m_lead_out * m_fps) / m_fps;
409 if (m_lead_in != 0 && m_lead_out != 0) {
410 std::ostringstream osstream;
411 argp[a++] = strdup("-vf");
412 osstream << X_("color=c=black:s=") << m_width << X_("x") << m_height << X_(":d=") << m_lead_in;
413 if (!m_sar.empty()) osstream << X_(":sar=") << m_sar;
414 osstream << X_(" [pre]; ");
415 osstream << X_("color=c=black:s=") << m_width << X_("x") << m_height << X_(":d=") << m_lead_out;
416 if (!m_sar.empty()) osstream << X_(":sar=") << m_sar;
417 osstream << X_(" [post]; ");
418 osstream << X_("[pre] [in] [post] concat=n=3");
419 argp[a++] = strdup(osstream.str().c_str());
420 } else if (m_lead_in != 0) {
421 std::ostringstream osstream;
422 argp[a++] = strdup("-vf");
423 osstream << X_("color=c=black:s=") << m_width << X_("x") << m_height << X_(":d=") << m_lead_in;
424 if (!m_sar.empty()) osstream << X_(":sar=") << m_sar;
425 osstream << X_(" [pre]; ");
426 osstream << X_("[pre] [in] concat=n=2");
427 argp[a++] = strdup(osstream.str().c_str());
428 } else if (m_lead_out != 0) {
429 std::ostringstream osstream;
430 argp[a++] = strdup("-vf");
431 osstream << X_("color=c=black:s=") << m_width << X_("x") << m_height << X_(":d=") << m_lead_out;
432 if (!m_sar.empty()) osstream << X_(":sar=") << m_sar;
433 osstream << X_(" [post]; ");
434 osstream << X_("[in] [post] concat=n=2");
435 argp[a++] = strdup(osstream.str().c_str());
439 std::ostringstream osstream;
440 argp[a++] = strdup("-map");
441 osstream << X_("0:") << m_videoidx;
442 argp[a++] = strdup(osstream.str().c_str());
443 argp[a++] = strdup("-map");
444 argp[a++] = strdup("1:0");
447 argp[a++] = strdup("-y");
448 argp[a++] = strdup(outfile.c_str());
450 assert(a<MAX_FFMPEG_ENCODER_ARGS);
451 /* Note: these are free()d in ~SystemExec */
453 if (debug_enable) { /* tentative debug mode */
454 printf("EXPORT ENCODE:\n");
455 for (int i=0; i< a; ++i) {
456 printf("%s ", argp[i]);
462 ffcmd = new ARDOUR::SystemExec(ffmpeg_exe, argp);
463 ffcmd->ReadStdout.connect_same_thread (*this, boost::bind (&TranscodeFfmpeg::ffmpegparse_v, this, _1 ,_2));
464 ffcmd->Terminated.connect_same_thread (*this, boost::bind (&TranscodeFfmpeg::ffexit, this));
465 if (ffcmd->start(2)) {
473 TranscodeFfmpeg::extract_audio (std::string outfile, ARDOUR::framecnt_t /*samplerate*/, unsigned int stream)
475 if (!probeok) return false;
476 if (stream >= m_audio.size()) return false;
481 argp=(char**) calloc(15,sizeof(char*));
482 argp[i++] = strdup(ffmpeg_exe.c_str());
483 argp[i++] = strdup("-i");
484 argp[i++] = strdup(infile.c_str());
485 #if 0 /* ffmpeg write original samplerate, use a3/SRC to resample */
486 argp[i++] = strdup("-ar");
487 argp[i] = (char*) calloc(7,sizeof(char)); snprintf(argp[i++], 7, "%"PRId64, samplerate);
489 argp[i++] = strdup("-ac");
490 argp[i] = (char*) calloc(3,sizeof(char)); snprintf(argp[i++], 3, "%i", m_audio.at(stream).channels);
491 argp[i++] = strdup("-map");
492 argp[i] = (char*) calloc(8,sizeof(char)); snprintf(argp[i++], 8, "0:%s", m_audio.at(stream).stream_id.c_str());
493 argp[i++] = strdup("-vn");
494 argp[i++] = strdup("-acodec");
495 argp[i++] = strdup("pcm_f32le");
496 argp[i++] = strdup("-y");
497 argp[i++] = strdup(outfile.c_str());
498 argp[i++] = (char *)0;
499 /* Note: argp is free()d in ~SystemExec */
501 if (debug_enable) { /* tentative debug mode */
502 printf("EXTRACT AUDIO:\n");
503 for (int i=0; i< 14; ++i) {
504 printf("%s ", argp[i]);
510 ffcmd = new ARDOUR::SystemExec(ffmpeg_exe, argp);
511 ffcmd->ReadStdout.connect_same_thread (*this, boost::bind (&TranscodeFfmpeg::ffmpegparse_a, this, _1 ,_2));
512 ffcmd->Terminated.connect_same_thread (*this, boost::bind (&TranscodeFfmpeg::ffexit, this));
513 if (ffcmd->start(2)) {
522 TranscodeFfmpeg::transcode (std::string outfile, const int outw, const int outh, const int kbitps)
524 if (!probeok) return false;
527 int bitrate = kbitps;
531 if (width < 1 || width > m_width) { width = m_width; } /* don't allow upscaling */
532 if (height < 1 || height > m_height) { height = floor(width / m_aspect); }
535 const double bitperpixel = .7; /* avg quality */
536 bitrate = floor(m_fps * width * height * bitperpixel / 10000.0);
538 bitrate = bitrate / 10;
540 if (bitrate < 10) bitrate = 10;
541 if (bitrate > 1000) bitrate = 1000;
543 argp=(char**) calloc(16,sizeof(char*));
544 argp[0] = strdup(ffmpeg_exe.c_str());
545 argp[1] = strdup("-i");
546 argp[2] = strdup(infile.c_str());
547 argp[3] = strdup("-b:v");
548 argp[4] = (char*) calloc(7,sizeof(char)); snprintf(argp[4], 7, "%i0k", bitrate);
549 argp[5] = strdup("-s");
550 argp[6] = (char*) calloc(10,sizeof(char)); snprintf(argp[6], 10, "%ix%i", width, height);
551 argp[7] = strdup("-y");
552 argp[8] = strdup("-vcodec");
553 argp[9] = strdup("mjpeg");
554 argp[10] = strdup("-an");
555 argp[11] = strdup("-intra");
556 argp[12] = strdup("-g");
557 argp[13] = strdup("1");
558 argp[14] = strdup(outfile.c_str());
559 argp[15] = (char *)0;
560 /* Note: these are free()d in ~SystemExec */
562 if (debug_enable) { /* tentative debug mode */
563 printf("TRANSCODE VIDEO:\n");
564 for (int i=0; i< 15; ++i) {
565 printf("%s ", argp[i]);
570 ffcmd = new ARDOUR::SystemExec(ffmpeg_exe, argp);
571 ffcmd->ReadStdout.connect_same_thread (*this, boost::bind (&TranscodeFfmpeg::ffmpegparse_v, this, _1 ,_2));
572 ffcmd->Terminated.connect_same_thread (*this, boost::bind (&TranscodeFfmpeg::ffexit, this));
573 if (ffcmd->start(2)) {
581 TranscodeFfmpeg::cancel ()
583 if (!ffcmd || !ffcmd->is_running()) { return;}
584 ffcmd->write_to_stdin("q");
585 #ifdef PLATFORM_WINDOWS
596 TranscodeFfmpeg::ffexit ()
600 Finished(); /* EMIT SIGNAL */
604 TranscodeFfmpeg::ffprobeparse (std::string d, size_t /* s */)
610 TranscodeFfmpeg::ffmpegparse_a (std::string d, size_t /* s */)
613 int h,m,s; char f[7];
614 ARDOUR::framecnt_t p = -1;
616 if (!(t=strstr(d.c_str(), "time="))) { return; }
618 if (sscanf(t+5, "%d:%d:%d.%s",&h,&m,&s,f) == 4) {
619 p = (ARDOUR::framecnt_t) floor( 100.0 * (
623 + atoi(f) / pow((double)10, (int)strlen(f))
625 p = p * m_fps / 100.0;
626 if (p > m_duration ) { p = m_duration; }
627 Progress(p, m_duration); /* EMIT SIGNAL */
629 Progress(0, 0); /* EMIT SIGNAL */
634 TranscodeFfmpeg::ffmpegparse_v (std::string d, size_t /* s */)
636 if (strstr(d.c_str(), "ERROR") || strstr(d.c_str(), "Error") || strstr(d.c_str(), "error")) {
637 warning << "ffmpeg-error: " << d << endmsg;
639 if (strncmp(d.c_str(), "frame=",6)) {
642 d.erase(d.find_last_not_of(" \t\r\n") + 1);
643 printf("ffmpeg: '%s'\n", d.c_str());
646 Progress(0, 0); /* EMIT SIGNAL */
649 ARDOUR::framecnt_t f = atol(d.substr(6));
651 Progress(0, 0); /* EMIT SIGNAL */
653 Progress(f, m_duration); /* EMIT SIGNAL */