Port the security fixes to Windows. Thanks to PXEGeek for much patience and testing...
[synfig.git] / synfig-core / trunk / 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 **
10 **      This package is free software; you can redistribute it and/or
11 **      modify it under the terms of the GNU General Public License as
12 **      published by the Free Software Foundation; either version 2 of
13 **      the License, or (at your option) any later version.
14 **
15 **      This package is distributed in the hope that it will be useful,
16 **      but WITHOUT ANY WARRANTY; without even the implied warranty of
17 **      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 **      General Public License for more details.
19 **      \endlegal
20 **
21 ** === N O T E S ===========================================================
22 **
23 ** ========================================================================= */
24
25 /* === H E A D E R S ======================================================= */
26
27 #define SYNFIG_TARGET
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 #elif defined(HAVE__SPAWNLP) && defined(HAVE__PIPE) && defined(HAVE_CWAIT)
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 {
83         pid=-1;
84         file=NULL;
85         filename=Filename;
86         multi_image=false;
87         buffer=NULL;
88         color_buffer=0;
89         set_remove_alpha();
90 }
91
92 ffmpeg_trgt::~ffmpeg_trgt()
93 {
94         if(file)
95         {
96                 etl::yield();
97                 sleep(1);
98                 fclose(file);
99                 int status;
100 #if defined(WIN32_PIPE_TO_PROCESSES)
101                 cwait(&status,pid,0);
102 #elif defined(UNIX_PIPE_TO_PROCESSES)
103                 waitpid(pid,&status,0);
104 #endif
105         }
106         file=NULL;
107         delete [] buffer;
108         delete [] color_buffer;
109 }
110
111 bool
112 ffmpeg_trgt::set_rend_desc(RendDesc *given_desc)
113 {
114         //given_desc->set_pixel_format(PF_RGB);
115
116         // Make sure that the width and height
117         // are multiples of 8
118         given_desc->set_w((given_desc->get_w()+4)/8*8);
119         given_desc->set_h((given_desc->get_h()+4)/8*8);
120
121         /*
122         // Valid framerates:
123         // 23.976, 24, 25, 29.97, 30, 50 ,59.94, 60
124         float fps=given_desc->get_frame_rate();
125         if(fps <24.0)
126                 given_desc->set_frame_rate(23.976);
127         if(fps>=24.0 && fps <25.0)
128                 given_desc->set_frame_rate(24);
129         if(fps>=25.0 && fps <29.97)
130                 given_desc->set_frame_rate(25);
131         if(fps>=29.97 && fps <30.0)
132                 given_desc->set_frame_rate(29.97);
133         if(fps>=29.97 && fps <30.0)
134                 given_desc->set_frame_rate(29.97);
135         if(fps>=30.0 && fps <50.0)
136                 given_desc->set_frame_rate(30.0);
137         if(fps>=50.0 && fps <59.94)
138                 given_desc->set_frame_rate(50);
139         if(fps>=59.94)
140                 given_desc->set_frame_rate(59.94);
141     */
142
143         desc=*given_desc;
144
145         return true;
146 }
147
148 bool
149 ffmpeg_trgt::init()
150 {
151         imagecount=desc.get_frame_start();
152         if(desc.get_frame_end()-desc.get_frame_start()>0)
153                 multi_image=true;
154
155 #if defined(WIN32_PIPE_TO_PROCESSES)
156
157         int p[2];
158         int stdin_fileno, stdout_fileno;
159
160         if(_pipe(p, 512, O_BINARY | O_NOINHERIT) < 0) {
161                 synfig::error(_("Unable to open pipe to ffmpeg"));
162                 return false;
163         }
164
165         // Save stdin/stdout so we can restore them later
166         stdin_fileno  = _dup(_fileno(stdin));
167         stdout_fileno = _dup(_fileno(stdout));
168
169         // ffmpeg should read from the pipe
170         if(_dup2(p[0], _fileno(stdin)) != 0) {
171                 synfig::error(_("Unable to open pipe to ffmpeg"));
172                 return false;
173         }
174
175         /*
176         ffmpeg accepts the output filename on the command-line
177         if(_dup2(_fileno(output), _fileno(stdout)) != 0) {
178                 synfig::error(_("Unable to open pipe to ffmpeg"));
179                 return false;
180         }
181         */
182
183         if( filename.c_str()[0] == '-' )
184                 pid = _spawnlp(_P_NOWAIT, "ffmpeg", "ffmpeg", "-f", "image2pipe", "-vcodec", "ppm", "-an", "-r", strprintf("%f", desc.get_frame_rate()).c_str(), "-i", "pipe:", "-loop", "-hq", "-title", get_canvas()->get_name().c_str(), "-vcodec", "mpeg1video", "-y", "--", filename.c_str(), (const char *)NULL);
185         else
186                 pid = _spawnlp(_P_NOWAIT, "ffmpeg", "ffmpeg", "-f", "image2pipe", "-vcodec", "ppm", "-an", "-r", strprintf("%f", desc.get_frame_rate()).c_str(), "-i", "pipe:", "-loop", "-hq", "-title", get_canvas()->get_name().c_str(), "-vcodec", "mpeg1video", "-y", filename.c_str(), (const char *)NULL);
187
188         if( pid < 0) {
189                 synfig::error(_("Unable to open pipe to ffmpeg"));
190                 return false;
191         }
192
193         // Restore stdin/stdout
194         if(_dup2(stdin_fileno, _fileno(stdin)) != 0) {
195                 synfig::error(_("Unable to open pipe to ffmpeg"));
196                 return false;
197         }
198         if(_dup2(stdout_fileno, _fileno(stdout)) != 0) {
199                 synfig::error(_("Unable to open pipe to ffmpeg"));
200                 return false;
201         }
202         close(stdin_fileno);
203         close(stdout_fileno);
204
205         // Close the pipe read end - ffmpeg uses it
206         close(p[0]);
207         
208         // We write data to the write end of the pipe
209         file = fdopen(p[1], "wb");
210
211 #elif defined(UNIX_PIPE_TO_PROCESSES)
212
213         int p[2];
214   
215         if (pipe(p)) {
216                 synfig::error(_("Unable to open pipe to ffmpeg"));
217                 return false;
218         };
219   
220         pid = fork();
221   
222         if (pid == -1) {
223                 synfig::error(_("Unable to open pipe to ffmpeg"));
224                 return false;
225         }
226   
227         if (pid == 0){
228                 // Child process
229                 // Close pipeout, not needed
230                 close(p[1]);
231                 // Dup pipeout to stdin
232                 if( dup2( p[0], STDIN_FILENO ) == -1 ){
233                         synfig::error(_("Unable to open pipe to ffmpeg"));
234                         return false;
235                 }
236                 // Close the unneeded pipeout
237                 close(p[0]);
238                 if( filename.c_str()[0] == '-' )
239                         execlp("ffmpeg", "ffmpeg", "-f", "image2pipe", "-vcodec", "ppm", "-an", "-r", strprintf("%f", desc.get_frame_rate()).c_str(), "-i", "pipe:", "-loop", "-hq", "-title", get_canvas()->get_name().c_str(), "-vcodec", "mpeg1video", "-y", "--", filename.c_str(), (const char *)NULL);
240                 else
241                         execlp("ffmpeg", "ffmpeg", "-f", "image2pipe", "-vcodec", "ppm", "-an", "-r", strprintf("%f", desc.get_frame_rate()).c_str(), "-i", "pipe:", "-loop", "-hq", "-title", get_canvas()->get_name().c_str(), "-vcodec", "mpeg1video", "-y", filename.c_str(), (const char *)NULL);
242                 // We should never reach here unless the exec failed
243                 synfig::error(_("Unable to open pipe to ffmpeg"));
244                 return false;
245         } else {
246                 // Parent process
247                 // Close pipein, not needed
248                 close(p[0]);
249                 // Save pipeout to file handle, will write to it later
250                 file = fdopen(p[1], "wb");
251         }
252
253 #else
254         #error There are no known APIs for creating child processes
255 #endif
256
257         // etl::yield();
258
259         if(!file)
260         {
261                 synfig::error(_("Unable to open pipe to ffmpeg"));
262                 return false;
263         }
264
265         return true;
266 }
267
268 void
269 ffmpeg_trgt::end_frame()
270 {
271         //fprintf(file, " ");
272         fflush(file);
273         imagecount++;
274 }
275
276 bool
277 ffmpeg_trgt::start_frame(synfig::ProgressCallback */*callback*/)
278 {
279         int w=desc.get_w(),h=desc.get_h();
280
281         if(!file)
282                 return false;
283
284         fprintf(file, "P6\n");
285         fprintf(file, "%d %d\n", w, h);
286         fprintf(file, "%d\n", 255);
287
288         delete [] buffer;
289         buffer=new unsigned char[3*w];
290         delete [] color_buffer;
291         color_buffer=new Color[w];
292
293         return true;
294 }
295
296 Color *
297 ffmpeg_trgt::start_scanline(int /*scanline*/)
298 {
299         return color_buffer;
300 }
301
302 bool
303 ffmpeg_trgt::end_scanline()
304 {
305         if(!file)
306                 return false;
307
308         convert_color_format(buffer, color_buffer, desc.get_w(), PF_RGB, gamma());
309
310         if(!fwrite(buffer,1,desc.get_w()*3,file))
311                 return false;
312
313         return true;
314 }