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.

1837 lines
61KB

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