]> git.sesse.net Git - ffmpeg/blob - libavformat/async.c
Merge commit '7f388c0fabc51eca3106e7cc443393269435ab52'
[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 "url.h"
38 #include <stdint.h>
39 #include <pthread.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     size_t          seek_pos;
54     int             seek_whence;
55     int             seek_completed;
56     int64_t         seek_ret;
57
58     int             io_error;
59     int             io_eof_reached;
60
61     size_t          logical_pos;
62     size_t          logical_size;
63     AVFifoBuffer   *fifo;
64
65     pthread_cond_t  cond_wakeup_main;
66     pthread_cond_t  cond_wakeup_background;
67     pthread_mutex_t mutex;
68     pthread_t       async_buffer_thread;
69
70     int             abort_request;
71     AVIOInterruptCB interrupt_callback;
72 } Context;
73
74 static int async_check_interrupt(void *arg)
75 {
76     URLContext *h   = arg;
77     Context    *c   = h->priv_data;
78
79     if (c->abort_request)
80         return 1;
81
82     if (ff_check_interrupt(&c->interrupt_callback))
83         c->abort_request = 1;
84
85     return c->abort_request;
86 }
87
88 static void *async_buffer_task(void *arg)
89 {
90     URLContext   *h    = arg;
91     Context      *c    = h->priv_data;
92     AVFifoBuffer *fifo = c->fifo;
93     int           ret  = 0;
94
95     while (1) {
96         int fifo_space, to_copy;
97
98         if (async_check_interrupt(h)) {
99             c->io_eof_reached = 1;
100             c->io_error       = AVERROR_EXIT;
101             break;
102         }
103
104         if (c->seek_request) {
105             pthread_mutex_lock(&c->mutex);
106
107             ret = ffurl_seek(c->inner, c->seek_pos, c->seek_whence);
108             if (ret < 0) {
109                 c->io_eof_reached = 1;
110                 c->io_error       = ret;
111             } else {
112                 c->io_eof_reached = 0;
113                 c->io_error       = 0;
114             }
115
116             c->seek_completed = 1;
117             c->seek_ret       = ret;
118             c->seek_request   = 0;
119
120             av_fifo_reset(fifo);
121
122             pthread_cond_signal(&c->cond_wakeup_main);
123             pthread_mutex_unlock(&c->mutex);
124             continue;
125         }
126
127         fifo_space = av_fifo_space(fifo);
128         if (c->io_eof_reached || fifo_space <= 0) {
129             pthread_mutex_lock(&c->mutex);
130             pthread_cond_signal(&c->cond_wakeup_main);
131             pthread_cond_wait(&c->cond_wakeup_background, &c->mutex);
132             pthread_mutex_unlock(&c->mutex);
133             continue;
134         }
135
136         to_copy = FFMIN(4096, fifo_space);
137         ret = av_fifo_generic_write(fifo, c->inner, to_copy, (void *)ffurl_read);
138         if (ret <= 0) {
139             c->io_eof_reached = 1;
140             if (ret < 0) {
141                 c->io_error = ret;
142             }
143         }
144
145         pthread_mutex_lock(&c->mutex);
146         pthread_cond_signal(&c->cond_wakeup_main);
147         pthread_mutex_unlock(&c->mutex);
148     }
149
150     return NULL;
151 }
152
153 static int async_open(URLContext *h, const char *arg, int flags, AVDictionary **options)
154 {
155     Context         *c = h->priv_data;
156     int              ret;
157     AVIOInterruptCB  interrupt_callback = {.callback = async_check_interrupt, .opaque = h};
158
159     av_strstart(arg, "async:", &arg);
160
161     c->fifo = av_fifo_alloc(BUFFER_CAPACITY);
162     if (!c->fifo) {
163         ret = AVERROR(ENOMEM);
164         goto fifo_fail;
165     }
166
167     /* wrap interrupt callback */
168     c->interrupt_callback = h->interrupt_callback;
169     ret = ffurl_open(&c->inner, arg, flags, &interrupt_callback, options);
170     if (ret != 0) {
171         av_log(h, AV_LOG_ERROR, "ffurl_open failed : %s, %s\n", strerror(ret), arg);
172         goto url_fail;
173     }
174
175     c->logical_size = ffurl_size(c->inner);
176     h->is_streamed  = c->inner->is_streamed;
177
178     ret = pthread_mutex_init(&c->mutex, NULL);
179     if (ret != 0) {
180         av_log(h, AV_LOG_ERROR, "pthread_mutex_init failed : %s\n", strerror(ret));
181         goto mutex_fail;
182     }
183
184     ret = pthread_cond_init(&c->cond_wakeup_main, NULL);
185     if (ret != 0) {
186         av_log(h, AV_LOG_ERROR, "pthread_cond_init failed : %s\n", strerror(ret));
187         goto cond_wakeup_main_fail;
188     }
189
190     ret = pthread_cond_init(&c->cond_wakeup_background, NULL);
191     if (ret != 0) {
192         av_log(h, AV_LOG_ERROR, "pthread_cond_init failed : %s\n", strerror(ret));
193         goto cond_wakeup_background_fail;
194     }
195
196     ret = pthread_create(&c->async_buffer_thread, NULL, async_buffer_task, h);
197     if (ret) {
198         av_log(h, AV_LOG_ERROR, "pthread_create failed : %s\n", strerror(ret));
199         goto thread_fail;
200     }
201
202     return 0;
203
204 thread_fail:
205     pthread_cond_destroy(&c->cond_wakeup_background);
206 cond_wakeup_background_fail:
207     pthread_cond_destroy(&c->cond_wakeup_main);
208 cond_wakeup_main_fail:
209     pthread_mutex_destroy(&c->mutex);
210 mutex_fail:
211     ffurl_close(c->inner);
212 url_fail:
213     av_fifo_freep(&c->fifo);
214 fifo_fail:
215     return ret;
216 }
217
218 static int async_close(URLContext *h)
219 {
220     Context *c = h->priv_data;
221     int      ret;
222
223     pthread_mutex_lock(&c->mutex);
224     c->abort_request = 1;
225     pthread_cond_signal(&c->cond_wakeup_background);
226     pthread_mutex_unlock(&c->mutex);
227
228     ret = pthread_join(c->async_buffer_thread, NULL);
229     if (ret != 0)
230         av_log(h, AV_LOG_ERROR, "pthread_join(): %s\n", strerror(ret));
231
232     pthread_cond_destroy(&c->cond_wakeup_background);
233     pthread_cond_destroy(&c->cond_wakeup_main);
234     pthread_mutex_destroy(&c->mutex);
235     ffurl_close(c->inner);
236     av_fifo_freep(&c->fifo);
237
238     return 0;
239 }
240
241 static int async_read_internal(URLContext *h, void *dest, int size, int read_complete,
242                                void (*func)(void*, void*, int))
243 {
244     Context      *c       = h->priv_data;
245     AVFifoBuffer *fifo    = c->fifo;
246     int           to_read = size;
247     int           ret     = 0;
248
249     pthread_mutex_lock(&c->mutex);
250
251     while (to_read > 0) {
252         int fifo_size, to_copy;
253         if (async_check_interrupt(h)) {
254             ret = AVERROR_EXIT;
255             break;
256         }
257         fifo_size = av_fifo_size(fifo);
258         to_copy   = FFMIN(to_read, fifo_size);
259         if (to_copy > 0) {
260             av_fifo_generic_read(fifo, dest, to_copy, func);
261             if (!func)
262                 dest = (uint8_t *)dest + to_copy;
263             c->logical_pos += to_copy;
264             to_read        -= to_copy;
265             ret             = size - to_read;
266
267             if (to_read <= 0 || !read_complete)
268                 break;
269         } else if (c->io_eof_reached) {
270             if (ret <= 0)
271                 ret = AVERROR_EOF;
272             break;
273         }
274         pthread_cond_signal(&c->cond_wakeup_background);
275         pthread_cond_wait(&c->cond_wakeup_main, &c->mutex);
276     }
277
278     pthread_cond_signal(&c->cond_wakeup_background);
279     pthread_mutex_unlock(&c->mutex);
280
281     return ret;
282 }
283
284 static int async_read(URLContext *h, unsigned char *buf, int size)
285 {
286     return async_read_internal(h, buf, size, 0, NULL);
287 }
288
289 static void fifo_do_not_copy_func(void* dest, void* src, int size) {
290     // do not copy
291 }
292
293 static int64_t async_seek(URLContext *h, int64_t pos, int whence)
294 {
295     Context      *c    = h->priv_data;
296     AVFifoBuffer *fifo = c->fifo;
297     int64_t       ret;
298     int64_t       new_logical_pos;
299     int fifo_size;
300
301     if (whence == AVSEEK_SIZE) {
302         av_log(h, AV_LOG_TRACE, "async_seek: AVSEEK_SIZE: %"PRId64"\n", (int64_t)c->logical_size);
303         return c->logical_size;
304     } else if (whence == SEEK_CUR) {
305         av_log(h, AV_LOG_TRACE, "async_seek: %"PRId64"\n", pos);
306         new_logical_pos = pos + c->logical_pos;
307     } else if (whence == SEEK_SET){
308         av_log(h, AV_LOG_TRACE, "async_seek: %"PRId64"\n", pos);
309         new_logical_pos = pos;
310     } else {
311         return AVERROR(EINVAL);
312     }
313     if (new_logical_pos < 0)
314         return AVERROR(EINVAL);
315
316     fifo_size = av_fifo_size(fifo);
317     if (new_logical_pos == c->logical_pos) {
318         /* current position */
319         return c->logical_pos;
320     } else if ((new_logical_pos > c->logical_pos) &&
321                (new_logical_pos < (c->logical_pos + fifo_size + SHORT_SEEK_THRESHOLD))) {
322         /* fast seek */
323         av_log(h, AV_LOG_TRACE, "async_seek: fask_seek %"PRId64" from %d dist:%d/%d\n",
324                 new_logical_pos, (int)c->logical_pos,
325                 (int)(new_logical_pos - c->logical_pos), fifo_size);
326         async_read_internal(h, NULL, new_logical_pos - c->logical_pos, 1, fifo_do_not_copy_func);
327         return c->logical_pos;
328     } else if (c->logical_size <= 0) {
329         /* can not seek */
330         return AVERROR(EINVAL);
331     } else if (new_logical_pos > c->logical_size) {
332         /* beyond end */
333         return AVERROR(EINVAL);
334     }
335
336     pthread_mutex_lock(&c->mutex);
337
338     c->seek_request   = 1;
339     c->seek_pos       = new_logical_pos;
340     c->seek_whence    = SEEK_SET;
341     c->seek_completed = 0;
342     c->seek_ret       = 0;
343
344     while (1) {
345         if (async_check_interrupt(h)) {
346             ret = AVERROR_EXIT;
347             break;
348         }
349         if (c->seek_completed) {
350             if (c->seek_ret >= 0)
351                 c->logical_pos  = c->seek_ret;
352             ret = c->seek_ret;
353             break;
354         }
355         pthread_cond_signal(&c->cond_wakeup_background);
356         pthread_cond_wait(&c->cond_wakeup_main, &c->mutex);
357     }
358
359     pthread_mutex_unlock(&c->mutex);
360
361     return ret;
362 }
363
364 #define OFFSET(x) offsetof(Context, x)
365 #define D AV_OPT_FLAG_DECODING_PARAM
366
367 static const AVOption options[] = {
368     {NULL},
369 };
370
371 static const AVClass async_context_class = {
372     .class_name = "Async",
373     .item_name  = av_default_item_name,
374     .option     = options,
375     .version    = LIBAVUTIL_VERSION_INT,
376 };
377
378 URLProtocol ff_async_protocol = {
379     .name                = "async",
380     .url_open2           = async_open,
381     .url_read            = async_read,
382     .url_seek            = async_seek,
383     .url_close           = async_close,
384     .priv_data_size      = sizeof(Context),
385     .priv_data_class     = &async_context_class,
386 };
387
388 #ifdef TEST
389
390 #define TEST_SEEK_POS    (1536)
391 #define TEST_STREAM_SIZE (2048)
392
393 typedef struct TestContext {
394     AVClass        *class;
395     size_t          logical_pos;
396     size_t          logical_size;
397 } TestContext;
398
399 static int async_test_open(URLContext *h, const char *arg, int flags, AVDictionary **options)
400 {
401     TestContext *c = h->priv_data;
402     c->logical_pos  = 0;
403     c->logical_size = TEST_STREAM_SIZE;
404     return 0;
405 }
406
407 static int async_test_close(URLContext *h)
408 {
409     return 0;
410 }
411
412 static int async_test_read(URLContext *h, unsigned char *buf, int size)
413 {
414     TestContext *c = h->priv_data;
415     int          i;
416     int          read_len = 0;
417
418     if (c->logical_pos >= c->logical_size)
419         return AVERROR_EOF;
420
421     for (i = 0; i < size; ++i) {
422         buf[i] = c->logical_pos & 0xFF;
423
424         c->logical_pos++;
425         read_len++;
426
427         if (c->logical_pos >= c->logical_size)
428             break;
429     }
430
431     return read_len;
432 }
433
434 static int64_t async_test_seek(URLContext *h, int64_t pos, int whence)
435 {
436     TestContext *c = h->priv_data;
437     int64_t      new_logical_pos;
438
439     if (whence == AVSEEK_SIZE) {
440         return c->logical_size;
441     } else if (whence == SEEK_CUR) {
442         new_logical_pos = pos + c->logical_pos;
443     } else if (whence == SEEK_SET){
444         new_logical_pos = pos;
445     } else {
446         return AVERROR(EINVAL);
447     }
448     if (new_logical_pos < 0)
449         return AVERROR(EINVAL);
450
451     c->logical_pos = new_logical_pos;
452     return new_logical_pos;
453 }
454
455 static const AVClass async_test_context_class = {
456     .class_name = "Async-Test",
457     .item_name  = av_default_item_name,
458     .version    = LIBAVUTIL_VERSION_INT,
459 };
460
461 URLProtocol ff_async_test_protocol = {
462     .name                = "async-test",
463     .url_open2           = async_test_open,
464     .url_read            = async_test_read,
465     .url_seek            = async_test_seek,
466     .url_close           = async_test_close,
467     .priv_data_size      = sizeof(TestContext),
468     .priv_data_class     = &async_test_context_class,
469 };
470
471 int main(void)
472 {
473     URLContext   *h = NULL;
474     int           i;
475     int           ret;
476     int64_t       size;
477     int64_t       pos;
478     int64_t       read_len;
479     unsigned char buf[4096];
480
481     ffurl_register_protocol(&ff_async_protocol);
482     ffurl_register_protocol(&ff_async_test_protocol);
483
484     ret = ffurl_open(&h, "async:async-test:", AVIO_FLAG_READ, NULL, NULL);
485     printf("open: %d\n", ret);
486
487     size = ffurl_size(h);
488     printf("size: %"PRId64"\n", size);
489
490     pos = ffurl_seek(h, 0, SEEK_CUR);
491     read_len = 0;
492     while (1) {
493         ret = ffurl_read(h, buf, sizeof(buf));
494         if (ret == AVERROR_EOF) {
495             printf("read-error: AVERROR_EOF at %"PRId64"\n", ffurl_seek(h, 0, SEEK_CUR));
496             break;
497         }
498         else if (ret == 0)
499             break;
500         else if (ret < 0) {
501             printf("read-error: %d at %"PRId64"\n", ret, ffurl_seek(h, 0, SEEK_CUR));
502             goto fail;
503         } else {
504             for (i = 0; i < ret; ++i) {
505                 if (buf[i] != (pos & 0xFF)) {
506                     printf("read-mismatch: actual %d, expecting %d, at %"PRId64"\n",
507                            (int)buf[i], (int)(pos & 0xFF), pos);
508                     break;
509                 }
510                 pos++;
511             }
512         }
513
514         read_len += ret;
515     }
516     printf("read: %"PRId64"\n", read_len);
517
518     ret = ffurl_read(h, buf, 1);
519     printf("read: %d\n", ret);
520
521     pos = ffurl_seek(h, TEST_SEEK_POS, SEEK_SET);
522     printf("seek: %"PRId64"\n", pos);
523
524     read_len = 0;
525     while (1) {
526         ret = ffurl_read(h, buf, sizeof(buf));
527         if (ret == AVERROR_EOF)
528             break;
529         else if (ret == 0)
530             break;
531         else if (ret < 0) {
532             printf("read-error: %d at %"PRId64"\n", ret, ffurl_seek(h, 0, SEEK_CUR));
533             goto fail;
534         } else {
535             for (i = 0; i < ret; ++i) {
536                 if (buf[i] != (pos & 0xFF)) {
537                     printf("read-mismatch: actual %d, expecting %d, at %"PRId64"\n",
538                            (int)buf[i], (int)(pos & 0xFF), pos);
539                     break;
540                 }
541                 pos++;
542             }
543         }
544
545         read_len += ret;
546     }
547     printf("read: %"PRId64"\n", read_len);
548
549     ret = ffurl_read(h, buf, 1);
550     printf("read: %d\n", ret);
551
552 fail:
553     ffurl_close(h);
554     return 0;
555 }
556
557 #endif