]> git.sesse.net Git - ffmpeg/blob - libavformat/async.c
Merge commit '16b0c929621f84983b83b9735ce973acb12723bc'
[ffmpeg] / libavformat / async.c
1 /*
2  * Input async protocol.
3  * Copyright (c) 2015 Zhang Rui <bbcallen@gmail.com>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  *
21  * Based on libavformat/cache.c by Michael Niedermayer
22  */
23
24  /**
25  * @TODO
26  *      support timeout
27  *      support backward short seek
28  *      support work with concatdec, hls
29  */
30
31 #include "libavutil/avassert.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/error.h"
34 #include "libavutil/fifo.h"
35 #include "libavutil/log.h"
36 #include "libavutil/opt.h"
37 #include "libavutil/thread.h"
38 #include "url.h"
39 #include <stdint.h>
40
41 #if HAVE_UNISTD_H
42 #include <unistd.h>
43 #endif
44
45 #define BUFFER_CAPACITY         (4 * 1024 * 1024)
46 #define SHORT_SEEK_THRESHOLD    (256 * 1024)
47
48 typedef struct Context {
49     AVClass        *class;
50     URLContext     *inner;
51
52     int             seek_request;
53     int64_t         seek_pos;
54     int             seek_whence;
55     int             seek_completed;
56     int64_t         seek_ret;
57
58     int             inner_io_error;
59     int             io_error;
60     int             io_eof_reached;
61
62     int64_t         logical_pos;
63     int64_t         logical_size;
64     AVFifoBuffer   *fifo;
65
66     pthread_cond_t  cond_wakeup_main;
67     pthread_cond_t  cond_wakeup_background;
68     pthread_mutex_t mutex;
69     pthread_t       async_buffer_thread;
70
71     int             abort_request;
72     AVIOInterruptCB interrupt_callback;
73 } Context;
74
75 static int async_check_interrupt(void *arg)
76 {
77     URLContext *h   = arg;
78     Context    *c   = h->priv_data;
79
80     if (c->abort_request)
81         return 1;
82
83     if (ff_check_interrupt(&c->interrupt_callback))
84         c->abort_request = 1;
85
86     return c->abort_request;
87 }
88
89 static int wrapped_url_read(void *src, void *dst, int size)
90 {
91     URLContext *h   = src;
92     Context    *c   = h->priv_data;
93     int         ret;
94
95     ret = ffurl_read(c->inner, dst, size);
96     c->inner_io_error = ret < 0 ? ret : 0;
97
98     return ret;
99 }
100
101 static void *async_buffer_task(void *arg)
102 {
103     URLContext   *h    = arg;
104     Context      *c    = h->priv_data;
105     AVFifoBuffer *fifo = c->fifo;
106     int           ret  = 0;
107     int64_t       seek_ret;
108
109     while (1) {
110         int fifo_space, to_copy;
111
112         pthread_mutex_lock(&c->mutex);
113         if (async_check_interrupt(h)) {
114             c->io_eof_reached = 1;
115             c->io_error       = AVERROR_EXIT;
116             pthread_cond_signal(&c->cond_wakeup_main);
117             pthread_mutex_unlock(&c->mutex);
118             break;
119         }
120
121         if (c->seek_request) {
122             seek_ret = ffurl_seek(c->inner, c->seek_pos, c->seek_whence);
123             if (seek_ret < 0) {
124                 c->io_eof_reached = 1;
125                 c->io_error       = (int)seek_ret;
126             } else {
127                 c->io_eof_reached = 0;
128                 c->io_error       = 0;
129             }
130
131             c->seek_completed = 1;
132             c->seek_ret       = seek_ret;
133             c->seek_request   = 0;
134
135             av_fifo_reset(fifo);
136
137             pthread_cond_signal(&c->cond_wakeup_main);
138             pthread_mutex_unlock(&c->mutex);
139             continue;
140         }
141
142         fifo_space = av_fifo_space(fifo);
143         if (c->io_eof_reached || fifo_space <= 0) {
144             pthread_cond_signal(&c->cond_wakeup_main);
145             pthread_cond_wait(&c->cond_wakeup_background, &c->mutex);
146             pthread_mutex_unlock(&c->mutex);
147             continue;
148         }
149         pthread_mutex_unlock(&c->mutex);
150
151         to_copy = FFMIN(4096, fifo_space);
152         ret = av_fifo_generic_write(fifo, (void *)h, to_copy, (void *)wrapped_url_read);
153
154         pthread_mutex_lock(&c->mutex);
155         if (ret <= 0) {
156             c->io_eof_reached = 1;
157             if (c->inner_io_error < 0)
158                 c->io_error = c->inner_io_error;
159         }
160
161         pthread_cond_signal(&c->cond_wakeup_main);
162         pthread_mutex_unlock(&c->mutex);
163     }
164
165     return NULL;
166 }
167
168 static int async_open(URLContext *h, const char *arg, int flags, AVDictionary **options)
169 {
170     Context         *c = h->priv_data;
171     int              ret;
172     AVIOInterruptCB  interrupt_callback = {.callback = async_check_interrupt, .opaque = h};
173
174     av_strstart(arg, "async:", &arg);
175
176     c->fifo = av_fifo_alloc(BUFFER_CAPACITY);
177     if (!c->fifo) {
178         ret = AVERROR(ENOMEM);
179         goto fifo_fail;
180     }
181
182     /* wrap interrupt callback */
183     c->interrupt_callback = h->interrupt_callback;
184     ret = ffurl_open(&c->inner, arg, flags, &interrupt_callback, options);
185     if (ret != 0) {
186         av_log(h, AV_LOG_ERROR, "ffurl_open failed : %s, %s\n", av_err2str(ret), arg);
187         goto url_fail;
188     }
189
190     c->logical_size = ffurl_size(c->inner);
191     h->is_streamed  = c->inner->is_streamed;
192
193     ret = pthread_mutex_init(&c->mutex, NULL);
194     if (ret != 0) {
195         av_log(h, AV_LOG_ERROR, "pthread_mutex_init failed : %s\n", av_err2str(ret));
196         goto mutex_fail;
197     }
198
199     ret = pthread_cond_init(&c->cond_wakeup_main, NULL);
200     if (ret != 0) {
201         av_log(h, AV_LOG_ERROR, "pthread_cond_init failed : %s\n", av_err2str(ret));
202         goto cond_wakeup_main_fail;
203     }
204
205     ret = pthread_cond_init(&c->cond_wakeup_background, NULL);
206     if (ret != 0) {
207         av_log(h, AV_LOG_ERROR, "pthread_cond_init failed : %s\n", av_err2str(ret));
208         goto cond_wakeup_background_fail;
209     }
210
211     ret = pthread_create(&c->async_buffer_thread, NULL, async_buffer_task, h);
212     if (ret) {
213         av_log(h, AV_LOG_ERROR, "pthread_create failed : %s\n", av_err2str(ret));
214         goto thread_fail;
215     }
216
217     return 0;
218
219 thread_fail:
220     pthread_cond_destroy(&c->cond_wakeup_background);
221 cond_wakeup_background_fail:
222     pthread_cond_destroy(&c->cond_wakeup_main);
223 cond_wakeup_main_fail:
224     pthread_mutex_destroy(&c->mutex);
225 mutex_fail:
226     ffurl_close(c->inner);
227 url_fail:
228     av_fifo_freep(&c->fifo);
229 fifo_fail:
230     return ret;
231 }
232
233 static int async_close(URLContext *h)
234 {
235     Context *c = h->priv_data;
236     int      ret;
237
238     pthread_mutex_lock(&c->mutex);
239     c->abort_request = 1;
240     pthread_cond_signal(&c->cond_wakeup_background);
241     pthread_mutex_unlock(&c->mutex);
242
243     ret = pthread_join(c->async_buffer_thread, NULL);
244     if (ret != 0)
245         av_log(h, AV_LOG_ERROR, "pthread_join(): %s\n", av_err2str(ret));
246
247     pthread_cond_destroy(&c->cond_wakeup_background);
248     pthread_cond_destroy(&c->cond_wakeup_main);
249     pthread_mutex_destroy(&c->mutex);
250     ffurl_close(c->inner);
251     av_fifo_freep(&c->fifo);
252
253     return 0;
254 }
255
256 static int async_read_internal(URLContext *h, void *dest, int size, int read_complete,
257                                void (*func)(void*, void*, int))
258 {
259     Context      *c       = h->priv_data;
260     AVFifoBuffer *fifo    = c->fifo;
261     int           to_read = size;
262     int           ret     = 0;
263
264     pthread_mutex_lock(&c->mutex);
265
266     while (to_read > 0) {
267         int fifo_size, to_copy;
268         if (async_check_interrupt(h)) {
269             ret = AVERROR_EXIT;
270             break;
271         }
272         fifo_size = av_fifo_size(fifo);
273         to_copy   = FFMIN(to_read, fifo_size);
274         if (to_copy > 0) {
275             av_fifo_generic_read(fifo, dest, to_copy, func);
276             if (!func)
277                 dest = (uint8_t *)dest + to_copy;
278             c->logical_pos += to_copy;
279             to_read        -= to_copy;
280             ret             = size - to_read;
281
282             if (to_read <= 0 || !read_complete)
283                 break;
284         } else if (c->io_eof_reached) {
285             if (ret <= 0) {
286                 if (c->io_error)
287                     ret = c->io_error;
288                 else
289                     ret = AVERROR_EOF;
290             }
291             break;
292         }
293         pthread_cond_signal(&c->cond_wakeup_background);
294         pthread_cond_wait(&c->cond_wakeup_main, &c->mutex);
295     }
296
297     pthread_cond_signal(&c->cond_wakeup_background);
298     pthread_mutex_unlock(&c->mutex);
299
300     return ret;
301 }
302
303 static int async_read(URLContext *h, unsigned char *buf, int size)
304 {
305     return async_read_internal(h, buf, size, 0, NULL);
306 }
307
308 static void fifo_do_not_copy_func(void* dest, void* src, int size) {
309     // do not copy
310 }
311
312 static int64_t async_seek(URLContext *h, int64_t pos, int whence)
313 {
314     Context      *c    = h->priv_data;
315     AVFifoBuffer *fifo = c->fifo;
316     int64_t       ret;
317     int64_t       new_logical_pos;
318     int fifo_size;
319
320     if (whence == AVSEEK_SIZE) {
321         av_log(h, AV_LOG_TRACE, "async_seek: AVSEEK_SIZE: %"PRId64"\n", (int64_t)c->logical_size);
322         return c->logical_size;
323     } else if (whence == SEEK_CUR) {
324         av_log(h, AV_LOG_TRACE, "async_seek: %"PRId64"\n", pos);
325         new_logical_pos = pos + c->logical_pos;
326     } else if (whence == SEEK_SET){
327         av_log(h, AV_LOG_TRACE, "async_seek: %"PRId64"\n", pos);
328         new_logical_pos = pos;
329     } else {
330         return AVERROR(EINVAL);
331     }
332     if (new_logical_pos < 0)
333         return AVERROR(EINVAL);
334
335     fifo_size = av_fifo_size(fifo);
336     if (new_logical_pos == c->logical_pos) {
337         /* current position */
338         return c->logical_pos;
339     } else if ((new_logical_pos > c->logical_pos) &&
340                (new_logical_pos < (c->logical_pos + fifo_size + SHORT_SEEK_THRESHOLD))) {
341         /* fast seek */
342         av_log(h, AV_LOG_TRACE, "async_seek: fask_seek %"PRId64" from %d dist:%d/%d\n",
343                 new_logical_pos, (int)c->logical_pos,
344                 (int)(new_logical_pos - c->logical_pos), fifo_size);
345         async_read_internal(h, NULL, (int)(new_logical_pos - c->logical_pos), 1, fifo_do_not_copy_func);
346         return c->logical_pos;
347     } else if (c->logical_size <= 0) {
348         /* can not seek */
349         return AVERROR(EINVAL);
350     } else if (new_logical_pos > c->logical_size) {
351         /* beyond end */
352         return AVERROR(EINVAL);
353     }
354
355     pthread_mutex_lock(&c->mutex);
356
357     c->seek_request   = 1;
358     c->seek_pos       = new_logical_pos;
359     c->seek_whence    = SEEK_SET;
360     c->seek_completed = 0;
361     c->seek_ret       = 0;
362
363     while (1) {
364         if (async_check_interrupt(h)) {
365             ret = AVERROR_EXIT;
366             break;
367         }
368         if (c->seek_completed) {
369             if (c->seek_ret >= 0)
370                 c->logical_pos  = c->seek_ret;
371             ret = c->seek_ret;
372             break;
373         }
374         pthread_cond_signal(&c->cond_wakeup_background);
375         pthread_cond_wait(&c->cond_wakeup_main, &c->mutex);
376     }
377
378     pthread_mutex_unlock(&c->mutex);
379
380     return ret;
381 }
382
383 #define OFFSET(x) offsetof(Context, x)
384 #define D AV_OPT_FLAG_DECODING_PARAM
385
386 static const AVOption options[] = {
387     {NULL},
388 };
389
390 #undef D
391 #undef OFFSET
392
393 static const AVClass async_context_class = {
394     .class_name = "Async",
395     .item_name  = av_default_item_name,
396     .option     = options,
397     .version    = LIBAVUTIL_VERSION_INT,
398 };
399
400 URLProtocol ff_async_protocol = {
401     .name                = "async",
402     .url_open2           = async_open,
403     .url_read            = async_read,
404     .url_seek            = async_seek,
405     .url_close           = async_close,
406     .priv_data_size      = sizeof(Context),
407     .priv_data_class     = &async_context_class,
408 };
409
410 #ifdef TEST
411
412 #define TEST_SEEK_POS    (1536)
413 #define TEST_STREAM_SIZE (2048)
414
415 typedef struct TestContext {
416     AVClass        *class;
417     int64_t         logical_pos;
418     int64_t         logical_size;
419
420     /* options */
421     int             opt_read_error;
422 } TestContext;
423
424 static int async_test_open(URLContext *h, const char *arg, int flags, AVDictionary **options)
425 {
426     TestContext *c = h->priv_data;
427     c->logical_pos  = 0;
428     c->logical_size = TEST_STREAM_SIZE;
429     return 0;
430 }
431
432 static int async_test_close(URLContext *h)
433 {
434     return 0;
435 }
436
437 static int async_test_read(URLContext *h, unsigned char *buf, int size)
438 {
439     TestContext *c = h->priv_data;
440     int          i;
441     int          read_len = 0;
442
443     if (c->opt_read_error)
444         return c->opt_read_error;
445
446     if (c->logical_pos >= c->logical_size)
447         return AVERROR_EOF;
448
449     for (i = 0; i < size; ++i) {
450         buf[i] = c->logical_pos & 0xFF;
451
452         c->logical_pos++;
453         read_len++;
454
455         if (c->logical_pos >= c->logical_size)
456             break;
457     }
458
459     return read_len;
460 }
461
462 static int64_t async_test_seek(URLContext *h, int64_t pos, int whence)
463 {
464     TestContext *c = h->priv_data;
465     int64_t      new_logical_pos;
466
467     if (whence == AVSEEK_SIZE) {
468         return c->logical_size;
469     } else if (whence == SEEK_CUR) {
470         new_logical_pos = pos + c->logical_pos;
471     } else if (whence == SEEK_SET){
472         new_logical_pos = pos;
473     } else {
474         return AVERROR(EINVAL);
475     }
476     if (new_logical_pos < 0)
477         return AVERROR(EINVAL);
478
479     c->logical_pos = new_logical_pos;
480     return new_logical_pos;
481 }
482
483 #define OFFSET(x) offsetof(TestContext, x)
484 #define D AV_OPT_FLAG_DECODING_PARAM
485
486 static const AVOption async_test_options[] = {
487     { "async-test-read-error",      "cause read fail",
488         OFFSET(opt_read_error),     AV_OPT_TYPE_INT, { .i64 = 0 }, INT_MIN, INT_MAX, .flags = D },
489     {NULL},
490 };
491
492 #undef D
493 #undef OFFSET
494
495 static const AVClass async_test_context_class = {
496     .class_name = "Async-Test",
497     .item_name  = av_default_item_name,
498     .option     = async_test_options,
499     .version    = LIBAVUTIL_VERSION_INT,
500 };
501
502 URLProtocol ff_async_test_protocol = {
503     .name                = "async-test",
504     .url_open2           = async_test_open,
505     .url_read            = async_test_read,
506     .url_seek            = async_test_seek,
507     .url_close           = async_test_close,
508     .priv_data_size      = sizeof(TestContext),
509     .priv_data_class     = &async_test_context_class,
510 };
511
512 int main(void)
513 {
514     URLContext   *h = NULL;
515     int           i;
516     int           ret;
517     int64_t       size;
518     int64_t       pos;
519     int64_t       read_len;
520     unsigned char buf[4096];
521     AVDictionary *opts = NULL;
522
523     ffurl_register_protocol(&ff_async_protocol);
524     ffurl_register_protocol(&ff_async_test_protocol);
525
526     /*
527      * test normal read
528      */
529     ret = ffurl_open(&h, "async:async-test:", AVIO_FLAG_READ, NULL, NULL);
530     printf("open: %d\n", ret);
531
532     size = ffurl_size(h);
533     printf("size: %"PRId64"\n", size);
534
535     pos = ffurl_seek(h, 0, SEEK_CUR);
536     read_len = 0;
537     while (1) {
538         ret = ffurl_read(h, buf, sizeof(buf));
539         if (ret == AVERROR_EOF) {
540             printf("read-error: AVERROR_EOF at %"PRId64"\n", ffurl_seek(h, 0, SEEK_CUR));
541             break;
542         }
543         else if (ret == 0)
544             break;
545         else if (ret < 0) {
546             printf("read-error: %d at %"PRId64"\n", ret, ffurl_seek(h, 0, SEEK_CUR));
547             goto fail;
548         } else {
549             for (i = 0; i < ret; ++i) {
550                 if (buf[i] != (pos & 0xFF)) {
551                     printf("read-mismatch: actual %d, expecting %d, at %"PRId64"\n",
552                            (int)buf[i], (int)(pos & 0xFF), pos);
553                     break;
554                 }
555                 pos++;
556             }
557         }
558
559         read_len += ret;
560     }
561     printf("read: %"PRId64"\n", read_len);
562
563     /*
564      * test normal seek
565      */
566     ret = ffurl_read(h, buf, 1);
567     printf("read: %d\n", ret);
568
569     pos = ffurl_seek(h, TEST_SEEK_POS, SEEK_SET);
570     printf("seek: %"PRId64"\n", pos);
571
572     read_len = 0;
573     while (1) {
574         ret = ffurl_read(h, buf, sizeof(buf));
575         if (ret == AVERROR_EOF)
576             break;
577         else if (ret == 0)
578             break;
579         else if (ret < 0) {
580             printf("read-error: %d at %"PRId64"\n", ret, ffurl_seek(h, 0, SEEK_CUR));
581             goto fail;
582         } else {
583             for (i = 0; i < ret; ++i) {
584                 if (buf[i] != (pos & 0xFF)) {
585                     printf("read-mismatch: actual %d, expecting %d, at %"PRId64"\n",
586                            (int)buf[i], (int)(pos & 0xFF), pos);
587                     break;
588                 }
589                 pos++;
590             }
591         }
592
593         read_len += ret;
594     }
595     printf("read: %"PRId64"\n", read_len);
596
597     ret = ffurl_read(h, buf, 1);
598     printf("read: %d\n", ret);
599
600     /*
601      * test read error
602      */
603     ffurl_close(h);
604     av_dict_set_int(&opts, "async-test-read-error", -10000, 0);
605     ret = ffurl_open(&h, "async:async-test:", AVIO_FLAG_READ, NULL, &opts);
606     printf("open: %d\n", ret);
607
608     ret = ffurl_read(h, buf, 1);
609     printf("read: %d\n", ret);
610
611 fail:
612     av_dict_free(&opts);
613     ffurl_close(h);
614     return 0;
615 }
616
617 #endif