<climits> is needed for INT_MAX in agg2 headers
[gnash.git] / utilities / processor.cpp
blob270f6752d87186c644b694dcc6e4ce5e70db39b6
1 // processor.cpp: Flash movie processor (gprocessor command), for Gnash.
2 //
3 // Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Free Software
4 // Foundation, Inc
5 //
6 // This program is free software; you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation; either version 3 of the License, or
9 // (at your option) any later version.
10 //
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 #ifdef HAVE_CONFIG_H
22 #include "gnashconfig.h"
23 #endif
25 #include "NullSoundHandler.h"
27 #include <ios>
28 #include <iostream>
29 #include <cstdio>
30 #include <cstdlib>
31 #include <ctime>
33 #ifdef ENABLE_NLS
34 # include <clocale>
35 #endif
37 #include "MovieFactory.h"
38 #include "swf/TagLoadersTable.h"
39 #include "swf/DefaultTagLoaders.h"
40 #include "ClockTime.h"
41 #include "movie_definition.h"
42 #include "MovieClip.h"
43 #include "movie_root.h"
44 #include "log.h"
45 #include "rc.h"
46 #include "URL.h"
47 #include "GnashException.h"
48 #include "VM.h"
49 #include "noseek_fd_adapter.h"
50 #include "ManualClock.h"
51 #include "StringPredicates.h"
52 #include "smart_ptr.h"
53 #include "IOChannel.h" // for proper dtor call
54 #include "GnashSleep.h" // for usleep comptibility.
55 #include "StreamProvider.h"
56 #include "RunResources.h"
58 #ifdef RENDERER_AGG
59 #include "Renderer.h"
60 #include "Renderer_agg.h"
61 #endif
63 extern "C"{
64 #ifdef HAVE_GETOPT_H
65 #include <getopt.h>
66 #endif
67 #ifndef __GNUC__
68 extern char *optarg;
69 extern int optopt;
70 extern int optind, getopt(int, char *const *, const char *);
71 #endif
74 #ifdef BOOST_NO_EXCEPTIONS
76 namespace boost
78 void throw_exception(std::exception const & e)
80 std::abort();
83 #endif
85 // How many seconds to wait for a frame advancement
86 // before kicking the movie (forcing it to next frame)
87 static const double waitforadvance = 5;
89 // How many time do we allow for loop backs
90 // (goto frame < current frame)
91 static const size_t allowloopbacks = 10;
93 // How many times to call 'advance' ?
94 // If 0 number of advance is unlimited
95 // (see other constraints)
96 // TODO: add a command-line switch to control this
97 static size_t limit_advances = 0;
99 // How much time to sleep between advances ?
100 // If set to -1 it will be computed based on FPS.
101 static long int delay = 0;
103 const char *GPROC_VERSION = "1.0";
105 using namespace gnash;
107 static void usage (const char *);
109 namespace {
110 gnash::LogFile& dbglogfile = gnash::LogFile::getDefaultInstance();
111 gnash::RcInitFile& rcfile = gnash::RcInitFile::getDefaultInstance();
114 static bool play_movie(const std::string& filename,
115 const RunResources& runResources);
117 static bool s_stop_on_errors = true;
119 // How many time do we allow to hit the end ?
120 static size_t allowed_end_hits = 1;
122 double lastAdvanceTimer;
124 void
125 resetLastAdvanceTimer()
127 // clocktime::getTicks() returns milliseconds
128 lastAdvanceTimer = static_cast<double>(clocktime::getTicks()) / 1000.0;
131 double
132 secondsSinceLastAdvance()
134 // clocktime::getTicks() returns milliseconds
135 double now = static_cast<double>(clocktime::getTicks()) / 1000.0;
136 return ( now - lastAdvanceTimer);
139 // A flag which will be used to interrupt playback
140 // by effect of a "quit" fscommand
142 static int quitrequested = false;
144 class FsCommandExecutor: public movie_root::AbstractFsCallback {
145 public:
146 void notify(const std::string& command, const std::string& args)
148 log_debug(_("fs_callback(%p): %s %s"), command, args);
150 StringNoCaseEqual ncasecomp;
152 if ( ncasecomp(command, "quit") ) quitrequested = true;
156 class EventCallback: public movie_root::AbstractIfaceCallback
158 public:
159 std::string call(const std::string& event, const std::string& arg)
161 log_debug(_("eventCallback: %s %s"), event, arg);
163 static bool mouseShown = true;
165 // These should return "true" if the mouse was visible before
166 // the call.
167 if ( event == "Mouse.hide" ) {
168 bool state = mouseShown;
169 mouseShown = false;
170 return state ? "true" : "false";
173 if ( event == "Mouse.show" ) {
174 bool state = mouseShown;
175 mouseShown = true;
176 return state ? "true" : "false" ;
179 // Some fake values for consistent test results.
181 if ( event == "System.capabilities.screenResolutionX" ) {
182 return "800";
185 if ( event == "System.capabilities.screenResolutionY" ) {
186 return "640";
189 if ( event == "System.capabilities.screenDPI" ) {
190 return "72";
193 if ( event == "System.capabilities.screenColor" ) {
194 return "Color";
197 if ( event == "System.capabilities.playerType" ) {
198 return "StandAlone";
201 return "";
205 bool yesNo(const std::string& /*query*/)
207 return true;
210 void exit() {
211 std::exit(EXIT_SUCCESS);
215 EventCallback eventCallback;
216 FsCommandExecutor execFsCommand;
219 main(int argc, char *argv[])
221 std::ios::sync_with_stdio(false);
223 // Enable native language support, i.e. internationalization
224 #ifdef ENABLE_NLS
225 std::setlocale (LC_ALL, "");
226 bindtextdomain (PACKAGE, LOCALEDIR);
227 textdomain (PACKAGE);
228 #endif
229 int c;
231 // scan for the two main standard GNU options
232 for (c = 0; c < argc; c++) {
233 if (strcmp("--help", argv[c]) == 0) {
234 usage(argv[0]);
235 exit(EXIT_SUCCESS);
237 if (strcmp("--version", argv[c]) == 0) {
238 printf (_("Gnash gprocessor version: %s, Gnash version: %s\n"),
239 GPROC_VERSION, VERSION);
240 exit(EXIT_SUCCESS);
244 std::vector<std::string> infiles;
246 //RcInitFile& rcfile = RcInitFile::getDefaultInstance();
247 //rcfile.loadFiles();
249 if (rcfile.verbosityLevel() > 0) {
250 dbglogfile.setVerbosity(rcfile.verbosityLevel());
253 dbglogfile.setLogFilename(rcfile.getDebugLog());
255 if (rcfile.useWriteLog()) {
256 dbglogfile.setWriteDisk(true);
259 if (rcfile.useActionDump()) {
260 dbglogfile.setActionDump(true);
261 dbglogfile.setVerbosity();
264 if (rcfile.useParserDump()) {
265 dbglogfile.setParserDump(true);
266 dbglogfile.setVerbosity();
269 while ((c = getopt (argc, argv, ":hvapr:gf:d:n")) != -1) {
270 switch (c) {
271 case 'h':
272 usage (argv[0]);
273 dbglogfile.removeLog();
274 exit(EXIT_SUCCESS);
275 case 'v':
276 dbglogfile.setVerbosity();
277 log_debug (_("Verbose output turned on"));
278 break;
279 case 'n':
280 dbglogfile.setNetwork(true);
281 break;
282 case 'a':
283 #if VERBOSE_ACTION
284 dbglogfile.setActionDump(true);
285 #else
286 log_error (_("Verbose actions disabled at compile time"));
287 #endif
288 break;
289 case 'p':
290 #if VERBOSE_PARSE
291 dbglogfile.setParserDump(true);
292 #else
293 log_error (_("Verbose parsing disabled at compile time"));
294 #endif
295 break;
296 case 'r':
297 allowed_end_hits = strtol(optarg, NULL, 0);
298 break;
299 case 'd':
300 delay = strtol(optarg, NULL, 0)*1000; // delay is in microseconds
301 // this will be recognized as a request to run at FPS speed
302 if ( delay < 0 ) delay = -1;
303 break;
304 case 'f':
305 limit_advances = strtol(optarg, NULL, 0);
306 break;
307 case ':':
308 fprintf(stderr, "Missing argument for switch ``%c''\n", optopt);
309 exit(EXIT_FAILURE);
310 case '?':
311 default:
312 fprintf(stderr, "Unknown switch ``%c''\n", optopt);
313 exit(EXIT_FAILURE);
318 // get the file name from the command line
319 while (optind < argc) {
320 infiles.push_back(argv[optind]);
321 optind++;
324 // No file names were supplied
325 if (infiles.empty()) {
326 std::cerr << "no input files" << std::endl;
327 usage(argv[0]);
328 dbglogfile.removeLog();
329 exit(EXIT_FAILURE);
332 boost::shared_ptr<gnash::media::MediaHandler> mediaHandler;
333 boost::shared_ptr<sound::sound_handler> soundHandler;
335 std::string mh = rcfile.getMediaHandler();
336 mediaHandler.reset(media::MediaFactory::instance().get(mh));
337 soundHandler.reset(new sound::NullSoundHandler(mediaHandler.get()));
341 boost::shared_ptr<SWF::TagLoadersTable> loaders(new SWF::TagLoadersTable());
342 addDefaultLoaders(*loaders);
344 #ifdef RENDERER_AGG
345 boost::shared_ptr<Renderer_agg_base> r(create_Renderer_agg("RGBA32"));
347 // Yes, this leaks. On some systems (e.g. Debian Lenny) the data is
348 // evidently accessed after main() returns. Rather than bothering to
349 // work out why, we let this byte leak, as it's returned to the system on
350 // exit anyway.
351 unsigned char* buf = new unsigned char[8];
352 r->init_buffer(buf, 1, 1, 1, 1);
353 #endif
355 // Play through all the movies.
356 for (std::vector<std::string>::const_iterator i = infiles.begin(),
357 e = infiles.end(); i != e; ++i)
360 RunResources runResources;
361 runResources.setSoundHandler(soundHandler);
362 runResources.setMediaHandler(mediaHandler);
363 runResources.setTagLoaders(loaders);
364 boost::shared_ptr<StreamProvider> sp(new StreamProvider(*i, *i));
365 runResources.setStreamProvider(sp);
367 #ifdef RENDERER_AGG
368 runResources.setRenderer(r);
369 #endif
371 bool success = play_movie(*i, runResources);
372 if (!success) {
373 if (s_stop_on_errors) {
374 // Fail.
375 std::cerr << "error playing through movie " << *i << std::endl;
376 std::exit(EXIT_FAILURE);
382 return 0;
385 // Load the named movie, make an instance, and play it, virtually.
386 // I.e. run through and render all the frames, even though we are not
387 // actually doing any output (our output handlers are disabled).
389 bool
390 play_movie(const std::string& filename, const RunResources& runResources)
392 boost::intrusive_ptr<gnash::movie_definition> md;
394 quitrequested = false;
396 URL url(filename);
400 if (filename == "-")
402 std::auto_ptr<IOChannel> in (
403 noseek_fd_adapter::make_stream(fileno(stdin)) );
404 md = MovieFactory::makeMovie(in, filename, runResources, false);
406 else
408 if ( url.protocol() == "file" )
410 const std::string& path = url.path();
411 #if 1 // add the *directory* the movie was loaded from to the local sandbox path
412 size_t lastSlash = path.find_last_of('/');
413 std::string dir = path.substr(0, lastSlash+1);
414 rcfile.addLocalSandboxPath(dir);
415 log_debug(_("%s appended to local sandboxes"), dir.c_str());
416 #else // add the *file* to be loaded to the local sandbox path
417 rcfile.addLocalSandboxPath(path);
418 log_debug(_("%s appended to local sandboxes"), path.c_str());
419 #endif
421 md = MovieFactory::makeMovie(url, runResources, NULL, false);
424 catch (GnashException& ge)
426 md = NULL;
427 fprintf(stderr, "%s\n", ge.what());
429 if (md == NULL) {
430 std::cerr << "error: can't play movie: "<< filename << std::endl;
431 return false;
434 float fps = md->get_frame_rate();
435 long fpsDelay = long(1000000/fps);
436 long clockAdvance = fpsDelay/1000;
437 long localDelay = delay == -1 ? fpsDelay : delay; // microseconds
439 log_debug("Will sleep %ld microseconds between iterations - "
440 "fps is %g, clockAdvance is %lu", localDelay, fps, clockAdvance);
443 // Use a clock advanced at every iteration to match exact FPS speed.
444 ManualClock cl;
445 gnash::movie_root m(*md, cl, runResources);
447 // Register processor to receive ActionScript events (Mouse, Stage
448 // System etc).
449 m.registerEventCallback(&eventCallback);
450 m.registerFSCommandCallback(&execFsCommand);
452 md->completeLoad();
454 MovieClip::MovieVariables v;
455 m.init(md.get(), v);
457 log_debug("iteration, timer: %lu, localDelay: %ld\n",
458 cl.elapsed(), localDelay);
459 gnashSleep(localDelay);
461 resetLastAdvanceTimer();
462 int kick_count = 0;
463 int stop_count=0;
464 size_t loop_back_count=0;
465 size_t latest_frame=0;
466 size_t end_hitcount=0;
467 size_t nadvances=0;
468 // Run through the movie.
469 while (!quitrequested) {
470 // @@ do we also have to run through all sprite frames
471 // as well?
473 // @@ also, ActionScript can rescale things
474 // dynamically -- we can't really do much about that I
475 // guess?
477 // @@ Maybe we should allow the user to specify some
478 // safety margin on scaled shapes.
480 size_t last_frame = m.get_current_frame();
481 //printf("advancing clock by %lu\n", clockAdvance);
482 cl.advance(clockAdvance);
483 m.advance();
485 if ( quitrequested )
487 quitrequested = false;
488 break;
491 m.display(); // FIXME: for which reason are we calling display here ??
492 ++nadvances;
493 if ( limit_advances && nadvances >= limit_advances)
495 log_debug("exiting after %d advances", nadvances);
496 break;
499 size_t curr_frame = m.get_current_frame();
501 // We reached the end, done !
502 if (curr_frame >= md->get_frame_count() - 1 )
504 if ( allowed_end_hits && ++end_hitcount >= allowed_end_hits )
506 log_debug("exiting after %d"
507 " times last frame was reached", end_hitcount);
508 break;
512 // We didn't advance
513 if (curr_frame == last_frame)
515 // Max stop counts reached, kick it
516 if ( secondsSinceLastAdvance() > waitforadvance )
518 stop_count=0;
520 // Kick the movie.
521 if ( last_frame + 1 > md->get_frame_count() -1 )
523 fprintf(stderr, "Exiting after %g seconds in STOP mode at last frame\n", waitforadvance);
524 break;
526 fprintf(stderr, "Kicking movie after %g seconds in STOP mode, kick ct = %d\n", waitforadvance, kick_count);
527 fflush(stderr);
528 m.goto_frame(last_frame + 1);
529 m.set_play_state(gnash::MovieClip::PLAYSTATE_PLAY);
530 kick_count++;
532 if (kick_count > 10) {
533 printf("movie is stalled; giving up on playing it through.\n");
534 break;
537 resetLastAdvanceTimer(); // It's like we advanced
541 // We looped back. Skip ahead...
542 else if (m.get_current_frame() < last_frame)
544 if ( last_frame > latest_frame ) latest_frame = last_frame;
545 if ( ++loop_back_count > allowloopbacks )
547 log_debug("%d loop backs; jumping one-after "
548 "latest frame (%d)",
549 loop_back_count, latest_frame+1);
550 m.goto_frame(latest_frame + 1);
551 loop_back_count = 0;
554 else
556 kick_count = 0;
557 stop_count = 0;
558 resetLastAdvanceTimer();
561 log_debug("iteration, timer: %lu, localDelay: %ld\n",
562 cl.elapsed(), localDelay);
563 gnashSleep(localDelay);
566 log_debug("-- Playback completed");
568 log_debug("-- Dropping ref of movie_definition");
570 // drop reference to movie_definition, to force
571 // destruction when core gnash doesn't need it anymore
572 md = 0;
574 log_debug("-- Cleaning gnash");
576 // Clear resources.
577 // Forces run of GC, which in turn may invoke
578 // destuctors of (say) MovieClip which would try
579 // to access the movie_root to unregister self
581 // This means that movie_root must be available.
582 MovieFactory::clear();
584 return true;
587 static void
588 usage (const char *name)
590 printf(
591 _("gprocessor -- an SWF processor for Gnash.\n"
592 "\n"
593 "usage: %s [options] <file>\n"
594 "\n"
595 "Process the given SWF movie files.\n"
596 "\n"
597 "%s%s%s%s"), name, _(
598 "options:\n"
599 "\n"
600 " --help(-h) Print this info.\n"
601 " --version Print the version numbers.\n"
602 " -v Be verbose; i.e. print log messages to stdout\n"
604 #if VERBOSE_PARSE
605 _(" -vp Be verbose about movie parsing\n"),
606 #else
608 #endif
609 #if VERBOSE_ACTION
610 _(" -va Be verbose about ActionScript\n"),
611 #else
613 #endif
615 " -d [<ms>]\n"
616 " Milliseconds delay between advances (0 by default).\n"
617 " If '-1' the delay will be computed from the FPS.\n"
618 " -r <times> Allow the given number of complete runs.\n"
619 " Keep looping undefinitely if set to 0.\n"
620 " Default is 1 (end as soon as the last frame is reached).\n"
621 " -f <frames> \n"
622 " Allow the given number of frame advancements.\n"
623 " Keep advancing untill any other stop condition\n"
624 " is encountered if set to 0 (default).\n")
629 // Local Variables:
630 // mode: C++
631 // indent-tabs-mode: t
632 // End: