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.

2019 lines
67KB

  1. /*
  2. * Apple HTTP Live Streaming demuxer
  3. * Copyright (c) 2010 Martin Storsjo
  4. * Copyright (c) 2013 Anssi Hannula
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. /**
  23. * @file
  24. * Apple HTTP Live Streaming demuxer
  25. * http://tools.ietf.org/html/draft-pantos-http-live-streaming
  26. */
  27. #include "libavutil/avstring.h"
  28. #include "libavutil/avassert.h"
  29. #include "libavutil/intreadwrite.h"
  30. #include "libavutil/mathematics.h"
  31. #include "libavutil/opt.h"
  32. #include "libavutil/dict.h"
  33. #include "libavutil/time.h"
  34. #include "avformat.h"
  35. #include "internal.h"
  36. #include "avio_internal.h"
  37. #include "id3v2.h"
  38. #define INITIAL_BUFFER_SIZE 32768
  39. #define MAX_FIELD_LEN 64
  40. #define MAX_CHARACTERISTICS_LEN 512
  41. #define MPEG_TIME_BASE 90000
  42. #define MPEG_TIME_BASE_Q (AVRational){1, MPEG_TIME_BASE}
  43. /*
  44. * An apple http stream consists of a playlist with media segment files,
  45. * played sequentially. There may be several playlists with the same
  46. * video content, in different bandwidth variants, that are played in
  47. * parallel (preferably only one bandwidth variant at a time). In this case,
  48. * the user supplied the url to a main playlist that only lists the variant
  49. * playlists.
  50. *
  51. * If the main playlist doesn't point at any variants, we still create
  52. * one anonymous toplevel variant for this, to maintain the structure.
  53. */
  54. enum KeyType {
  55. KEY_NONE,
  56. KEY_AES_128,
  57. KEY_SAMPLE_AES
  58. };
  59. struct segment {
  60. int64_t duration;
  61. int64_t url_offset;
  62. int64_t size;
  63. char *url;
  64. char *key;
  65. enum KeyType key_type;
  66. uint8_t iv[16];
  67. /* associated Media Initialization Section, treated as a segment */
  68. struct segment *init_section;
  69. };
  70. struct rendition;
  71. enum PlaylistType {
  72. PLS_TYPE_UNSPECIFIED,
  73. PLS_TYPE_EVENT,
  74. PLS_TYPE_VOD
  75. };
  76. /*
  77. * Each playlist has its own demuxer. If it currently is active,
  78. * it has an open AVIOContext too, and potentially an AVPacket
  79. * containing the next packet from this stream.
  80. */
  81. struct playlist {
  82. char url[MAX_URL_SIZE];
  83. AVIOContext pb;
  84. uint8_t* read_buffer;
  85. AVIOContext *input;
  86. AVFormatContext *parent;
  87. int index;
  88. AVFormatContext *ctx;
  89. AVPacket pkt;
  90. int stream_offset;
  91. int finished;
  92. enum PlaylistType type;
  93. int64_t target_duration;
  94. int start_seq_no;
  95. int n_segments;
  96. struct segment **segments;
  97. int needed, cur_needed;
  98. int cur_seq_no;
  99. int64_t cur_seg_offset;
  100. int64_t last_load_time;
  101. /* Currently active Media Initialization Section */
  102. struct segment *cur_init_section;
  103. uint8_t *init_sec_buf;
  104. unsigned int init_sec_buf_size;
  105. unsigned int init_sec_data_len;
  106. unsigned int init_sec_buf_read_offset;
  107. char key_url[MAX_URL_SIZE];
  108. uint8_t key[16];
  109. /* ID3 timestamp handling (elementary audio streams have ID3 timestamps
  110. * (and possibly other ID3 tags) in the beginning of each segment) */
  111. int is_id3_timestamped; /* -1: not yet known */
  112. int64_t id3_mpegts_timestamp; /* in mpegts tb */
  113. int64_t id3_offset; /* in stream original tb */
  114. uint8_t* id3_buf; /* temp buffer for id3 parsing */
  115. unsigned int id3_buf_size;
  116. AVDictionary *id3_initial; /* data from first id3 tag */
  117. int id3_found; /* ID3 tag found at some point */
  118. int id3_changed; /* ID3 tag data has changed at some point */
  119. ID3v2ExtraMeta *id3_deferred_extra; /* stored here until subdemuxer is opened */
  120. int64_t seek_timestamp;
  121. int seek_flags;
  122. int seek_stream_index; /* into subdemuxer stream array */
  123. /* Renditions associated with this playlist, if any.
  124. * Alternative rendition playlists have a single rendition associated
  125. * with them, and variant main Media Playlists may have
  126. * multiple (playlist-less) renditions associated with them. */
  127. int n_renditions;
  128. struct rendition **renditions;
  129. /* Media Initialization Sections (EXT-X-MAP) associated with this
  130. * playlist, if any. */
  131. int n_init_sections;
  132. struct segment **init_sections;
  133. };
  134. /*
  135. * Renditions are e.g. alternative subtitle or audio streams.
  136. * The rendition may either be an external playlist or it may be
  137. * contained in the main Media Playlist of the variant (in which case
  138. * playlist is NULL).
  139. */
  140. struct rendition {
  141. enum AVMediaType type;
  142. struct playlist *playlist;
  143. char group_id[MAX_FIELD_LEN];
  144. char language[MAX_FIELD_LEN];
  145. char name[MAX_FIELD_LEN];
  146. int disposition;
  147. };
  148. struct variant {
  149. int bandwidth;
  150. /* every variant contains at least the main Media Playlist in index 0 */
  151. int n_playlists;
  152. struct playlist **playlists;
  153. char audio_group[MAX_FIELD_LEN];
  154. char video_group[MAX_FIELD_LEN];
  155. char subtitles_group[MAX_FIELD_LEN];
  156. };
  157. typedef struct HLSContext {
  158. AVClass *class;
  159. AVFormatContext *ctx;
  160. int n_variants;
  161. struct variant **variants;
  162. int n_playlists;
  163. struct playlist **playlists;
  164. int n_renditions;
  165. struct rendition **renditions;
  166. int cur_seq_no;
  167. int live_start_index;
  168. int first_packet;
  169. int64_t first_timestamp;
  170. int64_t cur_timestamp;
  171. AVIOInterruptCB *interrupt_callback;
  172. char *user_agent; ///< holds HTTP user agent set as an AVOption to the HTTP protocol context
  173. char *cookies; ///< holds HTTP cookie values set in either the initial response or as an AVOption to the HTTP protocol context
  174. char *headers; ///< holds HTTP headers set as an AVOption to the HTTP protocol context
  175. char *http_proxy; ///< holds the address of the HTTP proxy server
  176. AVDictionary *avio_opts;
  177. int strict_std_compliance;
  178. } HLSContext;
  179. static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
  180. {
  181. int len = ff_get_line(s, buf, maxlen);
  182. while (len > 0 && av_isspace(buf[len - 1]))
  183. buf[--len] = '\0';
  184. return len;
  185. }
  186. static void free_segment_list(struct playlist *pls)
  187. {
  188. int i;
  189. for (i = 0; i < pls->n_segments; i++) {
  190. av_freep(&pls->segments[i]->key);
  191. av_freep(&pls->segments[i]->url);
  192. av_freep(&pls->segments[i]);
  193. }
  194. av_freep(&pls->segments);
  195. pls->n_segments = 0;
  196. }
  197. static void free_init_section_list(struct playlist *pls)
  198. {
  199. int i;
  200. for (i = 0; i < pls->n_init_sections; i++) {
  201. av_freep(&pls->init_sections[i]->url);
  202. av_freep(&pls->init_sections[i]);
  203. }
  204. av_freep(&pls->init_sections);
  205. pls->n_init_sections = 0;
  206. }
  207. static void free_playlist_list(HLSContext *c)
  208. {
  209. int i;
  210. for (i = 0; i < c->n_playlists; i++) {
  211. struct playlist *pls = c->playlists[i];
  212. free_segment_list(pls);
  213. free_init_section_list(pls);
  214. av_freep(&pls->renditions);
  215. av_freep(&pls->id3_buf);
  216. av_dict_free(&pls->id3_initial);
  217. ff_id3v2_free_extra_meta(&pls->id3_deferred_extra);
  218. av_freep(&pls->init_sec_buf);
  219. av_packet_unref(&pls->pkt);
  220. av_freep(&pls->pb.buffer);
  221. if (pls->input)
  222. ff_format_io_close(c->ctx, &pls->input);
  223. if (pls->ctx) {
  224. pls->ctx->pb = NULL;
  225. avformat_close_input(&pls->ctx);
  226. }
  227. av_free(pls);
  228. }
  229. av_freep(&c->playlists);
  230. av_freep(&c->cookies);
  231. av_freep(&c->user_agent);
  232. av_freep(&c->headers);
  233. av_freep(&c->http_proxy);
  234. c->n_playlists = 0;
  235. }
  236. static void free_variant_list(HLSContext *c)
  237. {
  238. int i;
  239. for (i = 0; i < c->n_variants; i++) {
  240. struct variant *var = c->variants[i];
  241. av_freep(&var->playlists);
  242. av_free(var);
  243. }
  244. av_freep(&c->variants);
  245. c->n_variants = 0;
  246. }
  247. static void free_rendition_list(HLSContext *c)
  248. {
  249. int i;
  250. for (i = 0; i < c->n_renditions; i++)
  251. av_freep(&c->renditions[i]);
  252. av_freep(&c->renditions);
  253. c->n_renditions = 0;
  254. }
  255. /*
  256. * Used to reset a statically allocated AVPacket to a clean slate,
  257. * containing no data.
  258. */
  259. static void reset_packet(AVPacket *pkt)
  260. {
  261. av_init_packet(pkt);
  262. pkt->data = NULL;
  263. }
  264. static struct playlist *new_playlist(HLSContext *c, const char *url,
  265. const char *base)
  266. {
  267. struct playlist *pls = av_mallocz(sizeof(struct playlist));
  268. if (!pls)
  269. return NULL;
  270. reset_packet(&pls->pkt);
  271. ff_make_absolute_url(pls->url, sizeof(pls->url), base, url);
  272. pls->seek_timestamp = AV_NOPTS_VALUE;
  273. pls->is_id3_timestamped = -1;
  274. pls->id3_mpegts_timestamp = AV_NOPTS_VALUE;
  275. dynarray_add(&c->playlists, &c->n_playlists, pls);
  276. return pls;
  277. }
  278. struct variant_info {
  279. char bandwidth[20];
  280. /* variant group ids: */
  281. char audio[MAX_FIELD_LEN];
  282. char video[MAX_FIELD_LEN];
  283. char subtitles[MAX_FIELD_LEN];
  284. };
  285. static struct variant *new_variant(HLSContext *c, struct variant_info *info,
  286. const char *url, const char *base)
  287. {
  288. struct variant *var;
  289. struct playlist *pls;
  290. pls = new_playlist(c, url, base);
  291. if (!pls)
  292. return NULL;
  293. var = av_mallocz(sizeof(struct variant));
  294. if (!var)
  295. return NULL;
  296. if (info) {
  297. var->bandwidth = atoi(info->bandwidth);
  298. strcpy(var->audio_group, info->audio);
  299. strcpy(var->video_group, info->video);
  300. strcpy(var->subtitles_group, info->subtitles);
  301. }
  302. dynarray_add(&c->variants, &c->n_variants, var);
  303. dynarray_add(&var->playlists, &var->n_playlists, pls);
  304. return var;
  305. }
  306. static void handle_variant_args(struct variant_info *info, const char *key,
  307. int key_len, char **dest, int *dest_len)
  308. {
  309. if (!strncmp(key, "BANDWIDTH=", key_len)) {
  310. *dest = info->bandwidth;
  311. *dest_len = sizeof(info->bandwidth);
  312. } else if (!strncmp(key, "AUDIO=", key_len)) {
  313. *dest = info->audio;
  314. *dest_len = sizeof(info->audio);
  315. } else if (!strncmp(key, "VIDEO=", key_len)) {
  316. *dest = info->video;
  317. *dest_len = sizeof(info->video);
  318. } else if (!strncmp(key, "SUBTITLES=", key_len)) {
  319. *dest = info->subtitles;
  320. *dest_len = sizeof(info->subtitles);
  321. }
  322. }
  323. struct key_info {
  324. char uri[MAX_URL_SIZE];
  325. char method[11];
  326. char iv[35];
  327. };
  328. static void handle_key_args(struct key_info *info, const char *key,
  329. int key_len, char **dest, int *dest_len)
  330. {
  331. if (!strncmp(key, "METHOD=", key_len)) {
  332. *dest = info->method;
  333. *dest_len = sizeof(info->method);
  334. } else if (!strncmp(key, "URI=", key_len)) {
  335. *dest = info->uri;
  336. *dest_len = sizeof(info->uri);
  337. } else if (!strncmp(key, "IV=", key_len)) {
  338. *dest = info->iv;
  339. *dest_len = sizeof(info->iv);
  340. }
  341. }
  342. struct init_section_info {
  343. char uri[MAX_URL_SIZE];
  344. char byterange[32];
  345. };
  346. static struct segment *new_init_section(struct playlist *pls,
  347. struct init_section_info *info,
  348. const char *url_base)
  349. {
  350. struct segment *sec;
  351. char *ptr;
  352. char tmp_str[MAX_URL_SIZE];
  353. if (!info->uri[0])
  354. return NULL;
  355. sec = av_mallocz(sizeof(*sec));
  356. if (!sec)
  357. return NULL;
  358. ff_make_absolute_url(tmp_str, sizeof(tmp_str), url_base, info->uri);
  359. sec->url = av_strdup(tmp_str);
  360. if (!sec->url) {
  361. av_free(sec);
  362. return NULL;
  363. }
  364. if (info->byterange[0]) {
  365. sec->size = atoi(info->byterange);
  366. ptr = strchr(info->byterange, '@');
  367. if (ptr)
  368. sec->url_offset = atoi(ptr+1);
  369. } else {
  370. /* the entire file is the init section */
  371. sec->size = -1;
  372. }
  373. dynarray_add(&pls->init_sections, &pls->n_init_sections, sec);
  374. return sec;
  375. }
  376. static void handle_init_section_args(struct init_section_info *info, const char *key,
  377. int key_len, char **dest, int *dest_len)
  378. {
  379. if (!strncmp(key, "URI=", key_len)) {
  380. *dest = info->uri;
  381. *dest_len = sizeof(info->uri);
  382. } else if (!strncmp(key, "BYTERANGE=", key_len)) {
  383. *dest = info->byterange;
  384. *dest_len = sizeof(info->byterange);
  385. }
  386. }
  387. struct rendition_info {
  388. char type[16];
  389. char uri[MAX_URL_SIZE];
  390. char group_id[MAX_FIELD_LEN];
  391. char language[MAX_FIELD_LEN];
  392. char assoc_language[MAX_FIELD_LEN];
  393. char name[MAX_FIELD_LEN];
  394. char defaultr[4];
  395. char forced[4];
  396. char characteristics[MAX_CHARACTERISTICS_LEN];
  397. };
  398. static struct rendition *new_rendition(HLSContext *c, struct rendition_info *info,
  399. const char *url_base)
  400. {
  401. struct rendition *rend;
  402. enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
  403. char *characteristic;
  404. char *chr_ptr;
  405. char *saveptr;
  406. if (!strcmp(info->type, "AUDIO"))
  407. type = AVMEDIA_TYPE_AUDIO;
  408. else if (!strcmp(info->type, "VIDEO"))
  409. type = AVMEDIA_TYPE_VIDEO;
  410. else if (!strcmp(info->type, "SUBTITLES"))
  411. type = AVMEDIA_TYPE_SUBTITLE;
  412. else if (!strcmp(info->type, "CLOSED-CAPTIONS"))
  413. /* CLOSED-CAPTIONS is ignored since we do not support CEA-608 CC in
  414. * AVC SEI RBSP anyway */
  415. return NULL;
  416. if (type == AVMEDIA_TYPE_UNKNOWN)
  417. return NULL;
  418. /* URI is mandatory for subtitles as per spec */
  419. if (type == AVMEDIA_TYPE_SUBTITLE && !info->uri[0])
  420. return NULL;
  421. /* TODO: handle subtitles (each segment has to parsed separately) */
  422. if (c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL)
  423. if (type == AVMEDIA_TYPE_SUBTITLE)
  424. return NULL;
  425. rend = av_mallocz(sizeof(struct rendition));
  426. if (!rend)
  427. return NULL;
  428. dynarray_add(&c->renditions, &c->n_renditions, rend);
  429. rend->type = type;
  430. strcpy(rend->group_id, info->group_id);
  431. strcpy(rend->language, info->language);
  432. strcpy(rend->name, info->name);
  433. /* add the playlist if this is an external rendition */
  434. if (info->uri[0]) {
  435. rend->playlist = new_playlist(c, info->uri, url_base);
  436. if (rend->playlist)
  437. dynarray_add(&rend->playlist->renditions,
  438. &rend->playlist->n_renditions, rend);
  439. }
  440. if (info->assoc_language[0]) {
  441. int langlen = strlen(rend->language);
  442. if (langlen < sizeof(rend->language) - 3) {
  443. rend->language[langlen] = ',';
  444. strncpy(rend->language + langlen + 1, info->assoc_language,
  445. sizeof(rend->language) - langlen - 2);
  446. }
  447. }
  448. if (!strcmp(info->defaultr, "YES"))
  449. rend->disposition |= AV_DISPOSITION_DEFAULT;
  450. if (!strcmp(info->forced, "YES"))
  451. rend->disposition |= AV_DISPOSITION_FORCED;
  452. chr_ptr = info->characteristics;
  453. while ((characteristic = av_strtok(chr_ptr, ",", &saveptr))) {
  454. if (!strcmp(characteristic, "public.accessibility.describes-music-and-sound"))
  455. rend->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  456. else if (!strcmp(characteristic, "public.accessibility.describes-video"))
  457. rend->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
  458. chr_ptr = NULL;
  459. }
  460. return rend;
  461. }
  462. static void handle_rendition_args(struct rendition_info *info, const char *key,
  463. int key_len, char **dest, int *dest_len)
  464. {
  465. if (!strncmp(key, "TYPE=", key_len)) {
  466. *dest = info->type;
  467. *dest_len = sizeof(info->type);
  468. } else if (!strncmp(key, "URI=", key_len)) {
  469. *dest = info->uri;
  470. *dest_len = sizeof(info->uri);
  471. } else if (!strncmp(key, "GROUP-ID=", key_len)) {
  472. *dest = info->group_id;
  473. *dest_len = sizeof(info->group_id);
  474. } else if (!strncmp(key, "LANGUAGE=", key_len)) {
  475. *dest = info->language;
  476. *dest_len = sizeof(info->language);
  477. } else if (!strncmp(key, "ASSOC-LANGUAGE=", key_len)) {
  478. *dest = info->assoc_language;
  479. *dest_len = sizeof(info->assoc_language);
  480. } else if (!strncmp(key, "NAME=", key_len)) {
  481. *dest = info->name;
  482. *dest_len = sizeof(info->name);
  483. } else if (!strncmp(key, "DEFAULT=", key_len)) {
  484. *dest = info->defaultr;
  485. *dest_len = sizeof(info->defaultr);
  486. } else if (!strncmp(key, "FORCED=", key_len)) {
  487. *dest = info->forced;
  488. *dest_len = sizeof(info->forced);
  489. } else if (!strncmp(key, "CHARACTERISTICS=", key_len)) {
  490. *dest = info->characteristics;
  491. *dest_len = sizeof(info->characteristics);
  492. }
  493. /*
  494. * ignored:
  495. * - AUTOSELECT: client may autoselect based on e.g. system language
  496. * - INSTREAM-ID: EIA-608 closed caption number ("CC1".."CC4")
  497. */
  498. }
  499. /* used by parse_playlist to allocate a new variant+playlist when the
  500. * playlist is detected to be a Media Playlist (not Master Playlist)
  501. * and we have no parent Master Playlist (parsing of which would have
  502. * allocated the variant and playlist already)
  503. * *pls == NULL => Master Playlist or parentless Media Playlist
  504. * *pls != NULL => parented Media Playlist, playlist+variant allocated */
  505. static int ensure_playlist(HLSContext *c, struct playlist **pls, const char *url)
  506. {
  507. if (*pls)
  508. return 0;
  509. if (!new_variant(c, NULL, url, NULL))
  510. return AVERROR(ENOMEM);
  511. *pls = c->playlists[c->n_playlists - 1];
  512. return 0;
  513. }
  514. static void update_options(char **dest, const char *name, void *src)
  515. {
  516. av_freep(dest);
  517. av_opt_get(src, name, AV_OPT_SEARCH_CHILDREN, (uint8_t**)dest);
  518. if (*dest && !strlen(*dest))
  519. av_freep(dest);
  520. }
  521. static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,
  522. AVDictionary *opts, AVDictionary *opts2)
  523. {
  524. HLSContext *c = s->priv_data;
  525. AVDictionary *tmp = NULL;
  526. const char *proto_name = NULL;
  527. int ret;
  528. av_dict_copy(&tmp, opts, 0);
  529. av_dict_copy(&tmp, opts2, 0);
  530. if (av_strstart(url, "crypto", NULL)) {
  531. if (url[6] == '+' || url[6] == ':')
  532. proto_name = avio_find_protocol_name(url + 7);
  533. }
  534. if (!proto_name)
  535. proto_name = avio_find_protocol_name(url);
  536. if (!proto_name)
  537. return AVERROR_INVALIDDATA;
  538. // only http(s) & file are allowed
  539. if (!av_strstart(proto_name, "http", NULL) && !av_strstart(proto_name, "file", NULL))
  540. return AVERROR_INVALIDDATA;
  541. if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')
  542. ;
  543. else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')
  544. ;
  545. else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
  546. return AVERROR_INVALIDDATA;
  547. ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);
  548. if (ret >= 0) {
  549. // update cookies on http response with setcookies.
  550. void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb;
  551. update_options(&c->cookies, "cookies", u);
  552. av_dict_set(&opts, "cookies", c->cookies, 0);
  553. }
  554. av_dict_free(&tmp);
  555. return ret;
  556. }
  557. static int parse_playlist(HLSContext *c, const char *url,
  558. struct playlist *pls, AVIOContext *in)
  559. {
  560. int ret = 0, is_segment = 0, is_variant = 0;
  561. int64_t duration = 0;
  562. enum KeyType key_type = KEY_NONE;
  563. uint8_t iv[16] = "";
  564. int has_iv = 0;
  565. char key[MAX_URL_SIZE] = "";
  566. char line[MAX_URL_SIZE];
  567. const char *ptr;
  568. int close_in = 0;
  569. int64_t seg_offset = 0;
  570. int64_t seg_size = -1;
  571. uint8_t *new_url = NULL;
  572. struct variant_info variant_info;
  573. char tmp_str[MAX_URL_SIZE];
  574. struct segment *cur_init_section = NULL;
  575. if (!in) {
  576. #if 1
  577. AVDictionary *opts = NULL;
  578. close_in = 1;
  579. /* Some HLS servers don't like being sent the range header */
  580. av_dict_set(&opts, "seekable", "0", 0);
  581. // broker prior HTTP options that should be consistent across requests
  582. av_dict_set(&opts, "user-agent", c->user_agent, 0);
  583. av_dict_set(&opts, "cookies", c->cookies, 0);
  584. av_dict_set(&opts, "headers", c->headers, 0);
  585. av_dict_set(&opts, "http_proxy", c->http_proxy, 0);
  586. ret = c->ctx->io_open(c->ctx, &in, url, AVIO_FLAG_READ, &opts);
  587. av_dict_free(&opts);
  588. if (ret < 0)
  589. return ret;
  590. #else
  591. ret = open_in(c, &in, url);
  592. if (ret < 0)
  593. return ret;
  594. close_in = 1;
  595. #endif
  596. }
  597. if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)
  598. url = new_url;
  599. read_chomp_line(in, line, sizeof(line));
  600. if (strcmp(line, "#EXTM3U")) {
  601. ret = AVERROR_INVALIDDATA;
  602. goto fail;
  603. }
  604. if (pls) {
  605. free_segment_list(pls);
  606. pls->finished = 0;
  607. pls->type = PLS_TYPE_UNSPECIFIED;
  608. }
  609. while (!avio_feof(in)) {
  610. read_chomp_line(in, line, sizeof(line));
  611. if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
  612. is_variant = 1;
  613. memset(&variant_info, 0, sizeof(variant_info));
  614. ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
  615. &variant_info);
  616. } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
  617. struct key_info info = {{0}};
  618. ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,
  619. &info);
  620. key_type = KEY_NONE;
  621. has_iv = 0;
  622. if (!strcmp(info.method, "AES-128"))
  623. key_type = KEY_AES_128;
  624. if (!strcmp(info.method, "SAMPLE-AES"))
  625. key_type = KEY_SAMPLE_AES;
  626. if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
  627. ff_hex_to_data(iv, info.iv + 2);
  628. has_iv = 1;
  629. }
  630. av_strlcpy(key, info.uri, sizeof(key));
  631. } else if (av_strstart(line, "#EXT-X-MEDIA:", &ptr)) {
  632. struct rendition_info info = {{0}};
  633. ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_rendition_args,
  634. &info);
  635. new_rendition(c, &info, url);
  636. } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
  637. ret = ensure_playlist(c, &pls, url);
  638. if (ret < 0)
  639. goto fail;
  640. pls->target_duration = atoi(ptr) * AV_TIME_BASE;
  641. } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
  642. ret = ensure_playlist(c, &pls, url);
  643. if (ret < 0)
  644. goto fail;
  645. pls->start_seq_no = atoi(ptr);
  646. } else if (av_strstart(line, "#EXT-X-PLAYLIST-TYPE:", &ptr)) {
  647. ret = ensure_playlist(c, &pls, url);
  648. if (ret < 0)
  649. goto fail;
  650. if (!strcmp(ptr, "EVENT"))
  651. pls->type = PLS_TYPE_EVENT;
  652. else if (!strcmp(ptr, "VOD"))
  653. pls->type = PLS_TYPE_VOD;
  654. } else if (av_strstart(line, "#EXT-X-MAP:", &ptr)) {
  655. struct init_section_info info = {{0}};
  656. ret = ensure_playlist(c, &pls, url);
  657. if (ret < 0)
  658. goto fail;
  659. ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_init_section_args,
  660. &info);
  661. cur_init_section = new_init_section(pls, &info, url);
  662. } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
  663. if (pls)
  664. pls->finished = 1;
  665. } else if (av_strstart(line, "#EXTINF:", &ptr)) {
  666. is_segment = 1;
  667. duration = atof(ptr) * AV_TIME_BASE;
  668. } else if (av_strstart(line, "#EXT-X-BYTERANGE:", &ptr)) {
  669. seg_size = atoi(ptr);
  670. ptr = strchr(ptr, '@');
  671. if (ptr)
  672. seg_offset = atoi(ptr+1);
  673. } else if (av_strstart(line, "#", NULL)) {
  674. continue;
  675. } else if (line[0]) {
  676. if (is_variant) {
  677. if (!new_variant(c, &variant_info, line, url)) {
  678. ret = AVERROR(ENOMEM);
  679. goto fail;
  680. }
  681. is_variant = 0;
  682. }
  683. if (is_segment) {
  684. struct segment *seg;
  685. if (!pls) {
  686. if (!new_variant(c, 0, url, NULL)) {
  687. ret = AVERROR(ENOMEM);
  688. goto fail;
  689. }
  690. pls = c->playlists[c->n_playlists - 1];
  691. }
  692. seg = av_malloc(sizeof(struct segment));
  693. if (!seg) {
  694. ret = AVERROR(ENOMEM);
  695. goto fail;
  696. }
  697. seg->duration = duration;
  698. seg->key_type = key_type;
  699. if (has_iv) {
  700. memcpy(seg->iv, iv, sizeof(iv));
  701. } else {
  702. int seq = pls->start_seq_no + pls->n_segments;
  703. memset(seg->iv, 0, sizeof(seg->iv));
  704. AV_WB32(seg->iv + 12, seq);
  705. }
  706. if (key_type != KEY_NONE) {
  707. ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key);
  708. seg->key = av_strdup(tmp_str);
  709. if (!seg->key) {
  710. av_free(seg);
  711. ret = AVERROR(ENOMEM);
  712. goto fail;
  713. }
  714. } else {
  715. seg->key = NULL;
  716. }
  717. ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line);
  718. seg->url = av_strdup(tmp_str);
  719. if (!seg->url) {
  720. av_free(seg->key);
  721. av_free(seg);
  722. ret = AVERROR(ENOMEM);
  723. goto fail;
  724. }
  725. dynarray_add(&pls->segments, &pls->n_segments, seg);
  726. is_segment = 0;
  727. seg->size = seg_size;
  728. if (seg_size >= 0) {
  729. seg->url_offset = seg_offset;
  730. seg_offset += seg_size;
  731. seg_size = -1;
  732. } else {
  733. seg->url_offset = 0;
  734. seg_offset = 0;
  735. }
  736. seg->init_section = cur_init_section;
  737. }
  738. }
  739. }
  740. if (pls)
  741. pls->last_load_time = av_gettime_relative();
  742. fail:
  743. av_free(new_url);
  744. if (close_in)
  745. ff_format_io_close(c->ctx, &in);
  746. return ret;
  747. }
  748. static struct segment *current_segment(struct playlist *pls)
  749. {
  750. return pls->segments[pls->cur_seq_no - pls->start_seq_no];
  751. }
  752. enum ReadFromURLMode {
  753. READ_NORMAL,
  754. READ_COMPLETE,
  755. };
  756. static int read_from_url(struct playlist *pls, struct segment *seg,
  757. uint8_t *buf, int buf_size,
  758. enum ReadFromURLMode mode)
  759. {
  760. int ret;
  761. /* limit read if the segment was only a part of a file */
  762. if (seg->size >= 0)
  763. buf_size = FFMIN(buf_size, seg->size - pls->cur_seg_offset);
  764. if (mode == READ_COMPLETE) {
  765. ret = avio_read(pls->input, buf, buf_size);
  766. if (ret != buf_size)
  767. av_log(NULL, AV_LOG_ERROR, "Could not read complete segment.\n");
  768. } else
  769. ret = avio_read(pls->input, buf, buf_size);
  770. if (ret > 0)
  771. pls->cur_seg_offset += ret;
  772. return ret;
  773. }
  774. /* Parse the raw ID3 data and pass contents to caller */
  775. static void parse_id3(AVFormatContext *s, AVIOContext *pb,
  776. AVDictionary **metadata, int64_t *dts,
  777. ID3v2ExtraMetaAPIC **apic, ID3v2ExtraMeta **extra_meta)
  778. {
  779. static const char id3_priv_owner_ts[] = "com.apple.streaming.transportStreamTimestamp";
  780. ID3v2ExtraMeta *meta;
  781. ff_id3v2_read_dict(pb, metadata, ID3v2_DEFAULT_MAGIC, extra_meta);
  782. for (meta = *extra_meta; meta; meta = meta->next) {
  783. if (!strcmp(meta->tag, "PRIV")) {
  784. ID3v2ExtraMetaPRIV *priv = meta->data;
  785. if (priv->datasize == 8 && !strcmp(priv->owner, id3_priv_owner_ts)) {
  786. /* 33-bit MPEG timestamp */
  787. int64_t ts = AV_RB64(priv->data);
  788. av_log(s, AV_LOG_DEBUG, "HLS ID3 audio timestamp %"PRId64"\n", ts);
  789. if ((ts & ~((1ULL << 33) - 1)) == 0)
  790. *dts = ts;
  791. else
  792. av_log(s, AV_LOG_ERROR, "Invalid HLS ID3 audio timestamp %"PRId64"\n", ts);
  793. }
  794. } else if (!strcmp(meta->tag, "APIC") && apic)
  795. *apic = meta->data;
  796. }
  797. }
  798. /* Check if the ID3 metadata contents have changed */
  799. static int id3_has_changed_values(struct playlist *pls, AVDictionary *metadata,
  800. ID3v2ExtraMetaAPIC *apic)
  801. {
  802. AVDictionaryEntry *entry = NULL;
  803. AVDictionaryEntry *oldentry;
  804. /* check that no keys have changed values */
  805. while ((entry = av_dict_get(metadata, "", entry, AV_DICT_IGNORE_SUFFIX))) {
  806. oldentry = av_dict_get(pls->id3_initial, entry->key, NULL, AV_DICT_MATCH_CASE);
  807. if (!oldentry || strcmp(oldentry->value, entry->value) != 0)
  808. return 1;
  809. }
  810. /* check if apic appeared */
  811. if (apic && (pls->ctx->nb_streams != 2 || !pls->ctx->streams[1]->attached_pic.data))
  812. return 1;
  813. if (apic) {
  814. int size = pls->ctx->streams[1]->attached_pic.size;
  815. if (size != apic->buf->size - AV_INPUT_BUFFER_PADDING_SIZE)
  816. return 1;
  817. if (memcmp(apic->buf->data, pls->ctx->streams[1]->attached_pic.data, size) != 0)
  818. return 1;
  819. }
  820. return 0;
  821. }
  822. /* Parse ID3 data and handle the found data */
  823. static void handle_id3(AVIOContext *pb, struct playlist *pls)
  824. {
  825. AVDictionary *metadata = NULL;
  826. ID3v2ExtraMetaAPIC *apic = NULL;
  827. ID3v2ExtraMeta *extra_meta = NULL;
  828. int64_t timestamp = AV_NOPTS_VALUE;
  829. parse_id3(pls->ctx, pb, &metadata, &timestamp, &apic, &extra_meta);
  830. if (timestamp != AV_NOPTS_VALUE) {
  831. pls->id3_mpegts_timestamp = timestamp;
  832. pls->id3_offset = 0;
  833. }
  834. if (!pls->id3_found) {
  835. /* initial ID3 tags */
  836. av_assert0(!pls->id3_deferred_extra);
  837. pls->id3_found = 1;
  838. /* get picture attachment and set text metadata */
  839. if (pls->ctx->nb_streams)
  840. ff_id3v2_parse_apic(pls->ctx, &extra_meta);
  841. else
  842. /* demuxer not yet opened, defer picture attachment */
  843. pls->id3_deferred_extra = extra_meta;
  844. av_dict_copy(&pls->ctx->metadata, metadata, 0);
  845. pls->id3_initial = metadata;
  846. } else {
  847. if (!pls->id3_changed && id3_has_changed_values(pls, metadata, apic)) {
  848. avpriv_report_missing_feature(pls->ctx, "Changing ID3 metadata in HLS audio elementary stream");
  849. pls->id3_changed = 1;
  850. }
  851. av_dict_free(&metadata);
  852. }
  853. if (!pls->id3_deferred_extra)
  854. ff_id3v2_free_extra_meta(&extra_meta);
  855. }
  856. static void intercept_id3(struct playlist *pls, uint8_t *buf,
  857. int buf_size, int *len)
  858. {
  859. /* intercept id3 tags, we do not want to pass them to the raw
  860. * demuxer on all segment switches */
  861. int bytes;
  862. int id3_buf_pos = 0;
  863. int fill_buf = 0;
  864. struct segment *seg = current_segment(pls);
  865. /* gather all the id3 tags */
  866. while (1) {
  867. /* see if we can retrieve enough data for ID3 header */
  868. if (*len < ID3v2_HEADER_SIZE && buf_size >= ID3v2_HEADER_SIZE) {
  869. bytes = read_from_url(pls, seg, buf + *len, ID3v2_HEADER_SIZE - *len, READ_COMPLETE);
  870. if (bytes > 0) {
  871. if (bytes == ID3v2_HEADER_SIZE - *len)
  872. /* no EOF yet, so fill the caller buffer again after
  873. * we have stripped the ID3 tags */
  874. fill_buf = 1;
  875. *len += bytes;
  876. } else if (*len <= 0) {
  877. /* error/EOF */
  878. *len = bytes;
  879. fill_buf = 0;
  880. }
  881. }
  882. if (*len < ID3v2_HEADER_SIZE)
  883. break;
  884. if (ff_id3v2_match(buf, ID3v2_DEFAULT_MAGIC)) {
  885. int64_t maxsize = seg->size >= 0 ? seg->size : 1024*1024;
  886. int taglen = ff_id3v2_tag_len(buf);
  887. int tag_got_bytes = FFMIN(taglen, *len);
  888. int remaining = taglen - tag_got_bytes;
  889. if (taglen > maxsize) {
  890. av_log(pls->ctx, AV_LOG_ERROR, "Too large HLS ID3 tag (%d > %"PRId64" bytes)\n",
  891. taglen, maxsize);
  892. break;
  893. }
  894. /*
  895. * Copy the id3 tag to our temporary id3 buffer.
  896. * We could read a small id3 tag directly without memcpy, but
  897. * we would still need to copy the large tags, and handling
  898. * both of those cases together with the possibility for multiple
  899. * tags would make the handling a bit complex.
  900. */
  901. pls->id3_buf = av_fast_realloc(pls->id3_buf, &pls->id3_buf_size, id3_buf_pos + taglen);
  902. if (!pls->id3_buf)
  903. break;
  904. memcpy(pls->id3_buf + id3_buf_pos, buf, tag_got_bytes);
  905. id3_buf_pos += tag_got_bytes;
  906. /* strip the intercepted bytes */
  907. *len -= tag_got_bytes;
  908. memmove(buf, buf + tag_got_bytes, *len);
  909. av_log(pls->ctx, AV_LOG_DEBUG, "Stripped %d HLS ID3 bytes\n", tag_got_bytes);
  910. if (remaining > 0) {
  911. /* read the rest of the tag in */
  912. if (read_from_url(pls, seg, pls->id3_buf + id3_buf_pos, remaining, READ_COMPLETE) != remaining)
  913. break;
  914. id3_buf_pos += remaining;
  915. av_log(pls->ctx, AV_LOG_DEBUG, "Stripped additional %d HLS ID3 bytes\n", remaining);
  916. }
  917. } else {
  918. /* no more ID3 tags */
  919. break;
  920. }
  921. }
  922. /* re-fill buffer for the caller unless EOF */
  923. if (*len >= 0 && (fill_buf || *len == 0)) {
  924. bytes = read_from_url(pls, seg, buf + *len, buf_size - *len, READ_NORMAL);
  925. /* ignore error if we already had some data */
  926. if (bytes >= 0)
  927. *len += bytes;
  928. else if (*len == 0)
  929. *len = bytes;
  930. }
  931. if (pls->id3_buf) {
  932. /* Now parse all the ID3 tags */
  933. AVIOContext id3ioctx;
  934. ffio_init_context(&id3ioctx, pls->id3_buf, id3_buf_pos, 0, NULL, NULL, NULL, NULL);
  935. handle_id3(&id3ioctx, pls);
  936. }
  937. if (pls->is_id3_timestamped == -1)
  938. pls->is_id3_timestamped = (pls->id3_mpegts_timestamp != AV_NOPTS_VALUE);
  939. }
  940. static int open_input(HLSContext *c, struct playlist *pls, struct segment *seg)
  941. {
  942. AVDictionary *opts = NULL;
  943. int ret;
  944. // broker prior HTTP options that should be consistent across requests
  945. av_dict_set(&opts, "user-agent", c->user_agent, 0);
  946. av_dict_set(&opts, "cookies", c->cookies, 0);
  947. av_dict_set(&opts, "headers", c->headers, 0);
  948. av_dict_set(&opts, "http_proxy", c->http_proxy, 0);
  949. av_dict_set(&opts, "seekable", "0", 0);
  950. if (seg->size >= 0) {
  951. /* try to restrict the HTTP request to the part we want
  952. * (if this is in fact a HTTP request) */
  953. av_dict_set_int(&opts, "offset", seg->url_offset, 0);
  954. av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
  955. }
  956. av_log(pls->parent, AV_LOG_VERBOSE, "HLS request for url '%s', offset %"PRId64", playlist %d\n",
  957. seg->url, seg->url_offset, pls->index);
  958. if (seg->key_type == KEY_NONE) {
  959. ret = open_url(pls->parent, &pls->input, seg->url, c->avio_opts, opts);
  960. } else if (seg->key_type == KEY_AES_128) {
  961. AVDictionary *opts2 = NULL;
  962. char iv[33], key[33], url[MAX_URL_SIZE];
  963. if (strcmp(seg->key, pls->key_url)) {
  964. AVIOContext *pb;
  965. if (open_url(pls->parent, &pb, seg->key, c->avio_opts, opts) == 0) {
  966. ret = avio_read(pb, pls->key, sizeof(pls->key));
  967. if (ret != sizeof(pls->key)) {
  968. av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
  969. seg->key);
  970. }
  971. ff_format_io_close(pls->parent, &pb);
  972. } else {
  973. av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
  974. seg->key);
  975. }
  976. av_strlcpy(pls->key_url, seg->key, sizeof(pls->key_url));
  977. }
  978. ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
  979. ff_data_to_hex(key, pls->key, sizeof(pls->key), 0);
  980. iv[32] = key[32] = '\0';
  981. if (strstr(seg->url, "://"))
  982. snprintf(url, sizeof(url), "crypto+%s", seg->url);
  983. else
  984. snprintf(url, sizeof(url), "crypto:%s", seg->url);
  985. av_dict_copy(&opts2, c->avio_opts, 0);
  986. av_dict_set(&opts2, "key", key, 0);
  987. av_dict_set(&opts2, "iv", iv, 0);
  988. ret = open_url(pls->parent, &pls->input, url, opts2, opts);
  989. av_dict_free(&opts2);
  990. if (ret < 0) {
  991. goto cleanup;
  992. }
  993. ret = 0;
  994. } else if (seg->key_type == KEY_SAMPLE_AES) {
  995. av_log(pls->parent, AV_LOG_ERROR,
  996. "SAMPLE-AES encryption is not supported yet\n");
  997. ret = AVERROR_PATCHWELCOME;
  998. }
  999. else
  1000. ret = AVERROR(ENOSYS);
  1001. /* Seek to the requested position. If this was a HTTP request, the offset
  1002. * should already be where want it to, but this allows e.g. local testing
  1003. * without a HTTP server. */
  1004. if (ret == 0 && seg->key_type == KEY_NONE && seg->url_offset) {
  1005. int64_t seekret = avio_seek(pls->input, seg->url_offset, SEEK_SET);
  1006. if (seekret < 0) {
  1007. av_log(pls->parent, AV_LOG_ERROR, "Unable to seek to offset %"PRId64" of HLS segment '%s'\n", seg->url_offset, seg->url);
  1008. ret = seekret;
  1009. ff_format_io_close(pls->parent, &pls->input);
  1010. }
  1011. }
  1012. cleanup:
  1013. av_dict_free(&opts);
  1014. pls->cur_seg_offset = 0;
  1015. return ret;
  1016. }
  1017. static int update_init_section(struct playlist *pls, struct segment *seg)
  1018. {
  1019. static const int max_init_section_size = 1024*1024;
  1020. HLSContext *c = pls->parent->priv_data;
  1021. int64_t sec_size;
  1022. int64_t urlsize;
  1023. int ret;
  1024. if (seg->init_section == pls->cur_init_section)
  1025. return 0;
  1026. pls->cur_init_section = NULL;
  1027. if (!seg->init_section)
  1028. return 0;
  1029. ret = open_input(c, pls, seg->init_section);
  1030. if (ret < 0) {
  1031. av_log(pls->parent, AV_LOG_WARNING,
  1032. "Failed to open an initialization section in playlist %d\n",
  1033. pls->index);
  1034. return ret;
  1035. }
  1036. if (seg->init_section->size >= 0)
  1037. sec_size = seg->init_section->size;
  1038. else if ((urlsize = avio_size(pls->input)) >= 0)
  1039. sec_size = urlsize;
  1040. else
  1041. sec_size = max_init_section_size;
  1042. av_log(pls->parent, AV_LOG_DEBUG,
  1043. "Downloading an initialization section of size %"PRId64"\n",
  1044. sec_size);
  1045. sec_size = FFMIN(sec_size, max_init_section_size);
  1046. av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
  1047. ret = read_from_url(pls, seg->init_section, pls->init_sec_buf,
  1048. pls->init_sec_buf_size, READ_COMPLETE);
  1049. ff_format_io_close(pls->parent, &pls->input);
  1050. if (ret < 0)
  1051. return ret;
  1052. pls->cur_init_section = seg->init_section;
  1053. pls->init_sec_data_len = ret;
  1054. pls->init_sec_buf_read_offset = 0;
  1055. /* spec says audio elementary streams do not have media initialization
  1056. * sections, so there should be no ID3 timestamps */
  1057. pls->is_id3_timestamped = 0;
  1058. return 0;
  1059. }
  1060. static int64_t default_reload_interval(struct playlist *pls)
  1061. {
  1062. return pls->n_segments > 0 ?
  1063. pls->segments[pls->n_segments - 1]->duration :
  1064. pls->target_duration;
  1065. }
  1066. static int read_data(void *opaque, uint8_t *buf, int buf_size)
  1067. {
  1068. struct playlist *v = opaque;
  1069. HLSContext *c = v->parent->priv_data;
  1070. int ret, i;
  1071. int just_opened = 0;
  1072. restart:
  1073. if (!v->needed)
  1074. return AVERROR_EOF;
  1075. if (!v->input) {
  1076. int64_t reload_interval;
  1077. struct segment *seg;
  1078. /* Check that the playlist is still needed before opening a new
  1079. * segment. */
  1080. if (v->ctx && v->ctx->nb_streams &&
  1081. v->parent->nb_streams >= v->stream_offset + v->ctx->nb_streams) {
  1082. v->needed = 0;
  1083. for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;
  1084. i++) {
  1085. if (v->parent->streams[i]->discard < AVDISCARD_ALL)
  1086. v->needed = 1;
  1087. }
  1088. }
  1089. if (!v->needed) {
  1090. av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
  1091. v->index);
  1092. return AVERROR_EOF;
  1093. }
  1094. /* If this is a live stream and the reload interval has elapsed since
  1095. * the last playlist reload, reload the playlists now. */
  1096. reload_interval = default_reload_interval(v);
  1097. reload:
  1098. if (!v->finished &&
  1099. av_gettime_relative() - v->last_load_time >= reload_interval) {
  1100. if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {
  1101. av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",
  1102. v->index);
  1103. return ret;
  1104. }
  1105. /* If we need to reload the playlist again below (if
  1106. * there's still no more segments), switch to a reload
  1107. * interval of half the target duration. */
  1108. reload_interval = v->target_duration / 2;
  1109. }
  1110. if (v->cur_seq_no < v->start_seq_no) {
  1111. av_log(NULL, AV_LOG_WARNING,
  1112. "skipping %d segments ahead, expired from playlists\n",
  1113. v->start_seq_no - v->cur_seq_no);
  1114. v->cur_seq_no = v->start_seq_no;
  1115. }
  1116. if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
  1117. if (v->finished)
  1118. return AVERROR_EOF;
  1119. while (av_gettime_relative() - v->last_load_time < reload_interval) {
  1120. if (ff_check_interrupt(c->interrupt_callback))
  1121. return AVERROR_EXIT;
  1122. av_usleep(100*1000);
  1123. }
  1124. /* Enough time has elapsed since the last reload */
  1125. goto reload;
  1126. }
  1127. seg = current_segment(v);
  1128. /* load/update Media Initialization Section, if any */
  1129. ret = update_init_section(v, seg);
  1130. if (ret)
  1131. return ret;
  1132. ret = open_input(c, v, seg);
  1133. if (ret < 0) {
  1134. if (ff_check_interrupt(c->interrupt_callback))
  1135. return AVERROR_EXIT;
  1136. av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n",
  1137. v->index);
  1138. v->cur_seq_no += 1;
  1139. goto reload;
  1140. }
  1141. just_opened = 1;
  1142. }
  1143. if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
  1144. /* Push init section out first before first actual segment */
  1145. int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
  1146. memcpy(buf, v->init_sec_buf, copy_size);
  1147. v->init_sec_buf_read_offset += copy_size;
  1148. return copy_size;
  1149. }
  1150. ret = read_from_url(v, current_segment(v), buf, buf_size, READ_NORMAL);
  1151. if (ret > 0) {
  1152. if (just_opened && v->is_id3_timestamped != 0) {
  1153. /* Intercept ID3 tags here, elementary audio streams are required
  1154. * to convey timestamps using them in the beginning of each segment. */
  1155. intercept_id3(v, buf, buf_size, &ret);
  1156. }
  1157. return ret;
  1158. }
  1159. ff_format_io_close(v->parent, &v->input);
  1160. v->cur_seq_no++;
  1161. c->cur_seq_no = v->cur_seq_no;
  1162. goto restart;
  1163. }
  1164. static int playlist_in_multiple_variants(HLSContext *c, struct playlist *pls)
  1165. {
  1166. int variant_count = 0;
  1167. int i, j;
  1168. for (i = 0; i < c->n_variants && variant_count < 2; i++) {
  1169. struct variant *v = c->variants[i];
  1170. for (j = 0; j < v->n_playlists; j++) {
  1171. if (v->playlists[j] == pls) {
  1172. variant_count++;
  1173. break;
  1174. }
  1175. }
  1176. }
  1177. return variant_count >= 2;
  1178. }
  1179. static void add_renditions_to_variant(HLSContext *c, struct variant *var,
  1180. enum AVMediaType type, const char *group_id)
  1181. {
  1182. int i;
  1183. for (i = 0; i < c->n_renditions; i++) {
  1184. struct rendition *rend = c->renditions[i];
  1185. if (rend->type == type && !strcmp(rend->group_id, group_id)) {
  1186. if (rend->playlist)
  1187. /* rendition is an external playlist
  1188. * => add the playlist to the variant */
  1189. dynarray_add(&var->playlists, &var->n_playlists, rend->playlist);
  1190. else
  1191. /* rendition is part of the variant main Media Playlist
  1192. * => add the rendition to the main Media Playlist */
  1193. dynarray_add(&var->playlists[0]->renditions,
  1194. &var->playlists[0]->n_renditions,
  1195. rend);
  1196. }
  1197. }
  1198. }
  1199. static void add_metadata_from_renditions(AVFormatContext *s, struct playlist *pls,
  1200. enum AVMediaType type)
  1201. {
  1202. int rend_idx = 0;
  1203. int i;
  1204. for (i = 0; i < pls->ctx->nb_streams; i++) {
  1205. AVStream *st = s->streams[pls->stream_offset + i];
  1206. if (st->codec->codec_type != type)
  1207. continue;
  1208. for (; rend_idx < pls->n_renditions; rend_idx++) {
  1209. struct rendition *rend = pls->renditions[rend_idx];
  1210. if (rend->type != type)
  1211. continue;
  1212. if (rend->language[0])
  1213. av_dict_set(&st->metadata, "language", rend->language, 0);
  1214. if (rend->name[0])
  1215. av_dict_set(&st->metadata, "comment", rend->name, 0);
  1216. st->disposition |= rend->disposition;
  1217. }
  1218. if (rend_idx >=pls->n_renditions)
  1219. break;
  1220. }
  1221. }
  1222. /* if timestamp was in valid range: returns 1 and sets seq_no
  1223. * if not: returns 0 and sets seq_no to closest segment */
  1224. static int find_timestamp_in_playlist(HLSContext *c, struct playlist *pls,
  1225. int64_t timestamp, int *seq_no)
  1226. {
  1227. int i;
  1228. int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
  1229. 0 : c->first_timestamp;
  1230. if (timestamp < pos) {
  1231. *seq_no = pls->start_seq_no;
  1232. return 0;
  1233. }
  1234. for (i = 0; i < pls->n_segments; i++) {
  1235. int64_t diff = pos + pls->segments[i]->duration - timestamp;
  1236. if (diff > 0) {
  1237. *seq_no = pls->start_seq_no + i;
  1238. return 1;
  1239. }
  1240. pos += pls->segments[i]->duration;
  1241. }
  1242. *seq_no = pls->start_seq_no + pls->n_segments - 1;
  1243. return 0;
  1244. }
  1245. static int select_cur_seq_no(HLSContext *c, struct playlist *pls)
  1246. {
  1247. int seq_no;
  1248. if (!pls->finished && !c->first_packet &&
  1249. av_gettime_relative() - pls->last_load_time >= default_reload_interval(pls))
  1250. /* reload the playlist since it was suspended */
  1251. parse_playlist(c, pls->url, pls, NULL);
  1252. /* If playback is already in progress (we are just selecting a new
  1253. * playlist) and this is a complete file, find the matching segment
  1254. * by counting durations. */
  1255. if (pls->finished && c->cur_timestamp != AV_NOPTS_VALUE) {
  1256. find_timestamp_in_playlist(c, pls, c->cur_timestamp, &seq_no);
  1257. return seq_no;
  1258. }
  1259. if (!pls->finished) {
  1260. if (!c->first_packet && /* we are doing a segment selection during playback */
  1261. c->cur_seq_no >= pls->start_seq_no &&
  1262. c->cur_seq_no < pls->start_seq_no + pls->n_segments)
  1263. /* While spec 3.4.3 says that we cannot assume anything about the
  1264. * content at the same sequence number on different playlists,
  1265. * in practice this seems to work and doing it otherwise would
  1266. * require us to download a segment to inspect its timestamps. */
  1267. return c->cur_seq_no;
  1268. /* If this is a live stream, start live_start_index segments from the
  1269. * start or end */
  1270. if (c->live_start_index < 0)
  1271. return pls->start_seq_no + FFMAX(pls->n_segments + c->live_start_index, 0);
  1272. else
  1273. return pls->start_seq_no + FFMIN(c->live_start_index, pls->n_segments - 1);
  1274. }
  1275. /* Otherwise just start on the first segment. */
  1276. return pls->start_seq_no;
  1277. }
  1278. static int save_avio_options(AVFormatContext *s)
  1279. {
  1280. HLSContext *c = s->priv_data;
  1281. const char *opts[] = {
  1282. "headers", "http_proxy", "user_agent", "user-agent", "cookies", NULL };
  1283. const char **opt = opts;
  1284. uint8_t *buf;
  1285. int ret = 0;
  1286. while (*opt) {
  1287. if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN | AV_OPT_ALLOW_NULL, &buf) >= 0) {
  1288. ret = av_dict_set(&c->avio_opts, *opt, buf,
  1289. AV_DICT_DONT_STRDUP_VAL);
  1290. if (ret < 0)
  1291. return ret;
  1292. }
  1293. opt++;
  1294. }
  1295. return ret;
  1296. }
  1297. static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
  1298. int flags, AVDictionary **opts)
  1299. {
  1300. av_log(s, AV_LOG_ERROR,
  1301. "A HLS playlist item '%s' referred to an external file '%s'. "
  1302. "Opening this file was forbidden for security reasons\n",
  1303. s->filename, url);
  1304. return AVERROR(EPERM);
  1305. }
  1306. static int hls_read_header(AVFormatContext *s)
  1307. {
  1308. void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb;
  1309. HLSContext *c = s->priv_data;
  1310. int ret = 0, i, j, stream_offset = 0;
  1311. c->ctx = s;
  1312. c->interrupt_callback = &s->interrupt_callback;
  1313. c->strict_std_compliance = s->strict_std_compliance;
  1314. c->first_packet = 1;
  1315. c->first_timestamp = AV_NOPTS_VALUE;
  1316. c->cur_timestamp = AV_NOPTS_VALUE;
  1317. if (u) {
  1318. // get the previous user agent & set back to null if string size is zero
  1319. update_options(&c->user_agent, "user-agent", u);
  1320. // get the previous cookies & set back to null if string size is zero
  1321. update_options(&c->cookies, "cookies", u);
  1322. // get the previous headers & set back to null if string size is zero
  1323. update_options(&c->headers, "headers", u);
  1324. // get the previous http proxt & set back to null if string size is zero
  1325. update_options(&c->http_proxy, "http_proxy", u);
  1326. }
  1327. if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
  1328. goto fail;
  1329. if ((ret = save_avio_options(s)) < 0)
  1330. goto fail;
  1331. /* Some HLS servers don't like being sent the range header */
  1332. av_dict_set(&c->avio_opts, "seekable", "0", 0);
  1333. if (c->n_variants == 0) {
  1334. av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
  1335. ret = AVERROR_EOF;
  1336. goto fail;
  1337. }
  1338. /* If the playlist only contained playlists (Master Playlist),
  1339. * parse each individual playlist. */
  1340. if (c->n_playlists > 1 || c->playlists[0]->n_segments == 0) {
  1341. for (i = 0; i < c->n_playlists; i++) {
  1342. struct playlist *pls = c->playlists[i];
  1343. if ((ret = parse_playlist(c, pls->url, pls, NULL)) < 0)
  1344. goto fail;
  1345. }
  1346. }
  1347. if (c->variants[0]->playlists[0]->n_segments == 0) {
  1348. av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
  1349. ret = AVERROR_EOF;
  1350. goto fail;
  1351. }
  1352. /* If this isn't a live stream, calculate the total duration of the
  1353. * stream. */
  1354. if (c->variants[0]->playlists[0]->finished) {
  1355. int64_t duration = 0;
  1356. for (i = 0; i < c->variants[0]->playlists[0]->n_segments; i++)
  1357. duration += c->variants[0]->playlists[0]->segments[i]->duration;
  1358. s->duration = duration;
  1359. }
  1360. /* Associate renditions with variants */
  1361. for (i = 0; i < c->n_variants; i++) {
  1362. struct variant *var = c->variants[i];
  1363. if (var->audio_group[0])
  1364. add_renditions_to_variant(c, var, AVMEDIA_TYPE_AUDIO, var->audio_group);
  1365. if (var->video_group[0])
  1366. add_renditions_to_variant(c, var, AVMEDIA_TYPE_VIDEO, var->video_group);
  1367. if (var->subtitles_group[0])
  1368. add_renditions_to_variant(c, var, AVMEDIA_TYPE_SUBTITLE, var->subtitles_group);
  1369. }
  1370. /* Open the demuxer for each playlist */
  1371. for (i = 0; i < c->n_playlists; i++) {
  1372. struct playlist *pls = c->playlists[i];
  1373. AVInputFormat *in_fmt = NULL;
  1374. if (!(pls->ctx = avformat_alloc_context())) {
  1375. ret = AVERROR(ENOMEM);
  1376. goto fail;
  1377. }
  1378. if (pls->n_segments == 0)
  1379. continue;
  1380. pls->index = i;
  1381. pls->needed = 1;
  1382. pls->parent = s;
  1383. pls->cur_seq_no = select_cur_seq_no(c, pls);
  1384. pls->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
  1385. if (!pls->read_buffer){
  1386. ret = AVERROR(ENOMEM);
  1387. avformat_free_context(pls->ctx);
  1388. pls->ctx = NULL;
  1389. goto fail;
  1390. }
  1391. ffio_init_context(&pls->pb, pls->read_buffer, INITIAL_BUFFER_SIZE, 0, pls,
  1392. read_data, NULL, NULL);
  1393. pls->pb.seekable = 0;
  1394. ret = av_probe_input_buffer(&pls->pb, &in_fmt, pls->segments[0]->url,
  1395. NULL, 0, 0);
  1396. if (ret < 0) {
  1397. /* Free the ctx - it isn't initialized properly at this point,
  1398. * so avformat_close_input shouldn't be called. If
  1399. * avformat_open_input fails below, it frees and zeros the
  1400. * context, so it doesn't need any special treatment like this. */
  1401. av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", pls->segments[0]->url);
  1402. avformat_free_context(pls->ctx);
  1403. pls->ctx = NULL;
  1404. goto fail;
  1405. }
  1406. pls->ctx->pb = &pls->pb;
  1407. pls->ctx->io_open = nested_io_open;
  1408. pls->stream_offset = stream_offset;
  1409. if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
  1410. goto fail;
  1411. ret = avformat_open_input(&pls->ctx, pls->segments[0]->url, in_fmt, NULL);
  1412. if (ret < 0)
  1413. goto fail;
  1414. if (pls->id3_deferred_extra && pls->ctx->nb_streams == 1) {
  1415. ff_id3v2_parse_apic(pls->ctx, &pls->id3_deferred_extra);
  1416. avformat_queue_attached_pictures(pls->ctx);
  1417. ff_id3v2_free_extra_meta(&pls->id3_deferred_extra);
  1418. pls->id3_deferred_extra = NULL;
  1419. }
  1420. pls->ctx->ctx_flags &= ~AVFMTCTX_NOHEADER;
  1421. ret = avformat_find_stream_info(pls->ctx, NULL);
  1422. if (ret < 0)
  1423. goto fail;
  1424. if (pls->is_id3_timestamped == -1)
  1425. av_log(s, AV_LOG_WARNING, "No expected HTTP requests have been made\n");
  1426. /* Create new AVStreams for each stream in this playlist */
  1427. for (j = 0; j < pls->ctx->nb_streams; j++) {
  1428. AVStream *st = avformat_new_stream(s, NULL);
  1429. AVStream *ist = pls->ctx->streams[j];
  1430. if (!st) {
  1431. ret = AVERROR(ENOMEM);
  1432. goto fail;
  1433. }
  1434. st->id = i;
  1435. avcodec_copy_context(st->codec, pls->ctx->streams[j]->codec);
  1436. if (pls->is_id3_timestamped) /* custom timestamps via id3 */
  1437. avpriv_set_pts_info(st, 33, 1, MPEG_TIME_BASE);
  1438. else
  1439. avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
  1440. }
  1441. add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_AUDIO);
  1442. add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_VIDEO);
  1443. add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_SUBTITLE);
  1444. stream_offset += pls->ctx->nb_streams;
  1445. }
  1446. /* Create a program for each variant */
  1447. for (i = 0; i < c->n_variants; i++) {
  1448. struct variant *v = c->variants[i];
  1449. AVProgram *program;
  1450. program = av_new_program(s, i);
  1451. if (!program)
  1452. goto fail;
  1453. av_dict_set_int(&program->metadata, "variant_bitrate", v->bandwidth, 0);
  1454. for (j = 0; j < v->n_playlists; j++) {
  1455. struct playlist *pls = v->playlists[j];
  1456. int is_shared = playlist_in_multiple_variants(c, pls);
  1457. int k;
  1458. for (k = 0; k < pls->ctx->nb_streams; k++) {
  1459. struct AVStream *st = s->streams[pls->stream_offset + k];
  1460. av_program_add_stream_index(s, i, pls->stream_offset + k);
  1461. /* Set variant_bitrate for streams unique to this variant */
  1462. if (!is_shared && v->bandwidth)
  1463. av_dict_set_int(&st->metadata, "variant_bitrate", v->bandwidth, 0);
  1464. }
  1465. }
  1466. }
  1467. return 0;
  1468. fail:
  1469. free_playlist_list(c);
  1470. free_variant_list(c);
  1471. free_rendition_list(c);
  1472. return ret;
  1473. }
  1474. static int recheck_discard_flags(AVFormatContext *s, int first)
  1475. {
  1476. HLSContext *c = s->priv_data;
  1477. int i, changed = 0;
  1478. /* Check if any new streams are needed */
  1479. for (i = 0; i < c->n_playlists; i++)
  1480. c->playlists[i]->cur_needed = 0;
  1481. for (i = 0; i < s->nb_streams; i++) {
  1482. AVStream *st = s->streams[i];
  1483. struct playlist *pls = c->playlists[s->streams[i]->id];
  1484. if (st->discard < AVDISCARD_ALL)
  1485. pls->cur_needed = 1;
  1486. }
  1487. for (i = 0; i < c->n_playlists; i++) {
  1488. struct playlist *pls = c->playlists[i];
  1489. if (pls->cur_needed && !pls->needed) {
  1490. pls->needed = 1;
  1491. changed = 1;
  1492. pls->cur_seq_no = select_cur_seq_no(c, pls);
  1493. pls->pb.eof_reached = 0;
  1494. if (c->cur_timestamp != AV_NOPTS_VALUE) {
  1495. /* catch up */
  1496. pls->seek_timestamp = c->cur_timestamp;
  1497. pls->seek_flags = AVSEEK_FLAG_ANY;
  1498. pls->seek_stream_index = -1;
  1499. }
  1500. av_log(s, AV_LOG_INFO, "Now receiving playlist %d, segment %d\n", i, pls->cur_seq_no);
  1501. } else if (first && !pls->cur_needed && pls->needed) {
  1502. if (pls->input)
  1503. ff_format_io_close(pls->parent, &pls->input);
  1504. pls->needed = 0;
  1505. changed = 1;
  1506. av_log(s, AV_LOG_INFO, "No longer receiving playlist %d\n", i);
  1507. }
  1508. }
  1509. return changed;
  1510. }
  1511. static void fill_timing_for_id3_timestamped_stream(struct playlist *pls)
  1512. {
  1513. if (pls->id3_offset >= 0) {
  1514. pls->pkt.dts = pls->id3_mpegts_timestamp +
  1515. av_rescale_q(pls->id3_offset,
  1516. pls->ctx->streams[pls->pkt.stream_index]->time_base,
  1517. MPEG_TIME_BASE_Q);
  1518. if (pls->pkt.duration)
  1519. pls->id3_offset += pls->pkt.duration;
  1520. else
  1521. pls->id3_offset = -1;
  1522. } else {
  1523. /* there have been packets with unknown duration
  1524. * since the last id3 tag, should not normally happen */
  1525. pls->pkt.dts = AV_NOPTS_VALUE;
  1526. }
  1527. if (pls->pkt.duration)
  1528. pls->pkt.duration = av_rescale_q(pls->pkt.duration,
  1529. pls->ctx->streams[pls->pkt.stream_index]->time_base,
  1530. MPEG_TIME_BASE_Q);
  1531. pls->pkt.pts = AV_NOPTS_VALUE;
  1532. }
  1533. static AVRational get_timebase(struct playlist *pls)
  1534. {
  1535. if (pls->is_id3_timestamped)
  1536. return MPEG_TIME_BASE_Q;
  1537. return pls->ctx->streams[pls->pkt.stream_index]->time_base;
  1538. }
  1539. static int compare_ts_with_wrapdetect(int64_t ts_a, struct playlist *pls_a,
  1540. int64_t ts_b, struct playlist *pls_b)
  1541. {
  1542. int64_t scaled_ts_a = av_rescale_q(ts_a, get_timebase(pls_a), MPEG_TIME_BASE_Q);
  1543. int64_t scaled_ts_b = av_rescale_q(ts_b, get_timebase(pls_b), MPEG_TIME_BASE_Q);
  1544. return av_compare_mod(scaled_ts_a, scaled_ts_b, 1LL << 33);
  1545. }
  1546. static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
  1547. {
  1548. HLSContext *c = s->priv_data;
  1549. int ret, i, minplaylist = -1;
  1550. recheck_discard_flags(s, c->first_packet);
  1551. c->first_packet = 0;
  1552. for (i = 0; i < c->n_playlists; i++) {
  1553. struct playlist *pls = c->playlists[i];
  1554. /* Make sure we've got one buffered packet from each open playlist
  1555. * stream */
  1556. if (pls->needed && !pls->pkt.data) {
  1557. while (1) {
  1558. int64_t ts_diff;
  1559. AVRational tb;
  1560. ret = av_read_frame(pls->ctx, &pls->pkt);
  1561. if (ret < 0) {
  1562. if (!avio_feof(&pls->pb) && ret != AVERROR_EOF)
  1563. return ret;
  1564. reset_packet(&pls->pkt);
  1565. break;
  1566. } else {
  1567. /* stream_index check prevents matching picture attachments etc. */
  1568. if (pls->is_id3_timestamped && pls->pkt.stream_index == 0) {
  1569. /* audio elementary streams are id3 timestamped */
  1570. fill_timing_for_id3_timestamped_stream(pls);
  1571. }
  1572. if (c->first_timestamp == AV_NOPTS_VALUE &&
  1573. pls->pkt.dts != AV_NOPTS_VALUE)
  1574. c->first_timestamp = av_rescale_q(pls->pkt.dts,
  1575. get_timebase(pls), AV_TIME_BASE_Q);
  1576. }
  1577. if (pls->seek_timestamp == AV_NOPTS_VALUE)
  1578. break;
  1579. if (pls->seek_stream_index < 0 ||
  1580. pls->seek_stream_index == pls->pkt.stream_index) {
  1581. if (pls->pkt.dts == AV_NOPTS_VALUE) {
  1582. pls->seek_timestamp = AV_NOPTS_VALUE;
  1583. break;
  1584. }
  1585. tb = get_timebase(pls);
  1586. ts_diff = av_rescale_rnd(pls->pkt.dts, AV_TIME_BASE,
  1587. tb.den, AV_ROUND_DOWN) -
  1588. pls->seek_timestamp;
  1589. if (ts_diff >= 0 && (pls->seek_flags & AVSEEK_FLAG_ANY ||
  1590. pls->pkt.flags & AV_PKT_FLAG_KEY)) {
  1591. pls->seek_timestamp = AV_NOPTS_VALUE;
  1592. break;
  1593. }
  1594. }
  1595. av_packet_unref(&pls->pkt);
  1596. reset_packet(&pls->pkt);
  1597. }
  1598. }
  1599. /* Check if this stream has the packet with the lowest dts */
  1600. if (pls->pkt.data) {
  1601. struct playlist *minpls = minplaylist < 0 ?
  1602. NULL : c->playlists[minplaylist];
  1603. if (minplaylist < 0) {
  1604. minplaylist = i;
  1605. } else {
  1606. int64_t dts = pls->pkt.dts;
  1607. int64_t mindts = minpls->pkt.dts;
  1608. if (dts == AV_NOPTS_VALUE ||
  1609. (mindts != AV_NOPTS_VALUE && compare_ts_with_wrapdetect(dts, pls, mindts, minpls) < 0))
  1610. minplaylist = i;
  1611. }
  1612. }
  1613. }
  1614. /* If we got a packet, return it */
  1615. if (minplaylist >= 0) {
  1616. struct playlist *pls = c->playlists[minplaylist];
  1617. *pkt = pls->pkt;
  1618. pkt->stream_index += pls->stream_offset;
  1619. reset_packet(&c->playlists[minplaylist]->pkt);
  1620. if (pkt->dts != AV_NOPTS_VALUE)
  1621. c->cur_timestamp = av_rescale_q(pkt->dts,
  1622. pls->ctx->streams[pls->pkt.stream_index]->time_base,
  1623. AV_TIME_BASE_Q);
  1624. return 0;
  1625. }
  1626. return AVERROR_EOF;
  1627. }
  1628. static int hls_close(AVFormatContext *s)
  1629. {
  1630. HLSContext *c = s->priv_data;
  1631. free_playlist_list(c);
  1632. free_variant_list(c);
  1633. free_rendition_list(c);
  1634. av_dict_free(&c->avio_opts);
  1635. return 0;
  1636. }
  1637. static int hls_read_seek(AVFormatContext *s, int stream_index,
  1638. int64_t timestamp, int flags)
  1639. {
  1640. HLSContext *c = s->priv_data;
  1641. struct playlist *seek_pls = NULL;
  1642. int i, seq_no;
  1643. int64_t first_timestamp, seek_timestamp, duration;
  1644. if ((flags & AVSEEK_FLAG_BYTE) ||
  1645. !(c->variants[0]->playlists[0]->finished || c->variants[0]->playlists[0]->type == PLS_TYPE_EVENT))
  1646. return AVERROR(ENOSYS);
  1647. first_timestamp = c->first_timestamp == AV_NOPTS_VALUE ?
  1648. 0 : c->first_timestamp;
  1649. seek_timestamp = av_rescale_rnd(timestamp, AV_TIME_BASE,
  1650. s->streams[stream_index]->time_base.den,
  1651. flags & AVSEEK_FLAG_BACKWARD ?
  1652. AV_ROUND_DOWN : AV_ROUND_UP);
  1653. duration = s->duration == AV_NOPTS_VALUE ?
  1654. 0 : s->duration;
  1655. if (0 < duration && duration < seek_timestamp - first_timestamp)
  1656. return AVERROR(EIO);
  1657. /* find the playlist with the specified stream */
  1658. for (i = 0; i < c->n_playlists; i++) {
  1659. struct playlist *pls = c->playlists[i];
  1660. if (stream_index >= pls->stream_offset &&
  1661. stream_index - pls->stream_offset < pls->ctx->nb_streams) {
  1662. seek_pls = pls;
  1663. break;
  1664. }
  1665. }
  1666. /* check if the timestamp is valid for the playlist with the
  1667. * specified stream index */
  1668. if (!seek_pls || !find_timestamp_in_playlist(c, seek_pls, seek_timestamp, &seq_no))
  1669. return AVERROR(EIO);
  1670. /* set segment now so we do not need to search again below */
  1671. seek_pls->cur_seq_no = seq_no;
  1672. seek_pls->seek_stream_index = stream_index - seek_pls->stream_offset;
  1673. for (i = 0; i < c->n_playlists; i++) {
  1674. /* Reset reading */
  1675. struct playlist *pls = c->playlists[i];
  1676. if (pls->input)
  1677. ff_format_io_close(pls->parent, &pls->input);
  1678. av_packet_unref(&pls->pkt);
  1679. reset_packet(&pls->pkt);
  1680. pls->pb.eof_reached = 0;
  1681. /* Clear any buffered data */
  1682. pls->pb.buf_end = pls->pb.buf_ptr = pls->pb.buffer;
  1683. /* Reset the pos, to let the mpegts demuxer know we've seeked. */
  1684. pls->pb.pos = 0;
  1685. /* Flush the packet queue of the subdemuxer. */
  1686. ff_read_frame_flush(pls->ctx);
  1687. pls->seek_timestamp = seek_timestamp;
  1688. pls->seek_flags = flags;
  1689. if (pls != seek_pls) {
  1690. /* set closest segment seq_no for playlists not handled above */
  1691. find_timestamp_in_playlist(c, pls, seek_timestamp, &pls->cur_seq_no);
  1692. /* seek the playlist to the given position without taking
  1693. * keyframes into account since this playlist does not have the
  1694. * specified stream where we should look for the keyframes */
  1695. pls->seek_stream_index = -1;
  1696. pls->seek_flags |= AVSEEK_FLAG_ANY;
  1697. }
  1698. }
  1699. c->cur_timestamp = seek_timestamp;
  1700. return 0;
  1701. }
  1702. static int hls_probe(AVProbeData *p)
  1703. {
  1704. /* Require #EXTM3U at the start, and either one of the ones below
  1705. * somewhere for a proper match. */
  1706. if (strncmp(p->buf, "#EXTM3U", 7))
  1707. return 0;
  1708. if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
  1709. strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
  1710. strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
  1711. return AVPROBE_SCORE_MAX;
  1712. return 0;
  1713. }
  1714. #define OFFSET(x) offsetof(HLSContext, x)
  1715. #define FLAGS AV_OPT_FLAG_DECODING_PARAM
  1716. static const AVOption hls_options[] = {
  1717. {"live_start_index", "segment index to start live streams at (negative values are from the end)",
  1718. OFFSET(live_start_index), AV_OPT_TYPE_INT, {.i64 = -3}, INT_MIN, INT_MAX, FLAGS},
  1719. {NULL}
  1720. };
  1721. static const AVClass hls_class = {
  1722. .class_name = "hls,applehttp",
  1723. .item_name = av_default_item_name,
  1724. .option = hls_options,
  1725. .version = LIBAVUTIL_VERSION_INT,
  1726. };
  1727. AVInputFormat ff_hls_demuxer = {
  1728. .name = "hls,applehttp",
  1729. .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
  1730. .priv_class = &hls_class,
  1731. .priv_data_size = sizeof(HLSContext),
  1732. .read_probe = hls_probe,
  1733. .read_header = hls_read_header,
  1734. .read_packet = hls_read_packet,
  1735. .read_close = hls_close,
  1736. .read_seek = hls_read_seek,
  1737. };