Instead of a timer, use delay
authorThadeu Lima de Souza Cascardo <cascardo@holoscopio.com>
Tue, 12 Aug 2008 20:26:51 +0000 (17:26 -0300)
committerThadeu Lima de Souza Cascardo <cascardo@holoscopio.com>
Tue, 12 Aug 2008 20:26:51 +0000 (17:26 -0300)
Instead of using a timer, which may run on another thread, just simply
delay the number of milliseconds needed to keep up with the requested
frame rate.

movie.c

diff --git a/movie.c b/movie.c
index 71fb01d..a03fb67 100644 (file)
--- a/movie.c
+++ b/movie.c
@@ -22,7 +22,8 @@
 #define VBORDER 8
 
 #define STOP_INTERVAL (5*1000)
-#define FPS (4)
+#define FPS (30)
+#define FRAME_INTERVAL (1000/(FPS))
 
 #include <stdio.h>
 #include <stdlib.h>
@@ -183,7 +184,7 @@ GetNextImage (SDL_Surface *image)
   SDL_Surface *text;
   SDL_Rect box;
   SDL_Color Yellow = { 255, 255, 0, 0};
-  center = GetNextPoint (), GetNextPoint (), GetNextPoint ();
+  center = GetNextPoint ();
   slice = SDL_CreateRGBSurface (SDL_SWSURFACE, WIDTH/2, HEIGHT/2,
                                 32,
                                0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000);
@@ -214,21 +215,6 @@ GetNextImage (SDL_Surface *image)
   return scale;
 }
 
-Uint32
-ShowNext (Uint32 interval, void *data)
-{
-  SDL_UserEvent event;
-  event.type = SDL_USEREVENT;
-  event.code = 0;
-  SDL_PushEvent ((SDL_Event *) &event);
-  if (stop)
-  {
-    stop = 0;
-    return STOP_INTERVAL;
-  }
-  return 1000/FPS;
-}
-
 int
 main (int argc, char **argv)
 {
@@ -236,6 +222,7 @@ main (int argc, char **argv)
   SDL_Surface *image;
   SDL_Surface *slice;
   SDL_Event event;
+  Uint32 now, last;
   int i;
   ReadPoints ("pro-gnu");
   SDL_Init (SDL_INIT_VIDEO | SDL_INIT_TIMER);
@@ -243,16 +230,33 @@ main (int argc, char **argv)
   font = TTF_OpenFont ("/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf", 48);
   screen = SDL_SetVideoMode (WIDTH, HEIGHT, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
   image = IMG_Load ("/home/cascardo/fotos/debconf.jpg");
-  SDL_AddTimer (0, ShowNext, NULL);
-  while (SDL_WaitEvent (&event))
+  last = SDL_GetTicks ();
+  while (1)
   {
-    if (event.type == SDL_KEYDOWN)
-      break;
-    else if (event.type == SDL_USEREVENT)
+    if (SDL_PollEvent (&event))
+    {
+      if (event.type == SDL_KEYDOWN)
+        break;
+    }
+    now = SDL_GetTicks ();
+    /* skip */
+    while (!stop && now > last + FRAME_INTERVAL)
+    {
+      last += FRAME_INTERVAL;
+      GetNextPoint ();
+    }
+    slice = GetNextImage (image);
+    ShowPoint (screen, slice);
+    SDL_FreeSurface (slice);
+    if (stop)
+    {
+      stop = 0;
+      SDL_Delay (STOP_INTERVAL);
+      last = SDL_GetTicks ();
+    }
+    else
     {
-      slice = GetNextImage (image);
-      ShowPoint (screen, slice);
-      SDL_FreeSurface (slice);
+      SDL_Delay (FRAME_INTERVAL - (now - last));
     }
   }
   SDL_FreeSurface (image);