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.

830 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. double 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 && 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. double duration = 0.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);
  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);
  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_interval *= 1000000;
  386. reload:
  387. if (!v->finished &&
  388. av_gettime() - v->last_load_time >= reload_interval) {
  389. if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
  390. return ret;
  391. /* If we need to reload the playlist again below (if
  392. * there's still no more segments), switch to a reload
  393. * interval of half the target duration. */
  394. reload_interval = v->target_duration * 500000LL;
  395. }
  396. if (v->cur_seq_no < v->start_seq_no) {
  397. av_log(NULL, AV_LOG_WARNING,
  398. "skipping %d segments ahead, expired from playlists\n",
  399. v->start_seq_no - v->cur_seq_no);
  400. v->cur_seq_no = v->start_seq_no;
  401. }
  402. if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
  403. if (v->finished)
  404. return AVERROR_EOF;
  405. while (av_gettime() - v->last_load_time < reload_interval) {
  406. if (ff_check_interrupt(c->interrupt_callback))
  407. return AVERROR_EXIT;
  408. av_usleep(100*1000);
  409. }
  410. /* Enough time has elapsed since the last reload */
  411. goto reload;
  412. }
  413. ret = open_input(c, v);
  414. if (ret < 0)
  415. return ret;
  416. }
  417. ret = ffurl_read(v->input, buf, buf_size);
  418. if (ret > 0)
  419. return ret;
  420. ffurl_close(v->input);
  421. v->input = NULL;
  422. v->cur_seq_no++;
  423. c->end_of_segment = 1;
  424. c->cur_seq_no = v->cur_seq_no;
  425. if (v->ctx && v->ctx->nb_streams && 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 += round(c->variants[0]->segments[i]->duration * AV_TIME_BASE);
  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 = NULL;
  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. ret = avformat_open_input(&v->ctx, v->segments[0]->url, in_fmt, NULL);
  526. if (ret < 0)
  527. goto fail;
  528. v->stream_offset = stream_offset;
  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. /* Create new AVprogram for variant i */
  535. program = av_new_program(s, i);
  536. if (!program)
  537. goto fail;
  538. av_dict_set(&program->metadata, "variant_bitrate", bitrate_str, 0);
  539. /* Create new AVStreams for each stream in this variant */
  540. for (j = 0; j < v->ctx->nb_streams; j++) {
  541. AVStream *st = avformat_new_stream(s, NULL);
  542. AVStream *ist = v->ctx->streams[j];
  543. if (!st) {
  544. ret = AVERROR(ENOMEM);
  545. goto fail;
  546. }
  547. ff_program_add_stream_index(s, i, stream_offset + j);
  548. st->id = i;
  549. avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
  550. avcodec_copy_context(st->codec, v->ctx->streams[j]->codec);
  551. if (v->bandwidth)
  552. av_dict_set(&st->metadata, "variant_bitrate", bitrate_str,
  553. 0);
  554. }
  555. stream_offset += v->ctx->nb_streams;
  556. }
  557. c->first_packet = 1;
  558. c->first_timestamp = AV_NOPTS_VALUE;
  559. c->seek_timestamp = AV_NOPTS_VALUE;
  560. return 0;
  561. fail:
  562. free_variant_list(c);
  563. return ret;
  564. }
  565. static int recheck_discard_flags(AVFormatContext *s, int first)
  566. {
  567. HLSContext *c = s->priv_data;
  568. int i, changed = 0;
  569. /* Check if any new streams are needed */
  570. for (i = 0; i < c->n_variants; i++)
  571. c->variants[i]->cur_needed = 0;
  572. for (i = 0; i < s->nb_streams; i++) {
  573. AVStream *st = s->streams[i];
  574. struct variant *var = c->variants[s->streams[i]->id];
  575. if (st->discard < AVDISCARD_ALL)
  576. var->cur_needed = 1;
  577. }
  578. for (i = 0; i < c->n_variants; i++) {
  579. struct variant *v = c->variants[i];
  580. if (v->cur_needed && !v->needed) {
  581. v->needed = 1;
  582. changed = 1;
  583. v->cur_seq_no = c->cur_seq_no;
  584. v->pb.eof_reached = 0;
  585. av_log(s, AV_LOG_INFO, "Now receiving variant %d\n", i);
  586. } else if (first && !v->cur_needed && v->needed) {
  587. if (v->input)
  588. ffurl_close(v->input);
  589. v->input = NULL;
  590. v->needed = 0;
  591. changed = 1;
  592. av_log(s, AV_LOG_INFO, "No longer receiving variant %d\n", i);
  593. }
  594. }
  595. return changed;
  596. }
  597. static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
  598. {
  599. HLSContext *c = s->priv_data;
  600. int ret, i, minvariant = -1;
  601. if (c->first_packet) {
  602. recheck_discard_flags(s, 1);
  603. c->first_packet = 0;
  604. }
  605. start:
  606. c->end_of_segment = 0;
  607. for (i = 0; i < c->n_variants; i++) {
  608. struct variant *var = c->variants[i];
  609. /* Make sure we've got one buffered packet from each open variant
  610. * stream */
  611. if (var->needed && !var->pkt.data) {
  612. while (1) {
  613. int64_t ts_diff;
  614. AVStream *st;
  615. ret = av_read_frame(var->ctx, &var->pkt);
  616. if (ret < 0) {
  617. if (!url_feof(&var->pb) && ret != AVERROR_EOF)
  618. return ret;
  619. reset_packet(&var->pkt);
  620. break;
  621. } else {
  622. if (c->first_timestamp == AV_NOPTS_VALUE)
  623. c->first_timestamp = var->pkt.dts;
  624. }
  625. if (c->seek_timestamp == AV_NOPTS_VALUE)
  626. break;
  627. if (var->pkt.dts == AV_NOPTS_VALUE) {
  628. c->seek_timestamp = AV_NOPTS_VALUE;
  629. break;
  630. }
  631. st = var->ctx->streams[var->pkt.stream_index];
  632. ts_diff = av_rescale_rnd(var->pkt.dts, AV_TIME_BASE,
  633. st->time_base.den, AV_ROUND_DOWN) -
  634. c->seek_timestamp;
  635. if (ts_diff >= 0 && (c->seek_flags & AVSEEK_FLAG_ANY ||
  636. var->pkt.flags & AV_PKT_FLAG_KEY)) {
  637. c->seek_timestamp = AV_NOPTS_VALUE;
  638. break;
  639. }
  640. }
  641. }
  642. /* Check if this stream has the packet with the lowest dts */
  643. if (var->pkt.data) {
  644. if(minvariant < 0) {
  645. minvariant = i;
  646. } else {
  647. struct variant *minvar = c->variants[minvariant];
  648. int64_t dts = var->pkt.dts;
  649. int64_t mindts = minvar->pkt.dts;
  650. AVStream *st = var->ctx->streams[ var->pkt.stream_index];
  651. AVStream *minst= minvar->ctx->streams[minvar->pkt.stream_index];
  652. if( st->start_time != AV_NOPTS_VALUE) dts -= st->start_time;
  653. if(minst->start_time != AV_NOPTS_VALUE) mindts -= minst->start_time;
  654. if (av_compare_ts(dts, st->time_base, mindts, minst->time_base) < 0)
  655. minvariant = i;
  656. }
  657. }
  658. }
  659. if (c->end_of_segment) {
  660. if (recheck_discard_flags(s, 0))
  661. goto start;
  662. }
  663. /* If we got a packet, return it */
  664. if (minvariant >= 0) {
  665. *pkt = c->variants[minvariant]->pkt;
  666. pkt->stream_index += c->variants[minvariant]->stream_offset;
  667. reset_packet(&c->variants[minvariant]->pkt);
  668. return 0;
  669. }
  670. return AVERROR_EOF;
  671. }
  672. static int hls_close(AVFormatContext *s)
  673. {
  674. HLSContext *c = s->priv_data;
  675. free_variant_list(c);
  676. return 0;
  677. }
  678. static int hls_read_seek(AVFormatContext *s, int stream_index,
  679. int64_t timestamp, int flags)
  680. {
  681. HLSContext *c = s->priv_data;
  682. int i, j, ret;
  683. if ((flags & AVSEEK_FLAG_BYTE) || !c->variants[0]->finished)
  684. return AVERROR(ENOSYS);
  685. c->seek_flags = flags;
  686. c->seek_timestamp = stream_index < 0 ? timestamp :
  687. av_rescale_rnd(timestamp, AV_TIME_BASE,
  688. s->streams[stream_index]->time_base.den,
  689. flags & AVSEEK_FLAG_BACKWARD ?
  690. AV_ROUND_DOWN : AV_ROUND_UP);
  691. timestamp = av_rescale_rnd(timestamp, 1, stream_index >= 0 ?
  692. s->streams[stream_index]->time_base.den :
  693. AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
  694. AV_ROUND_DOWN : AV_ROUND_UP);
  695. if (s->duration < c->seek_timestamp) {
  696. c->seek_timestamp = AV_NOPTS_VALUE;
  697. return AVERROR(EIO);
  698. }
  699. ret = AVERROR(EIO);
  700. for (i = 0; i < c->n_variants; i++) {
  701. /* Reset reading */
  702. struct variant *var = c->variants[i];
  703. int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ? 0 :
  704. av_rescale_rnd(c->first_timestamp, 1, stream_index >= 0 ?
  705. s->streams[stream_index]->time_base.den :
  706. AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
  707. AV_ROUND_DOWN : AV_ROUND_UP);
  708. if (var->input) {
  709. ffurl_close(var->input);
  710. var->input = NULL;
  711. }
  712. av_free_packet(&var->pkt);
  713. reset_packet(&var->pkt);
  714. var->pb.eof_reached = 0;
  715. /* Clear any buffered data */
  716. var->pb.buf_end = var->pb.buf_ptr = var->pb.buffer;
  717. /* Reset the pos, to let the mpegts demuxer know we've seeked. */
  718. var->pb.pos = 0;
  719. /* Locate the segment that contains the target timestamp */
  720. for (j = 0; j < var->n_segments; j++) {
  721. if (timestamp >= pos &&
  722. timestamp < pos + var->segments[j]->duration) {
  723. var->cur_seq_no = var->start_seq_no + j;
  724. ret = 0;
  725. break;
  726. }
  727. pos += var->segments[j]->duration;
  728. }
  729. if (ret)
  730. c->seek_timestamp = AV_NOPTS_VALUE;
  731. }
  732. return ret;
  733. }
  734. static int hls_probe(AVProbeData *p)
  735. {
  736. /* Require #EXTM3U at the start, and either one of the ones below
  737. * somewhere for a proper match. */
  738. if (strncmp(p->buf, "#EXTM3U", 7))
  739. return 0;
  740. if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
  741. strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
  742. strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
  743. return AVPROBE_SCORE_MAX;
  744. return 0;
  745. }
  746. AVInputFormat ff_hls_demuxer = {
  747. .name = "hls,applehttp",
  748. .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
  749. .priv_data_size = sizeof(HLSContext),
  750. .read_probe = hls_probe,
  751. .read_header = hls_read_header,
  752. .read_packet = hls_read_packet,
  753. .read_close = hls_close,
  754. .read_seek = hls_read_seek,
  755. };