You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

700 lines
19KB

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