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.

937 lines
31KB

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