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.

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