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.

827 lines
27KB

  1. /*
  2. * Apple HTTP Live Streaming demuxer
  3. * Copyright (c) 2010 Martin Storsjo
  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. /**
  22. * @file
  23. * Apple HTTP Live Streaming demuxer
  24. * http://tools.ietf.org/html/draft-pantos-http-live-streaming
  25. */
  26. #include "libavutil/avstring.h"
  27. #include "libavutil/intreadwrite.h"
  28. #include "libavutil/mathematics.h"
  29. #include "libavutil/opt.h"
  30. #include "libavutil/dict.h"
  31. #include "libavutil/time.h"
  32. #include "avformat.h"
  33. #include "internal.h"
  34. #include "avio_internal.h"
  35. #include "url.h"
  36. #define INITIAL_BUFFER_SIZE 32768
  37. /*
  38. * An apple http stream consists of a playlist with media segment files,
  39. * played sequentially. There may be several playlists with the same
  40. * video content, in different bandwidth variants, that are played in
  41. * parallel (preferably only one bandwidth variant at a time). In this case,
  42. * the user supplied the url to a main playlist that only lists the variant
  43. * playlists.
  44. *
  45. * If the main playlist doesn't point at any variants, we still create
  46. * one anonymous toplevel variant for this, to maintain the structure.
  47. */
  48. enum KeyType {
  49. KEY_NONE,
  50. KEY_AES_128,
  51. };
  52. struct segment {
  53. int duration;
  54. char url[MAX_URL_SIZE];
  55. char key[MAX_URL_SIZE];
  56. enum KeyType key_type;
  57. uint8_t iv[16];
  58. };
  59. /*
  60. * Each variant has its own demuxer. If it currently is active,
  61. * it has an open AVIOContext too, and potentially an AVPacket
  62. * containing the next packet from this stream.
  63. */
  64. struct variant {
  65. int bandwidth;
  66. char url[MAX_URL_SIZE];
  67. AVIOContext pb;
  68. uint8_t* read_buffer;
  69. URLContext *input;
  70. AVFormatContext *parent;
  71. int index;
  72. AVFormatContext *ctx;
  73. AVPacket pkt;
  74. int stream_offset;
  75. int finished;
  76. int target_duration;
  77. int start_seq_no;
  78. int n_segments;
  79. struct segment **segments;
  80. int needed, cur_needed;
  81. int cur_seq_no;
  82. int64_t last_load_time;
  83. char key_url[MAX_URL_SIZE];
  84. uint8_t key[16];
  85. };
  86. typedef struct HLSContext {
  87. int n_variants;
  88. struct variant **variants;
  89. int cur_seq_no;
  90. int end_of_segment;
  91. int first_packet;
  92. int64_t first_timestamp;
  93. int64_t seek_timestamp;
  94. int seek_flags;
  95. AVIOInterruptCB *interrupt_callback;
  96. char *user_agent; ///< holds HTTP user agent set as an AVOption to the HTTP protocol context
  97. char *cookies; ///< holds HTTP cookie values set in either the initial response or as an AVOption to the HTTP protocol context
  98. } HLSContext;
  99. static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
  100. {
  101. int len = ff_get_line(s, buf, maxlen);
  102. while (len > 0 && isspace(buf[len - 1]))
  103. buf[--len] = '\0';
  104. return len;
  105. }
  106. static void free_segment_list(struct variant *var)
  107. {
  108. int i;
  109. for (i = 0; i < var->n_segments; i++)
  110. av_free(var->segments[i]);
  111. av_freep(&var->segments);
  112. var->n_segments = 0;
  113. }
  114. static void free_variant_list(HLSContext *c)
  115. {
  116. int i;
  117. for (i = 0; i < c->n_variants; i++) {
  118. struct variant *var = c->variants[i];
  119. free_segment_list(var);
  120. av_free_packet(&var->pkt);
  121. av_free(var->pb.buffer);
  122. if (var->input)
  123. ffurl_close(var->input);
  124. if (var->ctx) {
  125. var->ctx->pb = NULL;
  126. avformat_close_input(&var->ctx);
  127. }
  128. av_free(var);
  129. }
  130. av_freep(&c->variants);
  131. av_freep(&c->cookies);
  132. av_freep(&c->user_agent);
  133. c->n_variants = 0;
  134. }
  135. /*
  136. * Used to reset a statically allocated AVPacket to a clean slate,
  137. * containing no data.
  138. */
  139. static void reset_packet(AVPacket *pkt)
  140. {
  141. av_init_packet(pkt);
  142. pkt->data = NULL;
  143. }
  144. static struct variant *new_variant(HLSContext *c, int bandwidth,
  145. const char *url, const char *base)
  146. {
  147. struct variant *var = av_mallocz(sizeof(struct variant));
  148. if (!var)
  149. return NULL;
  150. reset_packet(&var->pkt);
  151. var->bandwidth = bandwidth;
  152. ff_make_absolute_url(var->url, sizeof(var->url), base, url);
  153. dynarray_add(&c->variants, &c->n_variants, var);
  154. return var;
  155. }
  156. struct variant_info {
  157. char bandwidth[20];
  158. };
  159. static void handle_variant_args(struct variant_info *info, const char *key,
  160. int key_len, char **dest, int *dest_len)
  161. {
  162. if (!strncmp(key, "BANDWIDTH=", key_len)) {
  163. *dest = info->bandwidth;
  164. *dest_len = sizeof(info->bandwidth);
  165. }
  166. }
  167. struct key_info {
  168. char uri[MAX_URL_SIZE];
  169. char method[10];
  170. char iv[35];
  171. };
  172. static void handle_key_args(struct key_info *info, const char *key,
  173. int key_len, char **dest, int *dest_len)
  174. {
  175. if (!strncmp(key, "METHOD=", key_len)) {
  176. *dest = info->method;
  177. *dest_len = sizeof(info->method);
  178. } else if (!strncmp(key, "URI=", key_len)) {
  179. *dest = info->uri;
  180. *dest_len = sizeof(info->uri);
  181. } else if (!strncmp(key, "IV=", key_len)) {
  182. *dest = info->iv;
  183. *dest_len = sizeof(info->iv);
  184. }
  185. }
  186. static int parse_playlist(HLSContext *c, const char *url,
  187. struct variant *var, AVIOContext *in)
  188. {
  189. int ret = 0, duration = 0, is_segment = 0, is_variant = 0, bandwidth = 0;
  190. enum KeyType key_type = KEY_NONE;
  191. uint8_t iv[16] = "";
  192. int has_iv = 0;
  193. char key[MAX_URL_SIZE] = "";
  194. char line[1024];
  195. const char *ptr;
  196. int close_in = 0;
  197. if (!in) {
  198. AVDictionary *opts = NULL;
  199. close_in = 1;
  200. /* Some HLS servers dont like being sent the range header */
  201. av_dict_set(&opts, "seekable", "0", 0);
  202. // broker prior HTTP options that should be consistent across requests
  203. av_dict_set(&opts, "user-agent", c->user_agent, 0);
  204. av_dict_set(&opts, "cookies", c->cookies, 0);
  205. ret = avio_open2(&in, url, AVIO_FLAG_READ,
  206. c->interrupt_callback, &opts);
  207. av_dict_free(&opts);
  208. if (ret < 0)
  209. return ret;
  210. }
  211. read_chomp_line(in, line, sizeof(line));
  212. if (strcmp(line, "#EXTM3U")) {
  213. ret = AVERROR_INVALIDDATA;
  214. goto fail;
  215. }
  216. if (var) {
  217. free_segment_list(var);
  218. var->finished = 0;
  219. }
  220. while (!url_feof(in)) {
  221. read_chomp_line(in, line, sizeof(line));
  222. if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
  223. struct variant_info info = {{0}};
  224. is_variant = 1;
  225. ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
  226. &info);
  227. bandwidth = atoi(info.bandwidth);
  228. } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
  229. struct key_info info = {{0}};
  230. ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,
  231. &info);
  232. key_type = KEY_NONE;
  233. has_iv = 0;
  234. if (!strcmp(info.method, "AES-128"))
  235. key_type = KEY_AES_128;
  236. if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
  237. ff_hex_to_data(iv, info.iv + 2);
  238. has_iv = 1;
  239. }
  240. av_strlcpy(key, info.uri, sizeof(key));
  241. } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
  242. if (!var) {
  243. var = new_variant(c, 0, url, NULL);
  244. if (!var) {
  245. ret = AVERROR(ENOMEM);
  246. goto fail;
  247. }
  248. }
  249. var->target_duration = atoi(ptr);
  250. } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
  251. if (!var) {
  252. var = new_variant(c, 0, url, NULL);
  253. if (!var) {
  254. ret = AVERROR(ENOMEM);
  255. goto fail;
  256. }
  257. }
  258. var->start_seq_no = atoi(ptr);
  259. } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
  260. if (var)
  261. var->finished = 1;
  262. } else if (av_strstart(line, "#EXTINF:", &ptr)) {
  263. is_segment = 1;
  264. duration = atoi(ptr);
  265. } else if (av_strstart(line, "#", NULL)) {
  266. continue;
  267. } else if (line[0]) {
  268. if (is_variant) {
  269. if (!new_variant(c, bandwidth, line, url)) {
  270. ret = AVERROR(ENOMEM);
  271. goto fail;
  272. }
  273. is_variant = 0;
  274. bandwidth = 0;
  275. }
  276. if (is_segment) {
  277. struct segment *seg;
  278. if (!var) {
  279. var = new_variant(c, 0, url, NULL);
  280. if (!var) {
  281. ret = AVERROR(ENOMEM);
  282. goto fail;
  283. }
  284. }
  285. seg = av_malloc(sizeof(struct segment));
  286. if (!seg) {
  287. ret = AVERROR(ENOMEM);
  288. goto fail;
  289. }
  290. seg->duration = duration;
  291. seg->key_type = key_type;
  292. if (has_iv) {
  293. memcpy(seg->iv, iv, sizeof(iv));
  294. } else {
  295. int seq = var->start_seq_no + var->n_segments;
  296. memset(seg->iv, 0, sizeof(seg->iv));
  297. AV_WB32(seg->iv + 12, seq);
  298. }
  299. ff_make_absolute_url(seg->key, sizeof(seg->key), url, key);
  300. ff_make_absolute_url(seg->url, sizeof(seg->url), url, line);
  301. dynarray_add(&var->segments, &var->n_segments, seg);
  302. is_segment = 0;
  303. }
  304. }
  305. }
  306. if (var)
  307. var->last_load_time = av_gettime();
  308. fail:
  309. if (close_in)
  310. avio_close(in);
  311. return ret;
  312. }
  313. static int open_input(HLSContext *c, struct variant *var)
  314. {
  315. AVDictionary *opts = NULL;
  316. int ret;
  317. struct segment *seg = var->segments[var->cur_seq_no - var->start_seq_no];
  318. // broker prior HTTP options that should be consistent across requests
  319. av_dict_set(&opts, "user-agent", c->user_agent, 0);
  320. av_dict_set(&opts, "cookies", c->cookies, 0);
  321. av_dict_set(&opts, "seekable", "0", 0);
  322. if (seg->key_type == KEY_NONE) {
  323. ret = ffurl_open(&var->input, seg->url, AVIO_FLAG_READ,
  324. &var->parent->interrupt_callback, &opts);
  325. goto cleanup;
  326. } else if (seg->key_type == KEY_AES_128) {
  327. char iv[33], key[33], url[MAX_URL_SIZE];
  328. if (strcmp(seg->key, var->key_url)) {
  329. URLContext *uc;
  330. if (ffurl_open(&uc, seg->key, AVIO_FLAG_READ,
  331. &var->parent->interrupt_callback, &opts) == 0) {
  332. if (ffurl_read_complete(uc, var->key, sizeof(var->key))
  333. != sizeof(var->key)) {
  334. av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
  335. seg->key);
  336. }
  337. ffurl_close(uc);
  338. } else {
  339. av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
  340. seg->key);
  341. }
  342. av_strlcpy(var->key_url, seg->key, sizeof(var->key_url));
  343. }
  344. ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
  345. ff_data_to_hex(key, var->key, sizeof(var->key), 0);
  346. iv[32] = key[32] = '\0';
  347. if (strstr(seg->url, "://"))
  348. snprintf(url, sizeof(url), "crypto+%s", seg->url);
  349. else
  350. snprintf(url, sizeof(url), "crypto:%s", seg->url);
  351. if ((ret = ffurl_alloc(&var->input, url, AVIO_FLAG_READ,
  352. &var->parent->interrupt_callback)) < 0)
  353. goto cleanup;
  354. av_opt_set(var->input->priv_data, "key", key, 0);
  355. av_opt_set(var->input->priv_data, "iv", iv, 0);
  356. /* Need to repopulate options */
  357. av_dict_free(&opts);
  358. av_dict_set(&opts, "seekable", "0", 0);
  359. if ((ret = ffurl_connect(var->input, &opts)) < 0) {
  360. ffurl_close(var->input);
  361. var->input = NULL;
  362. goto cleanup;
  363. }
  364. ret = 0;
  365. }
  366. else
  367. ret = AVERROR(ENOSYS);
  368. cleanup:
  369. av_dict_free(&opts);
  370. return ret;
  371. }
  372. static int read_data(void *opaque, uint8_t *buf, int buf_size)
  373. {
  374. struct variant *v = opaque;
  375. HLSContext *c = v->parent->priv_data;
  376. int ret, i;
  377. restart:
  378. if (!v->input) {
  379. /* If this is a live stream and the reload interval has elapsed since
  380. * the last playlist reload, reload the variant playlists now. */
  381. int64_t reload_interval = v->n_segments > 0 ?
  382. v->segments[v->n_segments - 1]->duration :
  383. v->target_duration;
  384. reload_interval *= 1000000;
  385. reload:
  386. if (!v->finished &&
  387. av_gettime() - v->last_load_time >= reload_interval) {
  388. if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
  389. return ret;
  390. /* If we need to reload the playlist again below (if
  391. * there's still no more segments), switch to a reload
  392. * interval of half the target duration. */
  393. reload_interval = v->target_duration * 500000LL;
  394. }
  395. if (v->cur_seq_no < v->start_seq_no) {
  396. av_log(NULL, AV_LOG_WARNING,
  397. "skipping %d segments ahead, expired from playlists\n",
  398. v->start_seq_no - v->cur_seq_no);
  399. v->cur_seq_no = v->start_seq_no;
  400. }
  401. if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
  402. if (v->finished)
  403. return AVERROR_EOF;
  404. while (av_gettime() - v->last_load_time < reload_interval) {
  405. if (ff_check_interrupt(c->interrupt_callback))
  406. return AVERROR_EXIT;
  407. av_usleep(100*1000);
  408. }
  409. /* Enough time has elapsed since the last reload */
  410. goto reload;
  411. }
  412. ret = open_input(c, v);
  413. if (ret < 0)
  414. return ret;
  415. }
  416. ret = ffurl_read(v->input, buf, buf_size);
  417. if (ret > 0)
  418. return ret;
  419. ffurl_close(v->input);
  420. v->input = NULL;
  421. v->cur_seq_no++;
  422. c->end_of_segment = 1;
  423. c->cur_seq_no = v->cur_seq_no;
  424. if (v->ctx && v->ctx->nb_streams && v->parent->nb_streams >= v->stream_offset + v->ctx->nb_streams) {
  425. v->needed = 0;
  426. for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;
  427. i++) {
  428. if (v->parent->streams[i]->discard < AVDISCARD_ALL)
  429. v->needed = 1;
  430. }
  431. }
  432. if (!v->needed) {
  433. av_log(v->parent, AV_LOG_INFO, "No longer receiving variant %d\n",
  434. v->index);
  435. return AVERROR_EOF;
  436. }
  437. goto restart;
  438. }
  439. static int hls_read_header(AVFormatContext *s)
  440. {
  441. URLContext *u = s->pb->opaque;
  442. HLSContext *c = s->priv_data;
  443. int ret = 0, i, j, stream_offset = 0;
  444. c->interrupt_callback = &s->interrupt_callback;
  445. // if the URL context is good, read important options we must broker later
  446. if (u && u->prot->priv_data_class) {
  447. // get the previous user agent & set back to null if string size is zero
  448. av_freep(&c->user_agent);
  449. av_opt_get(u->priv_data, "user-agent", 0, (uint8_t**)&(c->user_agent));
  450. if (c->user_agent && !strlen(c->user_agent))
  451. av_freep(&c->user_agent);
  452. // get the previous cookies & set back to null if string size is zero
  453. av_freep(&c->cookies);
  454. av_opt_get(u->priv_data, "cookies", 0, (uint8_t**)&(c->cookies));
  455. if (c->cookies && !strlen(c->cookies))
  456. av_freep(&c->cookies);
  457. }
  458. if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
  459. goto fail;
  460. if (c->n_variants == 0) {
  461. av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
  462. ret = AVERROR_EOF;
  463. goto fail;
  464. }
  465. /* If the playlist only contained variants, parse each individual
  466. * variant playlist. */
  467. if (c->n_variants > 1 || c->variants[0]->n_segments == 0) {
  468. for (i = 0; i < c->n_variants; i++) {
  469. struct variant *v = c->variants[i];
  470. if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
  471. goto fail;
  472. }
  473. }
  474. if (c->variants[0]->n_segments == 0) {
  475. av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
  476. ret = AVERROR_EOF;
  477. goto fail;
  478. }
  479. /* If this isn't a live stream, calculate the total duration of the
  480. * stream. */
  481. if (c->variants[0]->finished) {
  482. int64_t duration = 0;
  483. for (i = 0; i < c->variants[0]->n_segments; i++)
  484. duration += c->variants[0]->segments[i]->duration;
  485. s->duration = duration * AV_TIME_BASE;
  486. }
  487. /* Open the demuxer for each variant */
  488. for (i = 0; i < c->n_variants; i++) {
  489. struct variant *v = c->variants[i];
  490. AVInputFormat *in_fmt = NULL;
  491. char bitrate_str[20];
  492. AVProgram *program = NULL;
  493. if (v->n_segments == 0)
  494. continue;
  495. if (!(v->ctx = avformat_alloc_context())) {
  496. ret = AVERROR(ENOMEM);
  497. goto fail;
  498. }
  499. v->index = i;
  500. v->needed = 1;
  501. v->parent = s;
  502. /* If this is a live stream with more than 3 segments, start at the
  503. * third last segment. */
  504. v->cur_seq_no = v->start_seq_no;
  505. if (!v->finished && v->n_segments > 3)
  506. v->cur_seq_no = v->start_seq_no + v->n_segments - 3;
  507. v->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
  508. ffio_init_context(&v->pb, v->read_buffer, INITIAL_BUFFER_SIZE, 0, v,
  509. read_data, NULL, NULL);
  510. v->pb.seekable = 0;
  511. ret = av_probe_input_buffer(&v->pb, &in_fmt, v->segments[0]->url,
  512. NULL, 0, 0);
  513. if (ret < 0) {
  514. /* Free the ctx - it isn't initialized properly at this point,
  515. * so avformat_close_input shouldn't be called. If
  516. * avformat_open_input fails below, it frees and zeros the
  517. * context, so it doesn't need any special treatment like this. */
  518. av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", v->segments[0]->url);
  519. avformat_free_context(v->ctx);
  520. v->ctx = NULL;
  521. goto fail;
  522. }
  523. v->ctx->pb = &v->pb;
  524. ret = avformat_open_input(&v->ctx, v->segments[0]->url, in_fmt, NULL);
  525. if (ret < 0)
  526. goto fail;
  527. v->stream_offset = stream_offset;
  528. v->ctx->ctx_flags &= ~AVFMTCTX_NOHEADER;
  529. ret = avformat_find_stream_info(v->ctx, NULL);
  530. if (ret < 0)
  531. goto fail;
  532. snprintf(bitrate_str, sizeof(bitrate_str), "%d", v->bandwidth);
  533. /* Create new AVprogram for variant i */
  534. program = av_new_program(s, i);
  535. if (!program)
  536. goto fail;
  537. av_dict_set(&program->metadata, "variant_bitrate", bitrate_str, 0);
  538. /* Create new AVStreams for each stream in this variant */
  539. for (j = 0; j < v->ctx->nb_streams; j++) {
  540. AVStream *st = avformat_new_stream(s, NULL);
  541. if (!st) {
  542. ret = AVERROR(ENOMEM);
  543. goto fail;
  544. }
  545. ff_program_add_stream_index(s, i, stream_offset + j);
  546. st->id = i;
  547. avcodec_copy_context(st->codec, v->ctx->streams[j]->codec);
  548. if (v->bandwidth)
  549. av_dict_set(&st->metadata, "variant_bitrate", bitrate_str,
  550. 0);
  551. }
  552. stream_offset += v->ctx->nb_streams;
  553. }
  554. c->first_packet = 1;
  555. c->first_timestamp = AV_NOPTS_VALUE;
  556. c->seek_timestamp = AV_NOPTS_VALUE;
  557. return 0;
  558. fail:
  559. free_variant_list(c);
  560. return ret;
  561. }
  562. static int recheck_discard_flags(AVFormatContext *s, int first)
  563. {
  564. HLSContext *c = s->priv_data;
  565. int i, changed = 0;
  566. /* Check if any new streams are needed */
  567. for (i = 0; i < c->n_variants; i++)
  568. c->variants[i]->cur_needed = 0;
  569. for (i = 0; i < s->nb_streams; i++) {
  570. AVStream *st = s->streams[i];
  571. struct variant *var = c->variants[s->streams[i]->id];
  572. if (st->discard < AVDISCARD_ALL)
  573. var->cur_needed = 1;
  574. }
  575. for (i = 0; i < c->n_variants; i++) {
  576. struct variant *v = c->variants[i];
  577. if (v->cur_needed && !v->needed) {
  578. v->needed = 1;
  579. changed = 1;
  580. v->cur_seq_no = c->cur_seq_no;
  581. v->pb.eof_reached = 0;
  582. av_log(s, AV_LOG_INFO, "Now receiving variant %d\n", i);
  583. } else if (first && !v->cur_needed && v->needed) {
  584. if (v->input)
  585. ffurl_close(v->input);
  586. v->input = NULL;
  587. v->needed = 0;
  588. changed = 1;
  589. av_log(s, AV_LOG_INFO, "No longer receiving variant %d\n", i);
  590. }
  591. }
  592. return changed;
  593. }
  594. static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
  595. {
  596. HLSContext *c = s->priv_data;
  597. int ret, i, minvariant = -1;
  598. if (c->first_packet) {
  599. recheck_discard_flags(s, 1);
  600. c->first_packet = 0;
  601. }
  602. start:
  603. c->end_of_segment = 0;
  604. for (i = 0; i < c->n_variants; i++) {
  605. struct variant *var = c->variants[i];
  606. /* Make sure we've got one buffered packet from each open variant
  607. * stream */
  608. if (var->needed && !var->pkt.data) {
  609. while (1) {
  610. int64_t ts_diff;
  611. AVStream *st;
  612. ret = av_read_frame(var->ctx, &var->pkt);
  613. if (ret < 0) {
  614. if (!url_feof(&var->pb) && ret != AVERROR_EOF)
  615. return ret;
  616. reset_packet(&var->pkt);
  617. break;
  618. } else {
  619. if (c->first_timestamp == AV_NOPTS_VALUE)
  620. c->first_timestamp = var->pkt.dts;
  621. }
  622. if (c->seek_timestamp == AV_NOPTS_VALUE)
  623. break;
  624. if (var->pkt.dts == AV_NOPTS_VALUE) {
  625. c->seek_timestamp = AV_NOPTS_VALUE;
  626. break;
  627. }
  628. st = var->ctx->streams[var->pkt.stream_index];
  629. ts_diff = av_rescale_rnd(var->pkt.dts, AV_TIME_BASE,
  630. st->time_base.den, AV_ROUND_DOWN) -
  631. c->seek_timestamp;
  632. if (ts_diff >= 0 && (c->seek_flags & AVSEEK_FLAG_ANY ||
  633. var->pkt.flags & AV_PKT_FLAG_KEY)) {
  634. c->seek_timestamp = AV_NOPTS_VALUE;
  635. break;
  636. }
  637. }
  638. }
  639. /* Check if this stream has the packet with the lowest dts */
  640. if (var->pkt.data) {
  641. if(minvariant < 0) {
  642. minvariant = i;
  643. } else {
  644. struct variant *minvar = c->variants[minvariant];
  645. int64_t dts = var->pkt.dts;
  646. int64_t mindts = minvar->pkt.dts;
  647. AVStream *st = var->ctx->streams[ var->pkt.stream_index];
  648. AVStream *minst= minvar->ctx->streams[minvar->pkt.stream_index];
  649. if( st->start_time != AV_NOPTS_VALUE) dts -= st->start_time;
  650. if(minst->start_time != AV_NOPTS_VALUE) mindts -= minst->start_time;
  651. if (av_compare_ts(dts, st->time_base, mindts, minst->time_base) < 0)
  652. minvariant = i;
  653. }
  654. }
  655. }
  656. if (c->end_of_segment) {
  657. if (recheck_discard_flags(s, 0))
  658. goto start;
  659. }
  660. /* If we got a packet, return it */
  661. if (minvariant >= 0) {
  662. *pkt = c->variants[minvariant]->pkt;
  663. pkt->stream_index += c->variants[minvariant]->stream_offset;
  664. reset_packet(&c->variants[minvariant]->pkt);
  665. return 0;
  666. }
  667. return AVERROR_EOF;
  668. }
  669. static int hls_close(AVFormatContext *s)
  670. {
  671. HLSContext *c = s->priv_data;
  672. free_variant_list(c);
  673. return 0;
  674. }
  675. static int hls_read_seek(AVFormatContext *s, int stream_index,
  676. int64_t timestamp, int flags)
  677. {
  678. HLSContext *c = s->priv_data;
  679. int i, j, ret;
  680. if ((flags & AVSEEK_FLAG_BYTE) || !c->variants[0]->finished)
  681. return AVERROR(ENOSYS);
  682. c->seek_flags = flags;
  683. c->seek_timestamp = stream_index < 0 ? timestamp :
  684. av_rescale_rnd(timestamp, AV_TIME_BASE,
  685. s->streams[stream_index]->time_base.den,
  686. flags & AVSEEK_FLAG_BACKWARD ?
  687. AV_ROUND_DOWN : AV_ROUND_UP);
  688. timestamp = av_rescale_rnd(timestamp, 1, stream_index >= 0 ?
  689. s->streams[stream_index]->time_base.den :
  690. AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
  691. AV_ROUND_DOWN : AV_ROUND_UP);
  692. if (s->duration < c->seek_timestamp) {
  693. c->seek_timestamp = AV_NOPTS_VALUE;
  694. return AVERROR(EIO);
  695. }
  696. ret = AVERROR(EIO);
  697. for (i = 0; i < c->n_variants; i++) {
  698. /* Reset reading */
  699. struct variant *var = c->variants[i];
  700. int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ? 0 :
  701. av_rescale_rnd(c->first_timestamp, 1, stream_index >= 0 ?
  702. s->streams[stream_index]->time_base.den :
  703. AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
  704. AV_ROUND_DOWN : AV_ROUND_UP);
  705. if (var->input) {
  706. ffurl_close(var->input);
  707. var->input = NULL;
  708. }
  709. av_free_packet(&var->pkt);
  710. reset_packet(&var->pkt);
  711. var->pb.eof_reached = 0;
  712. /* Clear any buffered data */
  713. var->pb.buf_end = var->pb.buf_ptr = var->pb.buffer;
  714. /* Reset the pos, to let the mpegts demuxer know we've seeked. */
  715. var->pb.pos = 0;
  716. /* Locate the segment that contains the target timestamp */
  717. for (j = 0; j < var->n_segments; j++) {
  718. if (timestamp >= pos &&
  719. timestamp < pos + var->segments[j]->duration) {
  720. var->cur_seq_no = var->start_seq_no + j;
  721. ret = 0;
  722. break;
  723. }
  724. pos += var->segments[j]->duration;
  725. }
  726. if (ret)
  727. c->seek_timestamp = AV_NOPTS_VALUE;
  728. }
  729. return ret;
  730. }
  731. static int hls_probe(AVProbeData *p)
  732. {
  733. /* Require #EXTM3U at the start, and either one of the ones below
  734. * somewhere for a proper match. */
  735. if (strncmp(p->buf, "#EXTM3U", 7))
  736. return 0;
  737. if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
  738. strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
  739. strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
  740. return AVPROBE_SCORE_MAX;
  741. return 0;
  742. }
  743. AVInputFormat ff_hls_demuxer = {
  744. .name = "hls,applehttp",
  745. .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
  746. .priv_data_size = sizeof(HLSContext),
  747. .read_probe = hls_probe,
  748. .read_header = hls_read_header,
  749. .read_packet = hls_read_packet,
  750. .read_close = hls_close,
  751. .read_seek = hls_read_seek,
  752. };