Use LinkableValueNode members functions when possible in the derived valuenodes.
[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 #ifdef USING_PCH
30 #       include "pch.h"
31 #else
32 #ifdef HAVE_CONFIG_H
33 #       include <config.h>
34 #endif
35
36 #include <ETL/stringf>
37 #include "trgt_ffmpeg.h"
38 #include <stdio.h>
39 #include <sys/types.h>
40 #if HAVE_SYS_WAIT_H
41  #include <sys/wait.h>
42 #endif
43 #if HAVE_IO_H
44  #include <io.h>
45 #endif
46 #if HAVE_PROCESS_H
47  #include <process.h>
48 #endif
49 #if HAVE_FCNTL_H
50  #include <fcntl.h>
51 #endif
52 #include <unistd.h>
53 #include <algorithm>
54 #include <functional>
55 #include <ETL/clock>
56
57 #endif
58
59 /* === M A C R O S ========================================================= */
60
61 using namespace synfig;
62 using namespace std;
63 using namespace etl;
64
65 #if defined(HAVE_FORK) && defined(HAVE_PIPE) && defined(HAVE_WAITPID)
66  #define UNIX_PIPE_TO_PROCESSES
67 #else
68  #define WIN32_PIPE_TO_PROCESSES
69 #endif
70
71 /* === G L O B A L S ======================================================= */
72
73 SYNFIG_TARGET_INIT(ffmpeg_trgt);
74 SYNFIG_TARGET_SET_NAME(ffmpeg_trgt,"ffmpeg");
75 SYNFIG_TARGET_SET_EXT(ffmpeg_trgt,"mpg");
76 SYNFIG_TARGET_SET_VERSION(ffmpeg_trgt,"0.1");
77 SYNFIG_TARGET_SET_CVS_ID(ffmpeg_trgt,"$Id$");
78
79 /* === M E T H O D S ======================================================= */
80
81 ffmpeg_trgt::ffmpeg_trgt(const char *Filename,
82                                                  const synfig::TargetParam& params)
83 {
84         pid=-1;
85         file=NULL;
86         filename=Filename;
87         multi_image=false;
88         buffer=NULL;
89         color_buffer=0;
90         set_remove_alpha();
91
92         // Set default video codec and bitrate if they weren't given.
93         if (params.video_codec == "none")
94                 video_codec = "mpeg1video";
95         else
96                 video_codec = params.video_codec;
97
98         if (params.bitrate == -1)
99                 bitrate = 200;
100         else
101                 bitrate = params.bitrate;
102 }
103
104 ffmpeg_trgt::~ffmpeg_trgt()
105 {
106         if(file)
107         {
108                 etl::yield();
109                 sleep(1);
110 #if defined(WIN32_PIPE_TO_PROCESSES)
111                 pclose(file);
112 #elif defined(UNIX_PIPE_TO_PROCESSES)
113                 fclose(file);
114                 int status;
115                 waitpid(pid,&status,0);
116 #endif
117         }
118         file=NULL;
119         delete [] buffer;
120         delete [] color_buffer;
121 }
122
123 bool
124 ffmpeg_trgt::set_rend_desc(RendDesc *given_desc)
125 {
126         //given_desc->set_pixel_format(PF_RGB);
127
128         // Make sure that the width and height
129         // are multiples of 8
130         given_desc->set_w((given_desc->get_w()+4)/8*8);
131         given_desc->set_h((given_desc->get_h()+4)/8*8);
132
133         /*
134         // Valid framerates:
135         // 23.976, 24, 25, 29.97, 30, 50 ,59.94, 60
136         float fps=given_desc->get_frame_rate();
137         if(fps <24.0)
138                 given_desc->set_frame_rate(23.976);
139         if(fps>=24.0 && fps <25.0)
140                 given_desc->set_frame_rate(24);
141         if(fps>=25.0 && fps <29.97)
142                 given_desc->set_frame_rate(25);
143         if(fps>=29.97 && fps <30.0)
144                 given_desc->set_frame_rate(29.97);
145         if(fps>=29.97 && fps <30.0)
146                 given_desc->set_frame_rate(29.97);
147         if(fps>=30.0 && fps <50.0)
148                 given_desc->set_frame_rate(30.0);
149         if(fps>=50.0 && fps <59.94)
150                 given_desc->set_frame_rate(50);
151         if(fps>=59.94)
152                 given_desc->set_frame_rate(59.94);
153     */
154
155         desc=*given_desc;
156
157         return true;
158 }
159
160 bool
161 ffmpeg_trgt::init()
162 {
163         imagecount=desc.get_frame_start();
164         if(desc.get_frame_end()-desc.get_frame_start()>0)
165                 multi_image=true;
166
167 #if defined(WIN32_PIPE_TO_PROCESSES)
168
169         string command;
170
171         if( filename.c_str()[0] == '-' )
172                 command = strprintf("ffmpeg -f image2pipe -vcodec ppm -an"
173                                                         " -r %f -i pipe: -loop_input"
174                                                         " -metadata title=\"%s\" "
175                                                         " -vcodec %s -b %ik"
176                                                         " -y -- \"%s\"\n",
177                                                         desc.get_frame_rate(),
178                                                         get_canvas()->get_name().c_str(),
179                                                         video_codec.c_str(), bitrate,
180                                                         filename.c_str());
181         else
182                 command = strprintf("ffmpeg -f image2pipe -vcodec ppm -an"
183                                                         " -r %f -i pipe: -loop_input"
184                                                         " -metadata title=\"%s\" "
185                                                         "-vcodec %s -b %ik"
186                                                         " -y -- \"%s\"\n",
187                                                         desc.get_frame_rate(),
188                                                         get_canvas()->get_name().c_str(),
189                                                         video_codec.c_str(), bitrate,
190                                                         filename.c_str());
191
192         file=popen(command.c_str(),POPEN_BINARY_WRITE_TYPE);
193
194 #elif defined(UNIX_PIPE_TO_PROCESSES)
195
196         int p[2];
197
198         if (pipe(p)) {
199                 synfig::error(_("Unable to open pipe to ffmpeg"));
200                 return false;
201         };
202
203         pid = fork();
204
205         if (pid == -1) {
206                 synfig::error(_("Unable to open pipe to ffmpeg"));
207                 return false;
208         }
209
210         if (pid == 0){
211                 // Child process
212                 // Close pipeout, not needed
213                 close(p[1]);
214                 // Dup pipeout to stdin
215                 if( dup2( p[0], STDIN_FILENO ) == -1 ){
216                         synfig::error(_("Unable to open pipe to ffmpeg"));
217                         return false;
218                 }
219                 // Close the unneeded pipeout
220                 close(p[0]);
221                 if( filename.c_str()[0] == '-' )
222                 {
223                         // x264 codec needs -vpre hq parameters
224                         if (video_codec == "libx264")
225                                 execlp("ffmpeg", "ffmpeg", "-f", "image2pipe", "-vcodec",
226                                            "ppm", "-an", "-r",
227                                            strprintf("%f", desc.get_frame_rate()).c_str(),
228                                            "-i", "pipe:", "-loop_input", "-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                                                 "-vpre", "hq",
233                                                 "-y", "--", filename.c_str(), (const char *)NULL);
234                         else
235                                 execlp("ffmpeg", "ffmpeg", "-f", "image2pipe", "-vcodec",
236                                            "ppm", "-an", "-r",
237                                            strprintf("%f", desc.get_frame_rate()).c_str(),
238                                            "-i", "pipe:", "-loop_input", "-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                 else
245                 {
246                         if (video_codec == "libx264")
247                                 execlp("ffmpeg", "ffmpeg", "-f", "image2pipe", "-vcodec",
248                                            "ppm", "-an", "-r",
249                                            strprintf("%f", desc.get_frame_rate()).c_str(),
250                                            "-i", "pipe:", "-loop_input",
251                                            "-metadata",
252                                            strprintf("title=\"%s\"", get_canvas()->get_name().c_str()).c_str(),
253                                            "-vcodec", video_codec.c_str(),
254                                            "-b", strprintf("%ik", bitrate).c_str(),
255                                            "-vpre", "hq",
256                                            "-y", filename.c_str(), (const char *)NULL);
257                         else
258                                 execlp("ffmpeg", "ffmpeg", "-f", "image2pipe", "-vcodec",
259                                            "ppm", "-an", "-r",
260                                            strprintf("%f", desc.get_frame_rate()).c_str(),
261                                            "-i", "pipe:", "-loop_input",
262                                            "-metadata",
263                                            strprintf("title=\"%s\"", get_canvas()->get_name().c_str()).c_str(),
264                                            "-vcodec", video_codec.c_str(),
265                                            "-b", strprintf("%ik", bitrate).c_str(),
266                                            "-y", filename.c_str(), (const char *)NULL);
267                 }
268
269                 // We should never reach here unless the exec failed
270                 synfig::error(_("Unable to open pipe to ffmpeg"));
271                 return false;
272         } else {
273                 // Parent process
274                 // Close pipein, not needed
275                 close(p[0]);
276                 // Save pipeout to file handle, will write to it later
277                 file = fdopen(p[1], "wb");
278         }
279
280 #else
281         #error There are no known APIs for creating child processes
282 #endif
283
284         // etl::yield();
285
286         if(!file)
287         {
288                 synfig::error(_("Unable to open pipe to ffmpeg"));
289                 return false;
290         }
291
292         return true;
293 }
294
295 void
296 ffmpeg_trgt::end_frame()
297 {
298         //fprintf(file, " ");
299         fflush(file);
300         imagecount++;
301 }
302
303 bool
304 ffmpeg_trgt::start_frame(synfig::ProgressCallback */*callback*/)
305 {
306         int w=desc.get_w(),h=desc.get_h();
307
308         if(!file)
309                 return false;
310
311         fprintf(file, "P6\n");
312         fprintf(file, "%d %d\n", w, h);
313         fprintf(file, "%d\n", 255);
314
315         delete [] buffer;
316         buffer=new unsigned char[3*w];
317         delete [] color_buffer;
318         color_buffer=new Color[w];
319
320         return true;
321 }
322
323 Color *
324 ffmpeg_trgt::start_scanline(int /*scanline*/)
325 {
326         return color_buffer;
327 }
328
329 bool
330 ffmpeg_trgt::end_scanline()
331 {
332         if(!file)
333                 return false;
334
335         convert_color_format(buffer, color_buffer, desc.get_w(), PF_RGB, gamma());
336
337         if(!fwrite(buffer,1,desc.get_w()*3,file))
338                 return false;
339
340         return true;
341 }