Merge branch 'nikitakit_master'
[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                 {
225                         // x264 codec needs -vpre hq parameters
226                         if (video_codec == "libx264")
227                                 execlp("ffmpeg", "ffmpeg", "-f", "image2pipe", "-vcodec",
228                                            "ppm", "-an", "-r",
229                                            strprintf("%f", desc.get_frame_rate()).c_str(),
230                                            "-i", "pipe:", "-loop_input", "-metadata",
231                                                 strprintf("title=\"%s\"", get_canvas()->get_name().c_str()).c_str(),
232                                                 "-vcodec", video_codec.c_str(),
233                                                 "-b", strprintf("%ik", bitrate).c_str(),
234                                                 "-vpre", "hq",
235                                                 "-y", "--", filename.c_str(), (const char *)NULL);
236                         else
237                                 execlp("ffmpeg", "ffmpeg", "-f", "image2pipe", "-vcodec",
238                                            "ppm", "-an", "-r",
239                                            strprintf("%f", desc.get_frame_rate()).c_str(),
240                                            "-i", "pipe:", "-loop_input", "-metadata",
241                                                 strprintf("title=\"%s\"", get_canvas()->get_name().c_str()).c_str(),
242                                                 "-vcodec", video_codec.c_str(),
243                                                 "-b", strprintf("%ik", bitrate).c_str(),
244                                                 "-y", "--", filename.c_str(), (const char *)NULL);
245                 }
246                 else
247                 {
248                         if (video_codec == "libx264")
249                                 execlp("ffmpeg", "ffmpeg", "-f", "image2pipe", "-vcodec",
250                                            "ppm", "-an", "-r",
251                                            strprintf("%f", desc.get_frame_rate()).c_str(),
252                                            "-i", "pipe:", "-loop_input",
253                                            "-metadata",
254                                            strprintf("title=\"%s\"", get_canvas()->get_name().c_str()).c_str(),
255                                            "-vcodec", video_codec.c_str(),
256                                            "-b", strprintf("%ik", bitrate).c_str(),
257                                            "-vpre", "hq",
258                                            "-y", filename.c_str(), (const char *)NULL);
259                         else
260                                 execlp("ffmpeg", "ffmpeg", "-f", "image2pipe", "-vcodec",
261                                            "ppm", "-an", "-r",
262                                            strprintf("%f", desc.get_frame_rate()).c_str(),
263                                            "-i", "pipe:", "-loop_input",
264                                            "-metadata",
265                                            strprintf("title=\"%s\"", get_canvas()->get_name().c_str()).c_str(),
266                                            "-vcodec", video_codec.c_str(),
267                                            "-b", strprintf("%ik", bitrate).c_str(),
268                                            "-y", filename.c_str(), (const char *)NULL);
269                 }
270
271                 // We should never reach here unless the exec failed
272                 synfig::error(_("Unable to open pipe to ffmpeg"));
273                 return false;
274         } else {
275                 // Parent process
276                 // Close pipein, not needed
277                 close(p[0]);
278                 // Save pipeout to file handle, will write to it later
279                 file = fdopen(p[1], "wb");
280         }
281
282 #else
283         #error There are no known APIs for creating child processes
284 #endif
285
286         // etl::yield();
287
288         if(!file)
289         {
290                 synfig::error(_("Unable to open pipe to ffmpeg"));
291                 return false;
292         }
293
294         return true;
295 }
296
297 void
298 ffmpeg_trgt::end_frame()
299 {
300         //fprintf(file, " ");
301         fflush(file);
302         imagecount++;
303 }
304
305 bool
306 ffmpeg_trgt::start_frame(synfig::ProgressCallback */*callback*/)
307 {
308         int w=desc.get_w(),h=desc.get_h();
309
310         if(!file)
311                 return false;
312
313         fprintf(file, "P6\n");
314         fprintf(file, "%d %d\n", w, h);
315         fprintf(file, "%d\n", 255);
316
317         delete [] buffer;
318         buffer=new unsigned char[3*w];
319         delete [] color_buffer;
320         color_buffer=new Color[w];
321
322         return true;
323 }
324
325 Color *
326 ffmpeg_trgt::start_scanline(int /*scanline*/)
327 {
328         return color_buffer;
329 }
330
331 bool
332 ffmpeg_trgt::end_scanline()
333 {
334         if(!file)
335                 return false;
336
337         convert_color_format(buffer, color_buffer, desc.get_w(), PF_RGB, gamma());
338
339         if(!fwrite(buffer,1,desc.get_w()*3,file))
340                 return false;
341
342         return true;
343 }