1 /* gifdec example -- simple GIF player using SDL2
3 * cc `pkg-config --cflags --libs sdl2` -o example gifdec.c example.c
5 * ./example animation.gif
15 main(int argc
, char *argv
[])
18 SDL_Renderer
*renderer
;
28 int ret
, paused
, quit
;
29 Uint32 t0
, t1
, delay
, delta
;
32 fprintf(stderr
, "usage:\n %s gif-file\n", argv
[0]);
35 gif
= gd_open_gif(argv
[1]);
37 fprintf(stderr
, "Could not open %s\n", argv
[1]);
40 frame
= malloc(gif
->width
* gif
->height
* 3);
42 fprintf(stderr
, "Could not allocate frame\n");
45 if (SDL_Init(SDL_INIT_VIDEO
|SDL_INIT_TIMER
) != 0) {
46 SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
49 if (SDL_CreateWindowAndRenderer(gif
->width
, gif
->height
, SDL_WINDOW_RESIZABLE
, &window
, &renderer
)) {
50 SDL_Log("Couldn't create window and renderer: %s", SDL_GetError());
53 snprintf(title
, sizeof(title
) - 1, "GIF %dx%d %d colors",
54 gif
->width
, gif
->height
, gif
->palette
->size
);
55 SDL_SetWindowTitle(window
, title
);
56 color
= &gif
->gct
.colors
[gif
->bgindex
* 3];
57 SDL_SetRenderDrawColor(renderer
, color
[0], color
[1], color
[2], 0x00);
58 SDL_RenderClear(renderer
);
59 SDL_RenderPresent(renderer
);
60 surface
= SDL_CreateRGBSurface(0, gif
->width
, gif
->height
, 32, 0, 0, 0, 0);
62 SDL_Log("SDL_CreateRGBSurface() failed: %s", SDL_GetError());
68 while (SDL_PollEvent(&event
) && !quit
) {
69 if (event
.type
== SDL_QUIT
)
71 if (event
.type
== SDL_KEYDOWN
) {
72 if (event
.key
.keysym
.sym
== SDLK_q
)
74 else if (event
.key
.keysym
.sym
== SDLK_SPACE
)
84 ret
= gd_get_frame(gif
);
87 SDL_LockSurface(surface
);
88 gd_render_frame(gif
, frame
);
90 for (i
= 0; i
< gif
->height
; i
++) {
91 for (j
= 0; j
< gif
->width
; j
++) {
92 if (!gd_is_bgcolor(gif
, color
))
93 pixel
= SDL_MapRGB(surface
->format
, color
[0], color
[1], color
[2]);
94 else if (((i
>> 2) + (j
>> 2)) & 1)
95 pixel
= SDL_MapRGB(surface
->format
, 0x7F, 0x7F, 0x7F);
97 pixel
= SDL_MapRGB(surface
->format
, 0x00, 0x00, 0x00);
98 addr
= surface
->pixels
+ (i
* surface
->pitch
+ j
* sizeof(pixel
));
99 memcpy(addr
, &pixel
, sizeof(pixel
));
103 SDL_UnlockSurface(surface
);
104 texture
= SDL_CreateTextureFromSurface(renderer
, surface
);
105 SDL_RenderCopy(renderer
, texture
, NULL
, NULL
);
106 SDL_RenderPresent(renderer
);
107 SDL_DestroyTexture(texture
);
110 delay
= gif
->gce
.delay
* 10;
111 delay
= delay
> delta
? delay
- delta
: 1;
116 SDL_FreeSurface(surface
);
117 SDL_DestroyRenderer(renderer
);
118 SDL_DestroyWindow(window
);