video-timeline tools path updates for OSX and Windows
[ardour.git] / gtk2_ardour / transcode_ffmpeg.cc
1 /*
2     Copyright (C) 2010-2013 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 <stdio.h>
21 #include <string.h>
22 #include <sstream>
23 #include <sys/types.h>
24
25 #include "pbd/error.h"
26 #include "pbd/convert.h"
27 #include "pbd/file_utils.h"
28 #include "gui_thread.h"
29
30 #include "transcode_ffmpeg.h"
31 #include "utils_videotl.h"
32
33 #ifdef PLATFORM_WINDOWS
34 #include <windows.h>
35 #include <shlobj.h> // CSIDL_*
36 #include "pbd/windows_special_dirs.h"
37 #endif
38
39 #include "i18n.h"
40
41 using namespace PBD;
42 using namespace VideoUtils;
43
44 TranscodeFfmpeg::TranscodeFfmpeg (std::string f)
45         : infile(f)
46 {
47         probeok = false;
48         ffexecok = false;
49         ffmpeg_exe = "";
50         ffprobe_exe = "";
51         m_duration = 0;
52         m_avoffset = m_lead_in = m_lead_out = 0;
53         m_width = m_height = 0;
54         m_aspect = m_fps = 0;
55         m_sar = "";
56 #if 1 /* tentative debug mode */
57         debug_enable = false;
58 #endif
59
60 #ifdef PLATFORM_WINDOWS
61         HKEY key;
62         DWORD size = PATH_MAX;
63         char tmp[PATH_MAX+1];
64         const char *program_files = PBD::get_win_special_folder (CSIDL_PROGRAM_FILES);
65 #endif
66
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;
70         }
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))
74                         )
75         {
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"));
78         }
79         if (Glib::file_test(ffmpeg_exe, Glib::FILE_TEST_EXISTS)) {
80                 ;
81         }
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);
84         }
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);
87         }
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");
91         }
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");
94         } else {
95                 ffmpeg_exe = X_("");
96         }
97 #endif
98
99         if (find_file (Searchpath(Glib::getenv("PATH")), X_("ffprobe_harvid"), ff_file_path)) {
100                 ffprobe_exe = ff_file_path;
101         }
102 #ifdef PLATFORM_WINDOWS
103         if (Glib::file_test(ffprobe_exe, Glib::FILE_TEST_EXISTS)) {
104                 ;
105         }
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);
108         }
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);
111         }
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");
115         }
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");
118         } else {
119                 ffprobe_exe = X_("");
120         }
121 #endif
122
123         if (ffmpeg_exe.empty() || ffprobe_exe.empty()) {
124                 warning << string_compose(
125                                 _(
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"
129                                         "\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"
132                                         "\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"
136                                         "\n"
137                                         "see also http://manual.ardour.org/video-timeline/setup/"
138                                  ), PROGRAM_NAME) << endmsg;
139                 return;
140         }
141         ffexecok = true;
142
143         if (infile.empty() || !probe()) {
144                 return;
145         }
146         probeok = true;
147 }
148
149 TranscodeFfmpeg::~TranscodeFfmpeg ()
150 {
151   ;
152 }
153
154 bool
155 TranscodeFfmpeg::probe ()
156 {
157         ffoutput = "";
158         char **argp;
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());
166         argp[6] = 0;
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)) {
171                 ffexit();
172                 return false;
173         }
174
175         /* wait for ffprobe process to exit */
176         ffcmd->wait();
177
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) {
182                 Glib::usleep(5000);
183         }
184         if (timeout == 0 || ffoutput.empty()) {
185                 return false;
186         }
187
188         /* parse */
189
190         std::vector<std::vector<std::string> > lines;
191         ParseCSV(ffoutput, lines);
192         double timebase = 0;
193         m_width = m_height = 0;
194         m_fps = m_aspect = 0;
195         m_duration = 0;
196         m_sar.clear();
197         m_codec.clear();
198         m_audio.clear();
199
200 #define PARSE_FRACTIONAL_FPS(VAR) \
201         { \
202                 std::string::size_type pos; \
203                 VAR = atof(value); \
204                 pos = value.find_first_of('/'); \
205                 if (pos != std::string::npos) { \
206                         VAR = atof(value.substr(0, pos)) / atof(value.substr(pos+1)); \
207                 } \
208         }
209
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 */
213                 } else
214                 if (i->at(0) == X_("stream")) {
215                         if (i->at(5) == X_("codec_type=video") && m_width == 0) {
216
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);
222
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 += " ";
231                                                 m_codec += value;
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 * (
248                                                                         h * 3600.0
249                                                                 + m * 60.0
250                                                                 + s * 1.0
251                                                                 + atoi(f) / pow((double)10, (int)strlen(f))
252                                                         ));
253                                                 }
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) {
262                                                         m_sar = value;
263                                                         m_sar.replace(pos, 1, "/");
264                                                 }
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));
270                                                 }
271                                         }
272                                 }
273
274                                 if (m_aspect == 0) {
275                                         m_aspect = (double)m_width / (double)m_height;
276                                 }
277
278                         } else if (i->at(5) == X_("codec_type=audio")) { /* new ffprobe */
279                                 FFAudioStream as;
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);
285
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 += " ";
292                                                 as.name += value;
293                                         } else if (key == X_("codec_name")) {
294                                                 if (!as.name.empty()) as.name += " ";
295                                                 as.name += value;
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;
302                                         }
303
304                                 }
305                                 m_audio.push_back(as);
306                         }
307                 }
308         }
309         /* end parse */
310
311 #if 0 /* DEBUG */
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);
320                 }
321         } else {
322           printf("audio: no audio streams in file.\n");
323         }
324 #endif
325
326         return true;
327 }
328
329 TranscodeFfmpeg::FFSettings
330 TranscodeFfmpeg::default_encoder_settings ()
331 {
332         TranscodeFfmpeg::FFSettings ffs;
333         ffs.clear();
334         ffs["-vcodec"] = "mpeg4";
335         ffs["-acodec"] = "ac3";
336         ffs["-b:v"] = "5000k";
337         ffs["-b:a"] = "160k";
338         return ffs;
339 }
340
341 TranscodeFfmpeg::FFSettings
342 TranscodeFfmpeg::default_meta_data ()
343 {
344         TranscodeFfmpeg::FFSettings ffm;
345         ffm.clear();
346         ffm["comment"] = "Created with ardour";
347         return ffm;
348 }
349
350 char *
351 TranscodeFfmpeg::format_metadata (std::string key, std::string value)
352 {
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)
358         {
359                 v1.replace(start_pos, 1, "_");
360                 start_pos += 1;
361         }
362
363         start_pos = 0;
364         while((start_pos = v1.find("\"", start_pos)) != std::string::npos) {
365                 v1.replace(start_pos, 1, "\\\"");
366                 start_pos += 2;
367         }
368
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());
372         return mds;
373 }
374
375 bool
376 TranscodeFfmpeg::encode (std::string outfile, std::string inf_a, std::string inf_v, TranscodeFfmpeg::FFSettings ffs, TranscodeFfmpeg::FFSettings meta, bool map)
377 {
378 #define MAX_FFMPEG_ENCODER_ARGS (100)
379         char **argp;
380         int a=0;
381
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());
388         }
389         argp[a++] = strdup("-i");
390         argp[a++] = strdup(inf_v.c_str());
391
392         argp[a++] = strdup("-i");
393         argp[a++] = strdup(inf_a.c_str());
394
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());
398         }
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());
402         }
403
404         if (m_fps > 0) {
405                 m_lead_in  = rint (m_lead_in * m_fps) / m_fps;
406                 m_lead_out = rint (m_lead_out * m_fps) / m_fps;
407         }
408
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());
436         }
437
438         if (map) {
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");
445         }
446
447         argp[a++] = strdup("-y");
448         argp[a++] = strdup(outfile.c_str());
449         argp[a] = (char *)0;
450         assert(a<MAX_FFMPEG_ENCODER_ARGS);
451         /* Note: these are free()d in ~SystemExec */
452 #if 1 /* DEBUG */
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]);
457         }
458         printf("\n");
459         }
460 #endif
461
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)) {
466                 ffexit();
467                 return false;
468         }
469         return true;
470 }
471
472 bool
473 TranscodeFfmpeg::extract_audio (std::string outfile, ARDOUR::framecnt_t /*samplerate*/, unsigned int stream)
474 {
475         if (!probeok) return false;
476   if (stream >= m_audio.size()) return false;
477
478         char **argp;
479         int i = 0;
480
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);
488 #endif
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 */
500 #if 1 /* DEBUG */
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]);
505         }
506         printf("\n");
507         }
508 #endif
509
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)) {
514                 ffexit();
515                 return false;
516         }
517         return true;
518 }
519
520
521 bool
522 TranscodeFfmpeg::transcode (std::string outfile, const int outw, const int outh, const int kbitps)
523 {
524         if (!probeok) return false;
525
526         char **argp;
527         int bitrate = kbitps;
528         int width = outw;
529         int height = outh;
530
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); }
533
534         if (bitrate == 0) {
535                 const double bitperpixel = .7; /* avg quality */
536                 bitrate = floor(m_fps * width * height * bitperpixel / 10000.0);
537         } else {
538                 bitrate = bitrate / 10;
539         }
540         if (bitrate < 10)  bitrate = 10;
541         if (bitrate > 1000) bitrate = 1000;
542
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 */
561 #if 1 /* DEBUG */
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]);
566         }
567         printf("\n");
568         }
569 #endif
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)) {
574                 ffexit();
575                 return false;
576         }
577         return true;
578 }
579
580 void
581 TranscodeFfmpeg::cancel ()
582 {
583         if (!ffcmd || !ffcmd->is_running()) { return;}
584         ffcmd->write_to_stdin("q");
585 #ifdef PLATFORM_WINDOWS
586         Sleep(1000);
587 #else
588         sleep (1);
589 #endif
590         if (ffcmd) {
591           ffcmd->terminate();
592         }
593 }
594
595 void
596 TranscodeFfmpeg::ffexit ()
597 {
598         delete ffcmd;
599         ffcmd=0;
600         Finished(); /* EMIT SIGNAL */
601 }
602
603 void
604 TranscodeFfmpeg::ffprobeparse (std::string d, size_t /* s */)
605 {
606         ffoutput+=d;
607 }
608
609 void
610 TranscodeFfmpeg::ffmpegparse_a (std::string d, size_t /* s */)
611 {
612         const char *t;
613         int h,m,s; char f[7];
614         ARDOUR::framecnt_t p = -1;
615
616         if (!(t=strstr(d.c_str(), "time="))) { return; }
617
618         if (sscanf(t+5, "%d:%d:%d.%s",&h,&m,&s,f) == 4) {
619                 p = (ARDOUR::framecnt_t) floor( 100.0 * (
620                       h * 3600.0
621                     + m * 60.0
622                     + s * 1.0
623                     + atoi(f) / pow((double)10, (int)strlen(f))
624                 ));
625                 p = p * m_fps / 100.0;
626                 if (p > m_duration ) { p = m_duration; }
627                 Progress(p, m_duration); /* EMIT SIGNAL */
628         } else {
629                 Progress(0, 0); /* EMIT SIGNAL */
630         }
631 }
632
633 void
634 TranscodeFfmpeg::ffmpegparse_v (std::string d, size_t /* s */)
635 {
636         if (strstr(d.c_str(), "ERROR") || strstr(d.c_str(), "Error") || strstr(d.c_str(), "error")) {
637                 warning << "ffmpeg-error: " << d << endmsg;
638         }
639         if (strncmp(d.c_str(), "frame=",6)) {
640 #if 1 /* DEBUG */
641                 if (debug_enable) {
642                         d.erase(d.find_last_not_of(" \t\r\n") + 1);
643                   printf("ffmpeg: '%s'\n", d.c_str());
644                 }
645 #endif
646                 Progress(0, 0); /* EMIT SIGNAL */
647                 return;
648         }
649         ARDOUR::framecnt_t f = atol(d.substr(6));
650         if (f == 0) {
651                 Progress(0, 0); /* EMIT SIGNAL */
652         } else {
653                 Progress(f, m_duration); /* EMIT SIGNAL */
654         }
655 }