FFMPEG module if needed parameter overriding.
[synfig.git] / synfig-core / src / modules / mod_ffmpeg / trgt_ffmpeg.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file trgt_ffmpeg.cpp
3 **      \brief ppm Target Module
4 **
5 **      $Id$
6 **
7 **      \legal
8 **      Copyright (c) 2002-2005 Robert B. Quattlebaum Jr., Adrian Bentley
9 **      Copyright (c) 2007 Chris Moore
10 **      Copyright (c) 2010 Diego Barrios Romero
11 **
12 **      This package is free software; you can redistribute it and/or
13 **      modify it under the terms of the GNU General Public License as
14 **      published by the Free Software Foundation; either version 2 of
15 **      the License, or (at your option) any later version.
16 **
17 **      This package is distributed in the hope that it will be useful,
18 **      but WITHOUT ANY WARRANTY; without even the implied warranty of
19 **      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 **      General Public License for more details.
21 **      \endlegal
22 **
23 ** === N O T E S ===========================================================
24 **
25 ** ========================================================================= */
26
27 /* === H E A D E R S ======================================================= */
28
29 #define SYNFIG_TARGET
30
31 #ifdef USING_PCH
32 #       include "pch.h"
33 #else
34 #ifdef HAVE_CONFIG_H
35 #       include <config.h>
36 #endif
37
38 #include <ETL/stringf>
39 #include "trgt_ffmpeg.h"
40 #include <stdio.h>
41 #include <sys/types.h>
42 #if HAVE_SYS_WAIT_H
43  #include <sys/wait.h>
44 #endif
45 #if HAVE_IO_H
46  #include <io.h>
47 #endif
48 #if HAVE_PROCESS_H
49  #include <process.h>
50 #endif
51 #if HAVE_FCNTL_H
52  #include <fcntl.h>
53 #endif
54 #include <unistd.h>
55 #include <algorithm>
56 #include <functional>
57 #include <ETL/clock>
58
59 #endif
60
61 /* === M A C R O S ========================================================= */
62
63 using namespace synfig;
64 using namespace std;
65 using namespace etl;
66
67 #if defined(HAVE_FORK) && defined(HAVE_PIPE) && defined(HAVE_WAITPID)
68  #define UNIX_PIPE_TO_PROCESSES
69 #else
70  #define WIN32_PIPE_TO_PROCESSES
71 #endif
72
73 /* === G L O B A L S ======================================================= */
74
75 SYNFIG_TARGET_INIT(ffmpeg_trgt);
76 SYNFIG_TARGET_SET_NAME(ffmpeg_trgt,"ffmpeg");
77 SYNFIG_TARGET_SET_EXT(ffmpeg_trgt,"mpg");
78 SYNFIG_TARGET_SET_VERSION(ffmpeg_trgt,"0.1");
79 SYNFIG_TARGET_SET_CVS_ID(ffmpeg_trgt,"$Id$");
80
81 /* === M E T H O D S ======================================================= */
82
83 ffmpeg_trgt::ffmpeg_trgt(const char *Filename,
84                                                  const synfig::TargetParam& params)
85 {
86         pid=-1;
87         file=NULL;
88         filename=Filename;
89         multi_image=false;
90         buffer=NULL;
91         color_buffer=0;
92         set_remove_alpha();
93
94         // Set default video codec and bitrate if they weren't given.
95         if (params.video_codec == "none")
96                 video_codec = "mpeg1video";
97         else
98                 video_codec = params.video_codec;
99
100         if (params.bitrate == -1)
101                 bitrate = 200;
102         else
103                 bitrate = params.bitrate;
104 }
105
106 ffmpeg_trgt::~ffmpeg_trgt()
107 {
108         if(file)
109         {
110                 etl::yield();
111                 sleep(1);
112 #if defined(WIN32_PIPE_TO_PROCESSES)
113                 pclose(file);
114 #elif defined(UNIX_PIPE_TO_PROCESSES)
115                 fclose(file);
116                 int status;
117                 waitpid(pid,&status,0);
118 #endif
119         }
120         file=NULL;
121         delete [] buffer;
122         delete [] color_buffer;
123 }
124
125 bool
126 ffmpeg_trgt::set_rend_desc(RendDesc *given_desc)
127 {
128         //given_desc->set_pixel_format(PF_RGB);
129
130         // Make sure that the width and height
131         // are multiples of 8
132         given_desc->set_w((given_desc->get_w()+4)/8*8);
133         given_desc->set_h((given_desc->get_h()+4)/8*8);
134
135         /*
136         // Valid framerates:
137         // 23.976, 24, 25, 29.97, 30, 50 ,59.94, 60
138         float fps=given_desc->get_frame_rate();
139         if(fps <24.0)
140                 given_desc->set_frame_rate(23.976);
141         if(fps>=24.0 && fps <25.0)
142                 given_desc->set_frame_rate(24);
143         if(fps>=25.0 && fps <29.97)
144                 given_desc->set_frame_rate(25);
145         if(fps>=29.97 && fps <30.0)
146                 given_desc->set_frame_rate(29.97);
147         if(fps>=29.97 && fps <30.0)
148                 given_desc->set_frame_rate(29.97);
149         if(fps>=30.0 && fps <50.0)
150                 given_desc->set_frame_rate(30.0);
151         if(fps>=50.0 && fps <59.94)
152                 given_desc->set_frame_rate(50);
153         if(fps>=59.94)
154                 given_desc->set_frame_rate(59.94);
155     */
156
157         desc=*given_desc;
158
159         return true;
160 }
161
162 bool
163 ffmpeg_trgt::init()
164 {
165         imagecount=desc.get_frame_start();
166         if(desc.get_frame_end()-desc.get_frame_start()>0)
167                 multi_image=true;
168
169 #if defined(WIN32_PIPE_TO_PROCESSES)
170
171         string command;
172
173         if( filename.c_str()[0] == '-' )
174                 command = strprintf("ffmpeg -f image2pipe -vcodec ppm -an"
175                                                         " -r %f -i pipe: -loop_input"
176                                                         " -metadata title=\"%s\" "
177                                                         " -vcodec %s -b %ik"
178                                                         " -y -- \"%s\"\n",
179                                                         desc.get_frame_rate(),
180                                                         get_canvas()->get_name().c_str(),
181                                                         video_codec.c_str(), bitrate,
182                                                         filename.c_str());
183         else
184                 command = strprintf("ffmpeg -f image2pipe -vcodec ppm -an"
185                                                         " -r %f -i pipe: -loop_input"
186                                                         " -metadata title=\"%s\" "
187                                                         "-vcodec %s -b %ik"
188                                                         " -y -- \"%s\"\n",
189                                                         desc.get_frame_rate(),
190                                                         get_canvas()->get_name().c_str(),
191                                                         video_codec.c_str(), bitrate,
192                                                         filename.c_str());
193
194         file=popen(command.c_str(),POPEN_BINARY_WRITE_TYPE);
195
196 #elif defined(UNIX_PIPE_TO_PROCESSES)
197
198         int p[2];
199
200         if (pipe(p)) {
201                 synfig::error(_("Unable to open pipe to ffmpeg"));
202                 return false;
203         };
204
205         pid = fork();
206
207         if (pid == -1) {
208                 synfig::error(_("Unable to open pipe to ffmpeg"));
209                 return false;
210         }
211
212         if (pid == 0){
213                 // Child process
214                 // Close pipeout, not needed
215                 close(p[1]);
216                 // Dup pipeout to stdin
217                 if( dup2( p[0], STDIN_FILENO ) == -1 ){
218                         synfig::error(_("Unable to open pipe to ffmpeg"));
219                         return false;
220                 }
221                 // Close the unneeded pipeout
222                 close(p[0]);
223                 if( filename.c_str()[0] == '-' )
224                         execlp("ffmpeg", "ffmpeg", "-f", "image2pipe", "-vcodec",
225                                    "ppm", "-an", "-r",
226                                    strprintf("%f", desc.get_frame_rate()).c_str(),
227                                    "-i", "pipe:", "-loop_input",
228                                    "-metadata",
229                                    strprintf("title=\"%s\"", get_canvas()->get_name().c_str()).c_str(),
230                                    "-vcodec", video_codec.c_str(),
231                                    "-b", strprintf("%ik", bitrate).c_str(),
232                                    "-y", "--", filename.c_str(), (const char *)NULL);
233                 else
234                         execlp("ffmpeg", "ffmpeg", "-f", "image2pipe", "-vcodec",
235                                    "ppm", "-an", "-r",
236                                    strprintf("%f", desc.get_frame_rate()).c_str(),
237                                    "-i", "pipe:", "-loop_input",
238                                    "-metadata",
239                                    strprintf("title=\"%s\"", get_canvas()->get_name().c_str()).c_str(),
240                                    "-vcodec", video_codec.c_str(),
241                                    "-b", strprintf("%ik", bitrate).c_str(),
242                                    "-y", filename.c_str(), (const char *)NULL);
243
244                 // We should never reach here unless the exec failed
245                 synfig::error(_("Unable to open pipe to ffmpeg"));
246                 return false;
247         } else {
248                 // Parent process
249                 // Close pipein, not needed
250                 close(p[0]);
251                 // Save pipeout to file handle, will write to it later
252                 file = fdopen(p[1], "wb");
253         }
254
255 #else
256         #error There are no known APIs for creating child processes
257 #endif
258
259         // etl::yield();
260
261         if(!file)
262         {
263                 synfig::error(_("Unable to open pipe to ffmpeg"));
264                 return false;
265         }
266
267         return true;
268 }
269
270 void
271 ffmpeg_trgt::end_frame()
272 {
273         //fprintf(file, " ");
274         fflush(file);
275         imagecount++;
276 }
277
278 bool
279 ffmpeg_trgt::start_frame(synfig::ProgressCallback */*callback*/)
280 {
281         int w=desc.get_w(),h=desc.get_h();
282
283         if(!file)
284                 return false;
285
286         fprintf(file, "P6\n");
287         fprintf(file, "%d %d\n", w, h);
288         fprintf(file, "%d\n", 255);
289
290         delete [] buffer;
291         buffer=new unsigned char[3*w];
292         delete [] color_buffer;
293         color_buffer=new Color[w];
294
295         return true;
296 }
297
298 Color *
299 ffmpeg_trgt::start_scanline(int /*scanline*/)
300 {
301         return color_buffer;
302 }
303
304 bool
305 ffmpeg_trgt::end_scanline()
306 {
307         if(!file)
308                 return false;
309
310         convert_color_format(buffer, color_buffer, desc.get_w(), PF_RGB, gamma());
311
312         if(!fwrite(buffer,1,desc.get_w()*3,file))
313                 return false;
314
315         return true;
316 }