xref: /aosp_15_r20/external/libdav1d/examples/dav1dplay.c (revision c09093415860a1c2373dacd84c4fde00c507cdfd)
1 /*
2  * Copyright © 2019, VideoLAN and dav1d authors
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright notice, this
9  *    list of conditions and the following disclaimer.
10  *
11  * 2. Redistributions in binary form must reproduce the above copyright notice,
12  *    this list of conditions and the following disclaimer in the documentation
13  *    and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
19  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include "config.h"
28 #include "vcs_version.h"
29 
30 #include <getopt.h>
31 #include <stdbool.h>
32 
33 #include <SDL.h>
34 
35 #include "dav1d/dav1d.h"
36 
37 #include "common/attributes.h"
38 #include "tools/input/input.h"
39 #include "dp_fifo.h"
40 #include "dp_renderer.h"
41 
42 #define FRAME_OFFSET_TO_PTS(foff) \
43     (uint64_t)(((foff) * rd_ctx->spf) * 1000000000.0 + .5)
44 #define TS_TO_PTS(ts) \
45     (uint64_t)(((ts) * rd_ctx->timebase) * 1000000000.0 + .5)
46 
47 // Selected renderer callbacks and cookie
48 static const Dav1dPlayRenderInfo *renderer_info = { NULL };
49 
50 /**
51  * Render context structure
52  * This structure contains informations necessary
53  * to be shared between the decoder and the renderer
54  * threads.
55  */
56 typedef struct render_context
57 {
58     Dav1dPlaySettings settings;
59     Dav1dSettings lib_settings;
60 
61     // Renderer private data (passed to callbacks)
62     void *rd_priv;
63 
64     // Lock to protect access to the context structure
65     SDL_mutex *lock;
66 
67     // Timestamp of last displayed frame (in timebase unit)
68     int64_t last_ts;
69     // Timestamp of last decoded frame (in timebase unit)
70     int64_t current_ts;
71     // Ticks when last frame was received
72     uint32_t last_ticks;
73     // PTS time base
74     double timebase;
75     // Seconds per frame
76     double spf;
77     // Number of frames
78     uint32_t total;
79 
80     // Fifo
81     Dav1dPlayPtrFifo *fifo;
82 
83     // Custom SDL2 event types
84     uint32_t event_types;
85 
86     // User pause state
87     uint8_t user_paused;
88     // Internal pause state
89     uint8_t paused;
90     // Start of internal pause state
91     uint32_t pause_start;
92     // Duration of internal pause state
93     uint32_t pause_time;
94 
95     // Seek accumulator
96     int seek;
97 
98     // Indicates if termination of the decoder thread was requested
99     uint8_t dec_should_terminate;
100 } Dav1dPlayRenderContext;
101 
dp_settings_print_usage(const char * const app,const char * const reason,...)102 static void dp_settings_print_usage(const char *const app,
103                                     const char *const reason, ...)
104 {
105     if (reason) {
106         va_list args;
107 
108         va_start(args, reason);
109         vfprintf(stderr, reason, args);
110         va_end(args);
111         fprintf(stderr, "\n\n");
112     }
113     fprintf(stderr, "Usage: %s [options]\n\n", app);
114     fprintf(stderr, "Supported options:\n"
115             " --input/-i  $file:    input file\n"
116             " --untimed/-u:         ignore PTS, render as fast as possible\n"
117             " --threads $num:       number of threads (default: 0)\n"
118             " --framedelay $num:    maximum frame delay, capped at $threads (default: 0);\n"
119             "                       set to 1 for low-latency decoding\n"
120             " --highquality:        enable high quality rendering\n"
121             " --zerocopy/-z:        enable zero copy upload path\n"
122             " --gpugrain/-g:        enable GPU grain synthesis\n"
123             " --fullscreen/-f:      enable full screen mode\n"
124             " --version/-v:         print version and exit\n"
125             " --renderer/-r:        select renderer backend (default: auto)\n");
126     exit(1);
127 }
128 
parse_unsigned(const char * const optarg,const int option,const char * const app)129 static unsigned parse_unsigned(const char *const optarg, const int option,
130                                const char *const app)
131 {
132     char *end;
133     const unsigned res = (unsigned) strtoul(optarg, &end, 0);
134     if (*end || end == optarg)
135         dp_settings_print_usage(app, "Invalid argument \"%s\" for option %s; should be an integer",
136           optarg, option);
137     return res;
138 }
139 
dp_rd_ctx_parse_args(Dav1dPlayRenderContext * rd_ctx,const int argc,char * const * const argv)140 static void dp_rd_ctx_parse_args(Dav1dPlayRenderContext *rd_ctx,
141                                  const int argc, char *const *const argv)
142 {
143     int o;
144     Dav1dPlaySettings *settings = &rd_ctx->settings;
145     Dav1dSettings *lib_settings = &rd_ctx->lib_settings;
146 
147     // Short options
148     static const char short_opts[] = "i:vuzgfr:";
149 
150     enum {
151         ARG_THREADS = 256,
152         ARG_FRAME_DELAY,
153         ARG_HIGH_QUALITY,
154     };
155 
156     // Long options
157     static const struct option long_opts[] = {
158         { "input",          1, NULL, 'i' },
159         { "version",        0, NULL, 'v' },
160         { "untimed",        0, NULL, 'u' },
161         { "threads",        1, NULL, ARG_THREADS },
162         { "framedelay",     1, NULL, ARG_FRAME_DELAY },
163         { "highquality",    0, NULL, ARG_HIGH_QUALITY },
164         { "zerocopy",       0, NULL, 'z' },
165         { "gpugrain",       0, NULL, 'g' },
166         { "fullscreen",     0, NULL, 'f'},
167         { "renderer",       0, NULL, 'r'},
168         { NULL,             0, NULL, 0 },
169     };
170 
171     while ((o = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
172         switch (o) {
173             case 'i':
174                 settings->inputfile = optarg;
175                 break;
176             case 'v':
177                 fprintf(stderr, "%s\n", dav1d_version());
178                 exit(0);
179             case 'u':
180                 settings->untimed = true;
181                 break;
182             case ARG_HIGH_QUALITY:
183                 settings->highquality = true;
184                 break;
185             case 'z':
186                 settings->zerocopy = true;
187                 break;
188             case 'g':
189                 settings->gpugrain = true;
190                 break;
191             case 'f':
192                 settings->fullscreen = true;
193                 break;
194             case 'r':
195                 settings->renderer_name = optarg;
196                 break;
197             case ARG_THREADS:
198                 lib_settings->n_threads =
199                     parse_unsigned(optarg, ARG_THREADS, argv[0]);
200                 break;
201             case ARG_FRAME_DELAY:
202                 lib_settings->max_frame_delay =
203                     parse_unsigned(optarg, ARG_FRAME_DELAY, argv[0]);
204                 break;
205             default:
206                 dp_settings_print_usage(argv[0], NULL);
207         }
208     }
209 
210     if (optind < argc)
211         dp_settings_print_usage(argv[0],
212             "Extra/unused arguments found, e.g. '%s'\n", argv[optind]);
213     if (!settings->inputfile)
214         dp_settings_print_usage(argv[0], "Input file (-i/--input) is required");
215     if (settings->renderer_name && strcmp(settings->renderer_name, "auto") == 0)
216         settings->renderer_name = NULL;
217 }
218 
219 /**
220  * Destroy a Dav1dPlayRenderContext
221  */
dp_rd_ctx_destroy(Dav1dPlayRenderContext * rd_ctx)222 static void dp_rd_ctx_destroy(Dav1dPlayRenderContext *rd_ctx)
223 {
224     assert(rd_ctx != NULL);
225 
226     renderer_info->destroy_renderer(rd_ctx->rd_priv);
227     dp_fifo_destroy(rd_ctx->fifo);
228     SDL_DestroyMutex(rd_ctx->lock);
229     free(rd_ctx);
230 }
231 
232 /**
233  * Create a Dav1dPlayRenderContext
234  *
235  * \note  The Dav1dPlayRenderContext must be destroyed
236  *        again by using dp_rd_ctx_destroy.
237  */
dp_rd_ctx_create(int argc,char ** argv)238 static Dav1dPlayRenderContext *dp_rd_ctx_create(int argc, char **argv)
239 {
240     Dav1dPlayRenderContext *rd_ctx;
241 
242     // Alloc
243     rd_ctx = calloc(1, sizeof(Dav1dPlayRenderContext));
244     if (rd_ctx == NULL) {
245         return NULL;
246     }
247 
248     // Parse and validate arguments
249     dav1d_default_settings(&rd_ctx->lib_settings);
250     memset(&rd_ctx->settings, 0, sizeof(rd_ctx->settings));
251     dp_rd_ctx_parse_args(rd_ctx, argc, argv);
252 
253     // Init SDL2 library
254     if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) {
255         fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
256         goto fail;
257     }
258 
259     // Register a custom event to notify our SDL main thread
260     // about new frames
261     rd_ctx->event_types = SDL_RegisterEvents(3);
262     if (rd_ctx->event_types == UINT32_MAX) {
263         fprintf(stderr, "Failure to create custom SDL event types!\n");
264         goto fail;
265     }
266 
267     rd_ctx->fifo = dp_fifo_create(5);
268     if (rd_ctx->fifo == NULL) {
269         fprintf(stderr, "Failed to create FIFO for output pictures!\n");
270         goto fail;
271     }
272 
273     rd_ctx->lock = SDL_CreateMutex();
274     if (rd_ctx->lock == NULL) {
275         fprintf(stderr, "SDL_CreateMutex failed: %s\n", SDL_GetError());
276         goto fail;
277     }
278 
279     // Select renderer
280     renderer_info = dp_get_renderer(rd_ctx->settings.renderer_name);
281 
282     if (renderer_info == NULL) {
283         printf("No suitable renderer matching %s found.\n",
284             (rd_ctx->settings.renderer_name) ? rd_ctx->settings.renderer_name : "auto");
285     } else {
286         printf("Using %s renderer\n", renderer_info->name);
287     }
288 
289     rd_ctx->rd_priv = (renderer_info) ? renderer_info->create_renderer(&rd_ctx->settings) : NULL;
290     if (rd_ctx->rd_priv == NULL) {
291         goto fail;
292     }
293 
294     return rd_ctx;
295 
296 fail:
297     if (rd_ctx->lock)
298         SDL_DestroyMutex(rd_ctx->lock);
299     if (rd_ctx->fifo)
300         dp_fifo_destroy(rd_ctx->fifo);
301     free(rd_ctx);
302     SDL_Quit();
303     return NULL;
304 }
305 
306 /**
307  * Notify about new event
308  */
dp_rd_ctx_post_event(Dav1dPlayRenderContext * rd_ctx,uint32_t type)309 static void dp_rd_ctx_post_event(Dav1dPlayRenderContext *rd_ctx, uint32_t type)
310 {
311     SDL_Event event;
312     SDL_zero(event);
313     event.type = type;
314     SDL_PushEvent(&event);
315 }
316 
317 /**
318  * Update the decoder context with a new dav1d picture
319  *
320  * Once the decoder decoded a new picture, this call can be used
321  * to update the internal texture of the render context with the
322  * new picture.
323  */
dp_rd_ctx_update_with_dav1d_picture(Dav1dPlayRenderContext * rd_ctx,Dav1dPicture * dav1d_pic)324 static void dp_rd_ctx_update_with_dav1d_picture(Dav1dPlayRenderContext *rd_ctx,
325                                                 Dav1dPicture *dav1d_pic)
326 {
327     rd_ctx->current_ts = dav1d_pic->m.timestamp;
328     renderer_info->update_frame(rd_ctx->rd_priv, dav1d_pic, &rd_ctx->settings);
329 }
330 
331 /**
332  * Toggle pause state
333  */
dp_rd_ctx_toggle_pause(Dav1dPlayRenderContext * rd_ctx)334 static void dp_rd_ctx_toggle_pause(Dav1dPlayRenderContext *rd_ctx)
335 {
336     SDL_LockMutex(rd_ctx->lock);
337     rd_ctx->user_paused = !rd_ctx->user_paused;
338     if (rd_ctx->seek)
339         goto out;
340     rd_ctx->paused = rd_ctx->user_paused;
341     uint32_t now = SDL_GetTicks();
342     if (rd_ctx->paused)
343         rd_ctx->pause_start = now;
344     else {
345         rd_ctx->pause_time += now - rd_ctx->pause_start;
346         rd_ctx->pause_start = 0;
347         rd_ctx->last_ticks = now;
348     }
349 out:
350     SDL_UnlockMutex(rd_ctx->lock);
351 }
352 
353 /**
354  * Query pause state
355  */
dp_rd_ctx_is_paused(Dav1dPlayRenderContext * rd_ctx)356 static int dp_rd_ctx_is_paused(Dav1dPlayRenderContext *rd_ctx)
357 {
358     int ret;
359     SDL_LockMutex(rd_ctx->lock);
360     ret = rd_ctx->paused;
361     SDL_UnlockMutex(rd_ctx->lock);
362     return ret;
363 }
364 
365 /**
366  * Request seeking, in seconds
367  */
dp_rd_ctx_seek(Dav1dPlayRenderContext * rd_ctx,int sec)368 static void dp_rd_ctx_seek(Dav1dPlayRenderContext *rd_ctx, int sec)
369 {
370     SDL_LockMutex(rd_ctx->lock);
371     rd_ctx->seek += sec;
372     if (!rd_ctx->paused)
373         rd_ctx->pause_start = SDL_GetTicks();
374     rd_ctx->paused = 1;
375     SDL_UnlockMutex(rd_ctx->lock);
376 }
377 
378 static int decode_frame(Dav1dPicture **p, Dav1dContext *c,
379                         Dav1dData *data, DemuxerContext *in_ctx);
380 static inline void destroy_pic(void *a);
381 
382 /**
383  * Seek the stream, if requested
384  */
dp_rd_ctx_handle_seek(Dav1dPlayRenderContext * rd_ctx,DemuxerContext * in_ctx,Dav1dContext * c,Dav1dData * data)385 static int dp_rd_ctx_handle_seek(Dav1dPlayRenderContext *rd_ctx,
386                                  DemuxerContext *in_ctx,
387                                  Dav1dContext *c, Dav1dData *data)
388 {
389     int res = 0;
390     SDL_LockMutex(rd_ctx->lock);
391     if (!rd_ctx->seek)
392         goto out;
393     int64_t seek = rd_ctx->seek * 1000000000ULL;
394     uint64_t pts = TS_TO_PTS(rd_ctx->current_ts);
395     pts = ((int64_t)pts > -seek) ? pts + seek : 0;
396     int end = pts >= FRAME_OFFSET_TO_PTS(rd_ctx->total);
397     if (end)
398         pts = FRAME_OFFSET_TO_PTS(rd_ctx->total - 1);
399     uint64_t target_pts = pts;
400     dav1d_flush(c);
401     uint64_t shift = FRAME_OFFSET_TO_PTS(5);
402     while (1) {
403         if (shift > pts)
404             shift = pts;
405         if ((res = input_seek(in_ctx, pts - shift)))
406             goto out;
407         Dav1dSequenceHeader seq;
408         uint64_t cur_pts;
409         do {
410             if ((res = input_read(in_ctx, data)))
411                 break;
412             cur_pts = TS_TO_PTS(data->m.timestamp);
413             res = dav1d_parse_sequence_header(&seq, data->data, data->sz);
414         } while (res && cur_pts < pts);
415         if (!res && cur_pts <= pts)
416             break;
417         if (shift > pts)
418             shift = pts;
419         pts -= shift;
420     }
421     if (!res) {
422         pts = TS_TO_PTS(data->m.timestamp);
423         while (pts < target_pts) {
424             Dav1dPicture *p;
425             if ((res = decode_frame(&p, c, data, in_ctx)))
426                 break;
427             if (p) {
428                 pts = TS_TO_PTS(p->m.timestamp);
429                 if (pts < target_pts)
430                     destroy_pic(p);
431                 else {
432                     dp_fifo_push(rd_ctx->fifo, p);
433                     uint32_t type = rd_ctx->event_types + DAV1D_EVENT_SEEK_FRAME;
434                     dp_rd_ctx_post_event(rd_ctx, type);
435                 }
436             }
437         }
438         if (!res) {
439             rd_ctx->last_ts = data->m.timestamp - rd_ctx->spf / rd_ctx->timebase;
440             rd_ctx->current_ts = data->m.timestamp;
441         }
442     }
443 out:
444     rd_ctx->paused = rd_ctx->user_paused;
445     if (!rd_ctx->paused && rd_ctx->seek) {
446         uint32_t now = SDL_GetTicks();
447         rd_ctx->pause_time += now - rd_ctx->pause_start;
448         rd_ctx->pause_start = 0;
449         rd_ctx->last_ticks = now;
450     }
451     rd_ctx->seek = 0;
452     SDL_UnlockMutex(rd_ctx->lock);
453     if (res)
454         fprintf(stderr, "Error seeking, aborting\n");
455     return res;
456 }
457 
458 /**
459  * Terminate decoder thread (async)
460  */
dp_rd_ctx_request_shutdown(Dav1dPlayRenderContext * rd_ctx)461 static void dp_rd_ctx_request_shutdown(Dav1dPlayRenderContext *rd_ctx)
462 {
463     SDL_LockMutex(rd_ctx->lock);
464     rd_ctx->dec_should_terminate = 1;
465     SDL_UnlockMutex(rd_ctx->lock);
466 }
467 
468 /**
469  * Query state of decoder shutdown request
470  */
dp_rd_ctx_should_terminate(Dav1dPlayRenderContext * rd_ctx)471 static int dp_rd_ctx_should_terminate(Dav1dPlayRenderContext *rd_ctx)
472 {
473     int ret = 0;
474     SDL_LockMutex(rd_ctx->lock);
475     ret = rd_ctx->dec_should_terminate;
476     SDL_UnlockMutex(rd_ctx->lock);
477     return ret;
478 }
479 
480 /**
481  * Render the currently available texture
482  *
483  * Renders the currently available texture, if any.
484  */
dp_rd_ctx_render(Dav1dPlayRenderContext * rd_ctx)485 static void dp_rd_ctx_render(Dav1dPlayRenderContext *rd_ctx)
486 {
487     SDL_LockMutex(rd_ctx->lock);
488     // Calculate time since last frame was received
489     uint32_t ticks_now = SDL_GetTicks();
490     uint32_t ticks_diff = (rd_ctx->last_ticks != 0) ? ticks_now - rd_ctx->last_ticks : 0;
491 
492     // Calculate when to display the frame
493     int64_t ts_diff = rd_ctx->current_ts - rd_ctx->last_ts;
494     int32_t pts_diff = (ts_diff * rd_ctx->timebase) * 1000.0 + .5;
495     int32_t wait_time = pts_diff - ticks_diff;
496 
497     // In untimed mode, simply don't wait
498     if (rd_ctx->settings.untimed)
499         wait_time = 0;
500 
501     // This way of timing the playback is not accurate, as there is no guarantee
502     // that SDL_Delay will wait for exactly the requested amount of time so in a
503     // accurate player this would need to be done in a better way.
504     if (wait_time > 0) {
505         SDL_Delay(wait_time);
506     } else if (wait_time < -10 && !rd_ctx->paused) { // Do not warn for minor time drifts
507         fprintf(stderr, "Frame displayed %f seconds too late\n", wait_time / 1000.0);
508     }
509 
510     renderer_info->render(rd_ctx->rd_priv, &rd_ctx->settings);
511 
512     rd_ctx->last_ts = rd_ctx->current_ts;
513     rd_ctx->last_ticks = SDL_GetTicks();
514 
515     SDL_UnlockMutex(rd_ctx->lock);
516 }
517 
decode_frame(Dav1dPicture ** p,Dav1dContext * c,Dav1dData * data,DemuxerContext * in_ctx)518 static int decode_frame(Dav1dPicture **p, Dav1dContext *c,
519                         Dav1dData *data, DemuxerContext *in_ctx)
520 {
521     int res;
522     // Send data packets we got from the demuxer to dav1d
523     if ((res = dav1d_send_data(c, data)) < 0) {
524         // On EAGAIN, dav1d can not consume more data and
525         // dav1d_get_picture needs to be called first, which
526         // will happen below, so just keep going in that case
527         // and do not error out.
528         if (res != DAV1D_ERR(EAGAIN)) {
529             dav1d_data_unref(data);
530             goto err;
531         }
532     }
533     *p = calloc(1, sizeof(**p));
534     // Try to get a decoded frame
535     if ((res = dav1d_get_picture(c, *p)) < 0) {
536         // In all error cases, even EAGAIN, p needs to be freed as
537         // it is never added to the queue and would leak.
538         free(*p);
539         *p = NULL;
540         // On EAGAIN, it means dav1d has not enough data to decode
541         // therefore this is not a decoding error but just means
542         // we need to feed it more data, which happens in the next
543         // run of the decoder loop.
544         if (res != DAV1D_ERR(EAGAIN))
545             goto err;
546     }
547     return data->sz == 0 ? input_read(in_ctx, data) : 0;
548 err:
549     fprintf(stderr, "Error decoding frame: %s\n",
550             strerror(-res));
551     return res;
552 }
553 
destroy_pic(void * a)554 static inline void destroy_pic(void *a)
555 {
556     Dav1dPicture *p = (Dav1dPicture *)a;
557     dav1d_picture_unref(p);
558     free(p);
559 }
560 
561 /* Decoder thread "main" function */
decoder_thread_main(void * cookie)562 static int decoder_thread_main(void *cookie)
563 {
564     Dav1dPlayRenderContext *rd_ctx = cookie;
565 
566     Dav1dPicture *p;
567     Dav1dContext *c = NULL;
568     Dav1dData data;
569     DemuxerContext *in_ctx = NULL;
570     int res = 0;
571     unsigned total, timebase[2], fps[2];
572 
573     Dav1dPlaySettings settings = rd_ctx->settings;
574 
575     if ((res = input_open(&in_ctx, "ivf",
576                           settings.inputfile,
577                           fps, &total, timebase)) < 0)
578     {
579         fprintf(stderr, "Failed to open demuxer\n");
580         res = 1;
581         goto cleanup;
582     }
583 
584     rd_ctx->timebase = (double)timebase[1] / timebase[0];
585     rd_ctx->spf = (double)fps[1] / fps[0];
586     rd_ctx->total = total;
587 
588     if ((res = dav1d_open(&c, &rd_ctx->lib_settings))) {
589         fprintf(stderr, "Failed opening dav1d decoder\n");
590         res = 1;
591         goto cleanup;
592     }
593 
594     if ((res = input_read(in_ctx, &data)) < 0) {
595         fprintf(stderr, "Failed demuxing input\n");
596         res = 1;
597         goto cleanup;
598     }
599 
600     // Decoder loop
601     while (1) {
602         if (dp_rd_ctx_should_terminate(rd_ctx) ||
603             (res = dp_rd_ctx_handle_seek(rd_ctx, in_ctx, c, &data)) ||
604             (res = decode_frame(&p, c, &data, in_ctx)))
605         {
606             break;
607         }
608         else if (p) {
609             // Queue frame
610             SDL_LockMutex(rd_ctx->lock);
611             int seek = rd_ctx->seek;
612             SDL_UnlockMutex(rd_ctx->lock);
613             if (!seek) {
614                 dp_fifo_push(rd_ctx->fifo, p);
615                 uint32_t type = rd_ctx->event_types + DAV1D_EVENT_NEW_FRAME;
616                 dp_rd_ctx_post_event(rd_ctx, type);
617             }
618         }
619     }
620 
621     // Release remaining data
622     if (data.sz > 0)
623         dav1d_data_unref(&data);
624     // Do not drain in case an error occured and caused us to leave the
625     // decoding loop early.
626     if (res < 0)
627         goto cleanup;
628 
629     // Drain decoder
630     // When there is no more data to feed to the decoder, for example
631     // because the file ended, we still need to request pictures, as
632     // even though we do not have more data, there can be frames decoded
633     // from data we sent before. So we need to call dav1d_get_picture until
634     // we get an EAGAIN error.
635     do {
636         if (dp_rd_ctx_should_terminate(rd_ctx))
637             break;
638         p = calloc(1, sizeof(*p));
639         res = dav1d_get_picture(c, p);
640         if (res < 0) {
641             free(p);
642             if (res != DAV1D_ERR(EAGAIN)) {
643                 fprintf(stderr, "Error decoding frame: %s\n",
644                         strerror(-res));
645                 break;
646             }
647         } else {
648             // Queue frame
649             dp_fifo_push(rd_ctx->fifo, p);
650             uint32_t type = rd_ctx->event_types + DAV1D_EVENT_NEW_FRAME;
651             dp_rd_ctx_post_event(rd_ctx, type);
652         }
653     } while (res != DAV1D_ERR(EAGAIN));
654 
655 cleanup:
656     dp_rd_ctx_post_event(rd_ctx, rd_ctx->event_types + DAV1D_EVENT_DEC_QUIT);
657 
658     if (in_ctx)
659         input_close(in_ctx);
660     if (c)
661         dav1d_close(&c);
662 
663     return (res != DAV1D_ERR(EAGAIN) && res < 0);
664 }
665 
main(int argc,char ** argv)666 int main(int argc, char **argv)
667 {
668     SDL_Thread *decoder_thread;
669 
670     // Check for version mismatch between library and tool
671     const char *version = dav1d_version();
672     if (strcmp(version, DAV1D_VERSION)) {
673         fprintf(stderr, "Version mismatch (library: %s, executable: %s)\n",
674                 version, DAV1D_VERSION);
675         return 1;
676     }
677 
678     // Create render context
679     Dav1dPlayRenderContext *rd_ctx = dp_rd_ctx_create(argc, argv);
680     if (rd_ctx == NULL) {
681         fprintf(stderr, "Failed creating render context\n");
682         return 5;
683     }
684 
685     if (rd_ctx->settings.zerocopy) {
686         if (renderer_info->alloc_pic) {
687             rd_ctx->lib_settings.allocator = (Dav1dPicAllocator) {
688                 .cookie = rd_ctx->rd_priv,
689                 .alloc_picture_callback = renderer_info->alloc_pic,
690                 .release_picture_callback = renderer_info->release_pic,
691             };
692         } else {
693             fprintf(stderr, "--zerocopy unsupported by selected renderer\n");
694         }
695     }
696 
697     if (rd_ctx->settings.gpugrain) {
698         if (renderer_info->supports_gpu_grain) {
699             rd_ctx->lib_settings.apply_grain = 0;
700         } else {
701             fprintf(stderr, "--gpugrain unsupported by selected renderer\n");
702         }
703     }
704 
705     // Start decoder thread
706     decoder_thread = SDL_CreateThread(decoder_thread_main, "Decoder thread", rd_ctx);
707 
708     // Main loop
709 #define NUM_MAX_EVENTS 8
710     SDL_Event events[NUM_MAX_EVENTS];
711     int num_frame_events = 0;
712     uint32_t start_time = 0, n_out = 0;
713     while (1) {
714         int num_events = 0;
715         SDL_WaitEvent(NULL);
716         while (num_events < NUM_MAX_EVENTS && SDL_PollEvent(&events[num_events++]))
717             break;
718         for (int i = 0; i < num_events; ++i) {
719             SDL_Event *e = &events[i];
720             if (e->type == SDL_QUIT) {
721                 dp_rd_ctx_request_shutdown(rd_ctx);
722                 dp_fifo_flush(rd_ctx->fifo, destroy_pic);
723                 goto out;
724             } else if (e->type == SDL_WINDOWEVENT) {
725                 if (e->window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
726                     // TODO: Handle window resizes
727                 } else if(e->window.event == SDL_WINDOWEVENT_EXPOSED) {
728                     dp_rd_ctx_render(rd_ctx);
729                 }
730             } else if (e->type == SDL_KEYDOWN) {
731                 SDL_KeyboardEvent *kbde = (SDL_KeyboardEvent *)e;
732                 if (kbde->keysym.sym == SDLK_SPACE) {
733                     dp_rd_ctx_toggle_pause(rd_ctx);
734                 } else if (kbde->keysym.sym == SDLK_ESCAPE) {
735                     dp_rd_ctx_request_shutdown(rd_ctx);
736                     dp_fifo_flush(rd_ctx->fifo, destroy_pic);
737                     goto out;
738                 } else if (kbde->keysym.sym == SDLK_LEFT ||
739                            kbde->keysym.sym == SDLK_RIGHT)
740                 {
741                     if (kbde->keysym.sym == SDLK_LEFT)
742                         dp_rd_ctx_seek(rd_ctx, -5);
743                     else if (kbde->keysym.sym == SDLK_RIGHT)
744                         dp_rd_ctx_seek(rd_ctx, +5);
745                     dp_fifo_flush(rd_ctx->fifo, destroy_pic);
746                     SDL_FlushEvent(rd_ctx->event_types + DAV1D_EVENT_NEW_FRAME);
747                     num_frame_events = 0;
748                 }
749             } else if (e->type == rd_ctx->event_types + DAV1D_EVENT_NEW_FRAME) {
750                 num_frame_events++;
751                 // Store current ticks for stats calculation
752                 if (start_time == 0)
753                     start_time = SDL_GetTicks();
754             } else if (e->type == rd_ctx->event_types + DAV1D_EVENT_SEEK_FRAME) {
755                 // Dequeue frame and update the render context with it
756                 Dav1dPicture *p = dp_fifo_shift(rd_ctx->fifo);
757                 // Do not update textures during termination
758                 if (!dp_rd_ctx_should_terminate(rd_ctx)) {
759                     dp_rd_ctx_update_with_dav1d_picture(rd_ctx, p);
760                     n_out++;
761                 }
762                 destroy_pic(p);
763             } else if (e->type == rd_ctx->event_types + DAV1D_EVENT_DEC_QUIT) {
764                 goto out;
765             }
766         }
767         if (num_frame_events && !dp_rd_ctx_is_paused(rd_ctx)) {
768             // Dequeue frame and update the render context with it
769             Dav1dPicture *p = dp_fifo_shift(rd_ctx->fifo);
770             // Do not update textures during termination
771             if (!dp_rd_ctx_should_terminate(rd_ctx)) {
772                 dp_rd_ctx_update_with_dav1d_picture(rd_ctx, p);
773                 dp_rd_ctx_render(rd_ctx);
774                 n_out++;
775             }
776             destroy_pic(p);
777             num_frame_events--;
778         }
779     }
780 
781 out:;
782     // Print stats
783     uint32_t time_ms = SDL_GetTicks() - start_time - rd_ctx->pause_time;
784     printf("Decoded %u frames in %d seconds, avg %.02f fps\n",
785            n_out, time_ms / 1000, n_out/ (time_ms / 1000.0));
786 
787     int decoder_ret = 0;
788     SDL_WaitThread(decoder_thread, &decoder_ret);
789     dp_rd_ctx_destroy(rd_ctx);
790     SDL_Quit();
791     return decoder_ret;
792 }
793