• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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             " --version/-v:         print version and exit\n"
124             " --renderer/-r:        select renderer backend (default: auto)\n");
125     exit(1);
126 }
127 
parse_unsigned(const char * const optarg,const int option,const char * const app)128 static unsigned parse_unsigned(const char *const optarg, const int option,
129                                const char *const app)
130 {
131     char *end;
132     const unsigned res = (unsigned) strtoul(optarg, &end, 0);
133     if (*end || end == optarg)
134         dp_settings_print_usage(app, "Invalid argument \"%s\" for option %s; should be an integer",
135           optarg, option);
136     return res;
137 }
138 
dp_rd_ctx_parse_args(Dav1dPlayRenderContext * rd_ctx,const int argc,char * const * const argv)139 static void dp_rd_ctx_parse_args(Dav1dPlayRenderContext *rd_ctx,
140                                  const int argc, char *const *const argv)
141 {
142     int o;
143     Dav1dPlaySettings *settings = &rd_ctx->settings;
144     Dav1dSettings *lib_settings = &rd_ctx->lib_settings;
145 
146     // Short options
147     static const char short_opts[] = "i:vuzgr:";
148 
149     enum {
150         ARG_THREADS = 256,
151         ARG_FRAME_DELAY,
152         ARG_HIGH_QUALITY,
153     };
154 
155     // Long options
156     static const struct option long_opts[] = {
157         { "input",          1, NULL, 'i' },
158         { "version",        0, NULL, 'v' },
159         { "untimed",        0, NULL, 'u' },
160         { "threads",        1, NULL, ARG_THREADS },
161         { "framedelay",     1, NULL, ARG_FRAME_DELAY },
162         { "highquality",    0, NULL, ARG_HIGH_QUALITY },
163         { "zerocopy",       0, NULL, 'z' },
164         { "gpugrain",       0, NULL, 'g' },
165         { "renderer",       0, NULL, 'r'},
166         { NULL,             0, NULL, 0 },
167     };
168 
169     while ((o = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
170         switch (o) {
171             case 'i':
172                 settings->inputfile = optarg;
173                 break;
174             case 'v':
175                 fprintf(stderr, "%s\n", dav1d_version());
176                 exit(0);
177             case 'u':
178                 settings->untimed = true;
179                 break;
180             case ARG_HIGH_QUALITY:
181                 settings->highquality = true;
182                 break;
183             case 'z':
184                 settings->zerocopy = true;
185                 break;
186             case 'g':
187                 settings->gpugrain = true;
188                 break;
189             case 'r':
190                 settings->renderer_name = optarg;
191                 break;
192             case ARG_THREADS:
193                 lib_settings->n_threads =
194                     parse_unsigned(optarg, ARG_THREADS, argv[0]);
195                 break;
196             case ARG_FRAME_DELAY:
197                 lib_settings->max_frame_delay =
198                     parse_unsigned(optarg, ARG_FRAME_DELAY, argv[0]);
199                 break;
200             default:
201                 dp_settings_print_usage(argv[0], NULL);
202         }
203     }
204 
205     if (optind < argc)
206         dp_settings_print_usage(argv[0],
207             "Extra/unused arguments found, e.g. '%s'\n", argv[optind]);
208     if (!settings->inputfile)
209         dp_settings_print_usage(argv[0], "Input file (-i/--input) is required");
210     if (settings->renderer_name && strcmp(settings->renderer_name, "auto") == 0)
211         settings->renderer_name = NULL;
212 }
213 
214 /**
215  * Destroy a Dav1dPlayRenderContext
216  */
dp_rd_ctx_destroy(Dav1dPlayRenderContext * rd_ctx)217 static void dp_rd_ctx_destroy(Dav1dPlayRenderContext *rd_ctx)
218 {
219     assert(rd_ctx != NULL);
220 
221     renderer_info->destroy_renderer(rd_ctx->rd_priv);
222     dp_fifo_destroy(rd_ctx->fifo);
223     SDL_DestroyMutex(rd_ctx->lock);
224     free(rd_ctx);
225 }
226 
227 /**
228  * Create a Dav1dPlayRenderContext
229  *
230  * \note  The Dav1dPlayRenderContext must be destroyed
231  *        again by using dp_rd_ctx_destroy.
232  */
dp_rd_ctx_create(int argc,char ** argv)233 static Dav1dPlayRenderContext *dp_rd_ctx_create(int argc, char **argv)
234 {
235     Dav1dPlayRenderContext *rd_ctx;
236 
237     // Alloc
238     rd_ctx = calloc(1, sizeof(Dav1dPlayRenderContext));
239     if (rd_ctx == NULL) {
240         return NULL;
241     }
242 
243     // Register a custom event to notify our SDL main thread
244     // about new frames
245     rd_ctx->event_types = SDL_RegisterEvents(3);
246     if (rd_ctx->event_types == UINT32_MAX) {
247         fprintf(stderr, "Failure to create custom SDL event types!\n");
248         free(rd_ctx);
249         return NULL;
250     }
251 
252     rd_ctx->fifo = dp_fifo_create(5);
253     if (rd_ctx->fifo == NULL) {
254         fprintf(stderr, "Failed to create FIFO for output pictures!\n");
255         free(rd_ctx);
256         return NULL;
257     }
258 
259     rd_ctx->lock = SDL_CreateMutex();
260     if (rd_ctx->lock == NULL) {
261         fprintf(stderr, "SDL_CreateMutex failed: %s\n", SDL_GetError());
262         dp_fifo_destroy(rd_ctx->fifo);
263         free(rd_ctx);
264         return NULL;
265     }
266 
267     // Parse and validate arguments
268     dav1d_default_settings(&rd_ctx->lib_settings);
269     memset(&rd_ctx->settings, 0, sizeof(rd_ctx->settings));
270     dp_rd_ctx_parse_args(rd_ctx, argc, argv);
271 
272     // Select renderer
273     renderer_info = dp_get_renderer(rd_ctx->settings.renderer_name);
274 
275     if (renderer_info == NULL) {
276         printf("No suitable renderer matching %s found.\n",
277             (rd_ctx->settings.renderer_name) ? rd_ctx->settings.renderer_name : "auto");
278     } else {
279         printf("Using %s renderer\n", renderer_info->name);
280     }
281 
282     rd_ctx->rd_priv = (renderer_info) ? renderer_info->create_renderer() : NULL;
283     if (rd_ctx->rd_priv == NULL) {
284         SDL_DestroyMutex(rd_ctx->lock);
285         dp_fifo_destroy(rd_ctx->fifo);
286         free(rd_ctx);
287         return NULL;
288     }
289 
290     return rd_ctx;
291 }
292 
293 /**
294  * Notify about new event
295  */
dp_rd_ctx_post_event(Dav1dPlayRenderContext * rd_ctx,uint32_t type)296 static void dp_rd_ctx_post_event(Dav1dPlayRenderContext *rd_ctx, uint32_t type)
297 {
298     SDL_Event event;
299     SDL_zero(event);
300     event.type = type;
301     SDL_PushEvent(&event);
302 }
303 
304 /**
305  * Update the decoder context with a new dav1d picture
306  *
307  * Once the decoder decoded a new picture, this call can be used
308  * to update the internal texture of the render context with the
309  * new picture.
310  */
dp_rd_ctx_update_with_dav1d_picture(Dav1dPlayRenderContext * rd_ctx,Dav1dPicture * dav1d_pic)311 static void dp_rd_ctx_update_with_dav1d_picture(Dav1dPlayRenderContext *rd_ctx,
312                                                 Dav1dPicture *dav1d_pic)
313 {
314     rd_ctx->current_ts = dav1d_pic->m.timestamp;
315     renderer_info->update_frame(rd_ctx->rd_priv, dav1d_pic, &rd_ctx->settings);
316 }
317 
318 /**
319  * Toggle pause state
320  */
dp_rd_ctx_toggle_pause(Dav1dPlayRenderContext * rd_ctx)321 static void dp_rd_ctx_toggle_pause(Dav1dPlayRenderContext *rd_ctx)
322 {
323     SDL_LockMutex(rd_ctx->lock);
324     rd_ctx->user_paused = !rd_ctx->user_paused;
325     if (rd_ctx->seek)
326         goto out;
327     rd_ctx->paused = rd_ctx->user_paused;
328     uint32_t now = SDL_GetTicks();
329     if (rd_ctx->paused)
330         rd_ctx->pause_start = now;
331     else {
332         rd_ctx->pause_time += now - rd_ctx->pause_start;
333         rd_ctx->pause_start = 0;
334         rd_ctx->last_ticks = now;
335     }
336 out:
337     SDL_UnlockMutex(rd_ctx->lock);
338 }
339 
340 /**
341  * Query pause state
342  */
dp_rd_ctx_is_paused(Dav1dPlayRenderContext * rd_ctx)343 static int dp_rd_ctx_is_paused(Dav1dPlayRenderContext *rd_ctx)
344 {
345     int ret;
346     SDL_LockMutex(rd_ctx->lock);
347     ret = rd_ctx->paused;
348     SDL_UnlockMutex(rd_ctx->lock);
349     return ret;
350 }
351 
352 /**
353  * Request seeking, in seconds
354  */
dp_rd_ctx_seek(Dav1dPlayRenderContext * rd_ctx,int sec)355 static void dp_rd_ctx_seek(Dav1dPlayRenderContext *rd_ctx, int sec)
356 {
357     SDL_LockMutex(rd_ctx->lock);
358     rd_ctx->seek += sec;
359     if (!rd_ctx->paused)
360         rd_ctx->pause_start = SDL_GetTicks();
361     rd_ctx->paused = 1;
362     SDL_UnlockMutex(rd_ctx->lock);
363 }
364 
365 static int decode_frame(Dav1dPicture **p, Dav1dContext *c,
366                         Dav1dData *data, DemuxerContext *in_ctx);
367 static inline void destroy_pic(void *a);
368 
369 /**
370  * Seek the stream, if requested
371  */
dp_rd_ctx_handle_seek(Dav1dPlayRenderContext * rd_ctx,DemuxerContext * in_ctx,Dav1dContext * c,Dav1dData * data)372 static int dp_rd_ctx_handle_seek(Dav1dPlayRenderContext *rd_ctx,
373                                  DemuxerContext *in_ctx,
374                                  Dav1dContext *c, Dav1dData *data)
375 {
376     int res = 0;
377     SDL_LockMutex(rd_ctx->lock);
378     if (!rd_ctx->seek)
379         goto out;
380     int64_t seek = rd_ctx->seek * 1000000000ULL;
381     uint64_t pts = TS_TO_PTS(rd_ctx->current_ts);
382     pts = ((int64_t)pts > -seek) ? pts + seek : 0;
383     int end = pts >= FRAME_OFFSET_TO_PTS(rd_ctx->total);
384     if (end)
385         pts = FRAME_OFFSET_TO_PTS(rd_ctx->total - 1);
386     uint64_t target_pts = pts;
387     dav1d_flush(c);
388     uint64_t shift = FRAME_OFFSET_TO_PTS(5);
389     while (1) {
390         if (shift > pts)
391             shift = pts;
392         if ((res = input_seek(in_ctx, pts - shift)))
393             goto out;
394         Dav1dSequenceHeader seq;
395         uint64_t cur_pts;
396         do {
397             if ((res = input_read(in_ctx, data)))
398                 break;
399             cur_pts = TS_TO_PTS(data->m.timestamp);
400             res = dav1d_parse_sequence_header(&seq, data->data, data->sz);
401         } while (res && cur_pts < pts);
402         if (!res && cur_pts <= pts)
403             break;
404         if (shift > pts)
405             shift = pts;
406         pts -= shift;
407     }
408     if (!res) {
409         pts = TS_TO_PTS(data->m.timestamp);
410         while (pts < target_pts) {
411             Dav1dPicture *p;
412             if ((res = decode_frame(&p, c, data, in_ctx)))
413                 break;
414             if (p) {
415                 pts = TS_TO_PTS(p->m.timestamp);
416                 if (pts < target_pts)
417                     destroy_pic(p);
418                 else {
419                     dp_fifo_push(rd_ctx->fifo, p);
420                     uint32_t type = rd_ctx->event_types + DAV1D_EVENT_SEEK_FRAME;
421                     dp_rd_ctx_post_event(rd_ctx, type);
422                 }
423             }
424         }
425         if (!res) {
426             rd_ctx->last_ts = data->m.timestamp - rd_ctx->spf / rd_ctx->timebase;
427             rd_ctx->current_ts = data->m.timestamp;
428         }
429     }
430 out:
431     rd_ctx->paused = rd_ctx->user_paused;
432     if (!rd_ctx->paused && rd_ctx->seek) {
433         uint32_t now = SDL_GetTicks();
434         rd_ctx->pause_time += now - rd_ctx->pause_start;
435         rd_ctx->pause_start = 0;
436         rd_ctx->last_ticks = now;
437     }
438     rd_ctx->seek = 0;
439     SDL_UnlockMutex(rd_ctx->lock);
440     if (res)
441         fprintf(stderr, "Error seeking, aborting\n");
442     return res;
443 }
444 
445 /**
446  * Terminate decoder thread (async)
447  */
dp_rd_ctx_request_shutdown(Dav1dPlayRenderContext * rd_ctx)448 static void dp_rd_ctx_request_shutdown(Dav1dPlayRenderContext *rd_ctx)
449 {
450     SDL_LockMutex(rd_ctx->lock);
451     rd_ctx->dec_should_terminate = 1;
452     SDL_UnlockMutex(rd_ctx->lock);
453 }
454 
455 /**
456  * Query state of decoder shutdown request
457  */
dp_rd_ctx_should_terminate(Dav1dPlayRenderContext * rd_ctx)458 static int dp_rd_ctx_should_terminate(Dav1dPlayRenderContext *rd_ctx)
459 {
460     int ret = 0;
461     SDL_LockMutex(rd_ctx->lock);
462     ret = rd_ctx->dec_should_terminate;
463     SDL_UnlockMutex(rd_ctx->lock);
464     return ret;
465 }
466 
467 /**
468  * Render the currently available texture
469  *
470  * Renders the currently available texture, if any.
471  */
dp_rd_ctx_render(Dav1dPlayRenderContext * rd_ctx)472 static void dp_rd_ctx_render(Dav1dPlayRenderContext *rd_ctx)
473 {
474     SDL_LockMutex(rd_ctx->lock);
475     // Calculate time since last frame was received
476     uint32_t ticks_now = SDL_GetTicks();
477     uint32_t ticks_diff = (rd_ctx->last_ticks != 0) ? ticks_now - rd_ctx->last_ticks : 0;
478 
479     // Calculate when to display the frame
480     int64_t ts_diff = rd_ctx->current_ts - rd_ctx->last_ts;
481     int32_t pts_diff = (ts_diff * rd_ctx->timebase) * 1000.0 + .5;
482     int32_t wait_time = pts_diff - ticks_diff;
483 
484     // In untimed mode, simply don't wait
485     if (rd_ctx->settings.untimed)
486         wait_time = 0;
487 
488     // This way of timing the playback is not accurate, as there is no guarantee
489     // that SDL_Delay will wait for exactly the requested amount of time so in a
490     // accurate player this would need to be done in a better way.
491     if (wait_time > 0) {
492         SDL_Delay(wait_time);
493     } else if (wait_time < -10 && !rd_ctx->paused) { // Do not warn for minor time drifts
494         fprintf(stderr, "Frame displayed %f seconds too late\n", wait_time / 1000.0);
495     }
496 
497     renderer_info->render(rd_ctx->rd_priv, &rd_ctx->settings);
498 
499     rd_ctx->last_ts = rd_ctx->current_ts;
500     rd_ctx->last_ticks = SDL_GetTicks();
501 
502     SDL_UnlockMutex(rd_ctx->lock);
503 }
504 
decode_frame(Dav1dPicture ** p,Dav1dContext * c,Dav1dData * data,DemuxerContext * in_ctx)505 static int decode_frame(Dav1dPicture **p, Dav1dContext *c,
506                         Dav1dData *data, DemuxerContext *in_ctx)
507 {
508     int res;
509     // Send data packets we got from the demuxer to dav1d
510     if ((res = dav1d_send_data(c, data)) < 0) {
511         // On EAGAIN, dav1d can not consume more data and
512         // dav1d_get_picture needs to be called first, which
513         // will happen below, so just keep going in that case
514         // and do not error out.
515         if (res != DAV1D_ERR(EAGAIN)) {
516             dav1d_data_unref(data);
517             goto err;
518         }
519     }
520     *p = calloc(1, sizeof(**p));
521     // Try to get a decoded frame
522     if ((res = dav1d_get_picture(c, *p)) < 0) {
523         // In all error cases, even EAGAIN, p needs to be freed as
524         // it is never added to the queue and would leak.
525         free(*p);
526         *p = NULL;
527         // On EAGAIN, it means dav1d has not enough data to decode
528         // therefore this is not a decoding error but just means
529         // we need to feed it more data, which happens in the next
530         // run of the decoder loop.
531         if (res != DAV1D_ERR(EAGAIN))
532             goto err;
533     }
534     return data->sz == 0 ? input_read(in_ctx, data) : 0;
535 err:
536     fprintf(stderr, "Error decoding frame: %s\n",
537             strerror(-res));
538     return res;
539 }
540 
destroy_pic(void * a)541 static inline void destroy_pic(void *a)
542 {
543     Dav1dPicture *p = (Dav1dPicture *)a;
544     dav1d_picture_unref(p);
545     free(p);
546 }
547 
548 /* Decoder thread "main" function */
decoder_thread_main(void * cookie)549 static int decoder_thread_main(void *cookie)
550 {
551     Dav1dPlayRenderContext *rd_ctx = cookie;
552 
553     Dav1dPicture *p;
554     Dav1dContext *c = NULL;
555     Dav1dData data;
556     DemuxerContext *in_ctx = NULL;
557     int res = 0;
558     unsigned total, timebase[2], fps[2];
559 
560     Dav1dPlaySettings settings = rd_ctx->settings;
561 
562     if ((res = input_open(&in_ctx, "ivf",
563                           settings.inputfile,
564                           fps, &total, timebase)) < 0)
565     {
566         fprintf(stderr, "Failed to open demuxer\n");
567         res = 1;
568         goto cleanup;
569     }
570 
571     rd_ctx->timebase = (double)timebase[1] / timebase[0];
572     rd_ctx->spf = (double)fps[1] / fps[0];
573     rd_ctx->total = total;
574 
575     if ((res = dav1d_open(&c, &rd_ctx->lib_settings))) {
576         fprintf(stderr, "Failed opening dav1d decoder\n");
577         res = 1;
578         goto cleanup;
579     }
580 
581     if ((res = input_read(in_ctx, &data)) < 0) {
582         fprintf(stderr, "Failed demuxing input\n");
583         res = 1;
584         goto cleanup;
585     }
586 
587     // Decoder loop
588     while (1) {
589         if (dp_rd_ctx_should_terminate(rd_ctx) ||
590             (res = dp_rd_ctx_handle_seek(rd_ctx, in_ctx, c, &data)) ||
591             (res = decode_frame(&p, c, &data, in_ctx)))
592         {
593             break;
594         }
595         else if (p) {
596             // Queue frame
597             SDL_LockMutex(rd_ctx->lock);
598             int seek = rd_ctx->seek;
599             SDL_UnlockMutex(rd_ctx->lock);
600             if (!seek) {
601                 dp_fifo_push(rd_ctx->fifo, p);
602                 uint32_t type = rd_ctx->event_types + DAV1D_EVENT_NEW_FRAME;
603                 dp_rd_ctx_post_event(rd_ctx, type);
604             }
605         }
606     }
607 
608     // Release remaining data
609     if (data.sz > 0)
610         dav1d_data_unref(&data);
611     // Do not drain in case an error occured and caused us to leave the
612     // decoding loop early.
613     if (res < 0)
614         goto cleanup;
615 
616     // Drain decoder
617     // When there is no more data to feed to the decoder, for example
618     // because the file ended, we still need to request pictures, as
619     // even though we do not have more data, there can be frames decoded
620     // from data we sent before. So we need to call dav1d_get_picture until
621     // we get an EAGAIN error.
622     do {
623         if (dp_rd_ctx_should_terminate(rd_ctx))
624             break;
625         p = calloc(1, sizeof(*p));
626         res = dav1d_get_picture(c, p);
627         if (res < 0) {
628             free(p);
629             if (res != DAV1D_ERR(EAGAIN)) {
630                 fprintf(stderr, "Error decoding frame: %s\n",
631                         strerror(-res));
632                 break;
633             }
634         } else {
635             // Queue frame
636             dp_fifo_push(rd_ctx->fifo, p);
637             uint32_t type = rd_ctx->event_types + DAV1D_EVENT_NEW_FRAME;
638             dp_rd_ctx_post_event(rd_ctx, type);
639         }
640     } while (res != DAV1D_ERR(EAGAIN));
641 
642 cleanup:
643     dp_rd_ctx_post_event(rd_ctx, rd_ctx->event_types + DAV1D_EVENT_DEC_QUIT);
644 
645     if (in_ctx)
646         input_close(in_ctx);
647     if (c)
648         dav1d_close(&c);
649 
650     return (res != DAV1D_ERR(EAGAIN) && res < 0);
651 }
652 
main(int argc,char ** argv)653 int main(int argc, char **argv)
654 {
655     SDL_Thread *decoder_thread;
656 
657     // Check for version mismatch between library and tool
658     const char *version = dav1d_version();
659     if (strcmp(version, DAV1D_VERSION)) {
660         fprintf(stderr, "Version mismatch (library: %s, executable: %s)\n",
661                 version, DAV1D_VERSION);
662         return 1;
663     }
664 
665     // Init SDL2 library
666     if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0)
667         return 10;
668 
669     // Create render context
670     Dav1dPlayRenderContext *rd_ctx = dp_rd_ctx_create(argc, argv);
671     if (rd_ctx == NULL) {
672         fprintf(stderr, "Failed creating render context\n");
673         return 5;
674     }
675 
676     if (rd_ctx->settings.zerocopy) {
677         if (renderer_info->alloc_pic) {
678             rd_ctx->lib_settings.allocator = (Dav1dPicAllocator) {
679                 .cookie = rd_ctx->rd_priv,
680                 .alloc_picture_callback = renderer_info->alloc_pic,
681                 .release_picture_callback = renderer_info->release_pic,
682             };
683         } else {
684             fprintf(stderr, "--zerocopy unsupported by selected renderer\n");
685         }
686     }
687 
688     if (rd_ctx->settings.gpugrain) {
689         if (renderer_info->supports_gpu_grain) {
690             rd_ctx->lib_settings.apply_grain = 0;
691         } else {
692             fprintf(stderr, "--gpugrain unsupported by selected renderer\n");
693         }
694     }
695 
696     // Start decoder thread
697     decoder_thread = SDL_CreateThread(decoder_thread_main, "Decoder thread", rd_ctx);
698 
699     // Main loop
700 #define NUM_MAX_EVENTS 8
701     SDL_Event events[NUM_MAX_EVENTS];
702     int num_frame_events = 0;
703     uint32_t start_time = 0, n_out = 0;
704     while (1) {
705         int num_events = 0;
706         SDL_WaitEvent(NULL);
707         while (num_events < NUM_MAX_EVENTS && SDL_PollEvent(&events[num_events++]))
708             break;
709         for (int i = 0; i < num_events; ++i) {
710             SDL_Event *e = &events[i];
711             if (e->type == SDL_QUIT) {
712                 dp_rd_ctx_request_shutdown(rd_ctx);
713                 dp_fifo_flush(rd_ctx->fifo, destroy_pic);
714                 SDL_FlushEvent(rd_ctx->event_types + DAV1D_EVENT_NEW_FRAME);
715                 SDL_FlushEvent(rd_ctx->event_types + DAV1D_EVENT_SEEK_FRAME);
716                 num_frame_events = 0;
717             } else if (e->type == SDL_WINDOWEVENT) {
718                 if (e->window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
719                     // TODO: Handle window resizes
720                 } else if(e->window.event == SDL_WINDOWEVENT_EXPOSED) {
721                     dp_rd_ctx_render(rd_ctx);
722                 }
723             } else if (e->type == SDL_KEYDOWN) {
724                 SDL_KeyboardEvent *kbde = (SDL_KeyboardEvent *)e;
725                 if (kbde->keysym.sym == SDLK_SPACE) {
726                     dp_rd_ctx_toggle_pause(rd_ctx);
727                 } else if (kbde->keysym.sym == SDLK_LEFT ||
728                            kbde->keysym.sym == SDLK_RIGHT)
729                 {
730                     if (kbde->keysym.sym == SDLK_LEFT)
731                         dp_rd_ctx_seek(rd_ctx, -5);
732                     else if (kbde->keysym.sym == SDLK_RIGHT)
733                         dp_rd_ctx_seek(rd_ctx, +5);
734                     dp_fifo_flush(rd_ctx->fifo, destroy_pic);
735                     SDL_FlushEvent(rd_ctx->event_types + DAV1D_EVENT_NEW_FRAME);
736                     num_frame_events = 0;
737                 }
738             } else if (e->type == rd_ctx->event_types + DAV1D_EVENT_NEW_FRAME) {
739                 num_frame_events++;
740                 // Store current ticks for stats calculation
741                 if (start_time == 0)
742                     start_time = SDL_GetTicks();
743             } else if (e->type == rd_ctx->event_types + DAV1D_EVENT_SEEK_FRAME) {
744                 // Dequeue frame and update the render context with it
745                 Dav1dPicture *p = dp_fifo_shift(rd_ctx->fifo);
746                 // Do not update textures during termination
747                 if (!dp_rd_ctx_should_terminate(rd_ctx)) {
748                     dp_rd_ctx_update_with_dav1d_picture(rd_ctx, p);
749                     n_out++;
750                 }
751                 destroy_pic(p);
752             } else if (e->type == rd_ctx->event_types + DAV1D_EVENT_DEC_QUIT) {
753                 goto out;
754             }
755         }
756         if (num_frame_events && !dp_rd_ctx_is_paused(rd_ctx)) {
757             // Dequeue frame and update the render context with it
758             Dav1dPicture *p = dp_fifo_shift(rd_ctx->fifo);
759             // Do not update textures during termination
760             if (!dp_rd_ctx_should_terminate(rd_ctx)) {
761                 dp_rd_ctx_update_with_dav1d_picture(rd_ctx, p);
762                 dp_rd_ctx_render(rd_ctx);
763                 n_out++;
764             }
765             destroy_pic(p);
766             num_frame_events--;
767         }
768     }
769 
770 out:;
771     // Print stats
772     uint32_t time_ms = SDL_GetTicks() - start_time - rd_ctx->pause_time;
773     printf("Decoded %u frames in %d seconds, avg %.02f fps\n",
774            n_out, time_ms / 1000, n_out/ (time_ms / 1000.0));
775 
776     int decoder_ret = 0;
777     SDL_WaitThread(decoder_thread, &decoder_ret);
778     dp_rd_ctx_destroy(rd_ctx);
779     return decoder_ret;
780 }
781