hls.c 25 KB

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