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.

855 lines
28KB

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