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.

1835 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. * *pls == NULL => Master Playlist or parentless Media Playlist
  430. * *pls != NULL => parented Media Playlist, playlist+variant allocated */
  431. static int ensure_playlist(HLSContext *c, struct playlist **pls, const char *url)
  432. {
  433. if (*pls)
  434. return 0;
  435. if (!new_variant(c, NULL, url, NULL))
  436. return AVERROR(ENOMEM);
  437. *pls = c->playlists[c->n_playlists - 1];
  438. return 0;
  439. }
  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. if ((ret = ffurl_connect(pls->input, &tmp)) < 0) {
  456. ffurl_close(pls->input);
  457. pls->input = NULL;
  458. }
  459. av_dict_free(&tmp);
  460. return ret;
  461. }
  462. static int open_url(HLSContext *c, URLContext **uc, const char *url, AVDictionary *opts)
  463. {
  464. AVDictionary *tmp = NULL;
  465. int ret;
  466. av_dict_copy(&tmp, c->avio_opts, 0);
  467. av_dict_copy(&tmp, opts, 0);
  468. ret = ffurl_open(uc, url, AVIO_FLAG_READ, c->interrupt_callback, &tmp);
  469. av_dict_free(&tmp);
  470. return ret;
  471. }
  472. static int parse_playlist(HLSContext *c, const char *url,
  473. struct playlist *pls, AVIOContext *in)
  474. {
  475. int ret = 0, is_segment = 0, is_variant = 0;
  476. int64_t duration = 0;
  477. enum KeyType key_type = KEY_NONE;
  478. uint8_t iv[16] = "";
  479. int has_iv = 0;
  480. char key[MAX_URL_SIZE] = "";
  481. char line[MAX_URL_SIZE];
  482. const char *ptr;
  483. int close_in = 0;
  484. int64_t seg_offset = 0;
  485. int64_t seg_size = -1;
  486. uint8_t *new_url = NULL;
  487. struct variant_info variant_info;
  488. char tmp_str[MAX_URL_SIZE];
  489. if (!in) {
  490. #if 1
  491. AVDictionary *opts = NULL;
  492. close_in = 1;
  493. /* Some HLS servers don't like being sent the range header */
  494. av_dict_set(&opts, "seekable", "0", 0);
  495. // broker prior HTTP options that should be consistent across requests
  496. av_dict_set(&opts, "user-agent", c->user_agent, 0);
  497. av_dict_set(&opts, "cookies", c->cookies, 0);
  498. av_dict_set(&opts, "headers", c->headers, 0);
  499. ret = avio_open2(&in, url, AVIO_FLAG_READ,
  500. c->interrupt_callback, &opts);
  501. av_dict_free(&opts);
  502. if (ret < 0)
  503. return ret;
  504. #else
  505. ret = open_in(c, &in, url);
  506. if (ret < 0)
  507. return ret;
  508. close_in = 1;
  509. #endif
  510. }
  511. if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)
  512. url = new_url;
  513. read_chomp_line(in, line, sizeof(line));
  514. if (strcmp(line, "#EXTM3U")) {
  515. ret = AVERROR_INVALIDDATA;
  516. goto fail;
  517. }
  518. if (pls) {
  519. free_segment_list(pls);
  520. pls->finished = 0;
  521. pls->type = PLS_TYPE_UNSPECIFIED;
  522. }
  523. while (!avio_feof(in)) {
  524. read_chomp_line(in, line, sizeof(line));
  525. if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
  526. is_variant = 1;
  527. memset(&variant_info, 0, sizeof(variant_info));
  528. ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
  529. &variant_info);
  530. } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
  531. struct key_info info = {{0}};
  532. ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,
  533. &info);
  534. key_type = KEY_NONE;
  535. has_iv = 0;
  536. if (!strcmp(info.method, "AES-128"))
  537. key_type = KEY_AES_128;
  538. if (!strcmp(info.method, "SAMPLE-AES"))
  539. key_type = KEY_SAMPLE_AES;
  540. if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
  541. ff_hex_to_data(iv, info.iv + 2);
  542. has_iv = 1;
  543. }
  544. av_strlcpy(key, info.uri, sizeof(key));
  545. } else if (av_strstart(line, "#EXT-X-MEDIA:", &ptr)) {
  546. struct rendition_info info = {{0}};
  547. ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_rendition_args,
  548. &info);
  549. new_rendition(c, &info, url);
  550. } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
  551. ret = ensure_playlist(c, &pls, url);
  552. if (ret < 0)
  553. goto fail;
  554. pls->target_duration = atoi(ptr) * AV_TIME_BASE;
  555. } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
  556. ret = ensure_playlist(c, &pls, url);
  557. if (ret < 0)
  558. goto fail;
  559. pls->start_seq_no = atoi(ptr);
  560. } else if (av_strstart(line, "#EXT-X-PLAYLIST-TYPE:", &ptr)) {
  561. ret = ensure_playlist(c, &pls, url);
  562. if (ret < 0)
  563. goto fail;
  564. if (!strcmp(ptr, "EVENT"))
  565. pls->type = PLS_TYPE_EVENT;
  566. else if (!strcmp(ptr, "VOD"))
  567. pls->type = PLS_TYPE_VOD;
  568. } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
  569. if (pls)
  570. pls->finished = 1;
  571. } else if (av_strstart(line, "#EXTINF:", &ptr)) {
  572. is_segment = 1;
  573. duration = atof(ptr) * AV_TIME_BASE;
  574. } else if (av_strstart(line, "#EXT-X-BYTERANGE:", &ptr)) {
  575. seg_size = atoi(ptr);
  576. ptr = strchr(ptr, '@');
  577. if (ptr)
  578. seg_offset = atoi(ptr+1);
  579. } else if (av_strstart(line, "#", NULL)) {
  580. continue;
  581. } else if (line[0]) {
  582. if (is_variant) {
  583. if (!new_variant(c, &variant_info, line, url)) {
  584. ret = AVERROR(ENOMEM);
  585. goto fail;
  586. }
  587. is_variant = 0;
  588. }
  589. if (is_segment) {
  590. struct segment *seg;
  591. if (!pls) {
  592. if (!new_variant(c, 0, url, NULL)) {
  593. ret = AVERROR(ENOMEM);
  594. goto fail;
  595. }
  596. pls = c->playlists[c->n_playlists - 1];
  597. }
  598. seg = av_malloc(sizeof(struct segment));
  599. if (!seg) {
  600. ret = AVERROR(ENOMEM);
  601. goto fail;
  602. }
  603. seg->duration = duration;
  604. seg->key_type = key_type;
  605. if (has_iv) {
  606. memcpy(seg->iv, iv, sizeof(iv));
  607. } else {
  608. int seq = pls->start_seq_no + pls->n_segments;
  609. memset(seg->iv, 0, sizeof(seg->iv));
  610. AV_WB32(seg->iv + 12, seq);
  611. }
  612. if (key_type != KEY_NONE) {
  613. ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key);
  614. seg->key = av_strdup(tmp_str);
  615. if (!seg->key) {
  616. av_free(seg);
  617. ret = AVERROR(ENOMEM);
  618. goto fail;
  619. }
  620. } else {
  621. seg->key = NULL;
  622. }
  623. ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line);
  624. seg->url = av_strdup(tmp_str);
  625. if (!seg->url) {
  626. av_free(seg->key);
  627. av_free(seg);
  628. ret = AVERROR(ENOMEM);
  629. goto fail;
  630. }
  631. dynarray_add(&pls->segments, &pls->n_segments, seg);
  632. is_segment = 0;
  633. seg->size = seg_size;
  634. if (seg_size >= 0) {
  635. seg->url_offset = seg_offset;
  636. seg_offset += seg_size;
  637. seg_size = -1;
  638. } else {
  639. seg->url_offset = 0;
  640. seg_offset = 0;
  641. }
  642. }
  643. }
  644. }
  645. if (pls)
  646. pls->last_load_time = av_gettime_relative();
  647. fail:
  648. av_free(new_url);
  649. if (close_in)
  650. avio_close(in);
  651. return ret;
  652. }
  653. enum ReadFromURLMode {
  654. READ_NORMAL,
  655. READ_COMPLETE,
  656. };
  657. /* read from URLContext, limiting read to current segment */
  658. static int read_from_url(struct playlist *pls, uint8_t *buf, int buf_size,
  659. enum ReadFromURLMode mode)
  660. {
  661. int ret;
  662. struct segment *seg = pls->segments[pls->cur_seq_no - pls->start_seq_no];
  663. /* limit read if the segment was only a part of a file */
  664. if (seg->size >= 0)
  665. buf_size = FFMIN(buf_size, seg->size - pls->cur_seg_offset);
  666. if (mode == READ_COMPLETE)
  667. ret = ffurl_read_complete(pls->input, buf, buf_size);
  668. else
  669. ret = ffurl_read(pls->input, buf, buf_size);
  670. if (ret > 0)
  671. pls->cur_seg_offset += ret;
  672. return ret;
  673. }
  674. /* Parse the raw ID3 data and pass contents to caller */
  675. static void parse_id3(AVFormatContext *s, AVIOContext *pb,
  676. AVDictionary **metadata, int64_t *dts,
  677. ID3v2ExtraMetaAPIC **apic, ID3v2ExtraMeta **extra_meta)
  678. {
  679. static const char id3_priv_owner_ts[] = "com.apple.streaming.transportStreamTimestamp";
  680. ID3v2ExtraMeta *meta;
  681. ff_id3v2_read_dict(pb, metadata, ID3v2_DEFAULT_MAGIC, extra_meta);
  682. for (meta = *extra_meta; meta; meta = meta->next) {
  683. if (!strcmp(meta->tag, "PRIV")) {
  684. ID3v2ExtraMetaPRIV *priv = meta->data;
  685. if (priv->datasize == 8 && !strcmp(priv->owner, id3_priv_owner_ts)) {
  686. /* 33-bit MPEG timestamp */
  687. int64_t ts = AV_RB64(priv->data);
  688. av_log(s, AV_LOG_DEBUG, "HLS ID3 audio timestamp %"PRId64"\n", ts);
  689. if ((ts & ~((1ULL << 33) - 1)) == 0)
  690. *dts = ts;
  691. else
  692. av_log(s, AV_LOG_ERROR, "Invalid HLS ID3 audio timestamp %"PRId64"\n", ts);
  693. }
  694. } else if (!strcmp(meta->tag, "APIC") && apic)
  695. *apic = meta->data;
  696. }
  697. }
  698. /* Check if the ID3 metadata contents have changed */
  699. static int id3_has_changed_values(struct playlist *pls, AVDictionary *metadata,
  700. ID3v2ExtraMetaAPIC *apic)
  701. {
  702. AVDictionaryEntry *entry = NULL;
  703. AVDictionaryEntry *oldentry;
  704. /* check that no keys have changed values */
  705. while ((entry = av_dict_get(metadata, "", entry, AV_DICT_IGNORE_SUFFIX))) {
  706. oldentry = av_dict_get(pls->id3_initial, entry->key, NULL, AV_DICT_MATCH_CASE);
  707. if (!oldentry || strcmp(oldentry->value, entry->value) != 0)
  708. return 1;
  709. }
  710. /* check if apic appeared */
  711. if (apic && (pls->ctx->nb_streams != 2 || !pls->ctx->streams[1]->attached_pic.data))
  712. return 1;
  713. if (apic) {
  714. int size = pls->ctx->streams[1]->attached_pic.size;
  715. if (size != apic->buf->size - AV_INPUT_BUFFER_PADDING_SIZE)
  716. return 1;
  717. if (memcmp(apic->buf->data, pls->ctx->streams[1]->attached_pic.data, size) != 0)
  718. return 1;
  719. }
  720. return 0;
  721. }
  722. /* Parse ID3 data and handle the found data */
  723. static void handle_id3(AVIOContext *pb, struct playlist *pls)
  724. {
  725. AVDictionary *metadata = NULL;
  726. ID3v2ExtraMetaAPIC *apic = NULL;
  727. ID3v2ExtraMeta *extra_meta = NULL;
  728. int64_t timestamp = AV_NOPTS_VALUE;
  729. parse_id3(pls->ctx, pb, &metadata, &timestamp, &apic, &extra_meta);
  730. if (timestamp != AV_NOPTS_VALUE) {
  731. pls->id3_mpegts_timestamp = timestamp;
  732. pls->id3_offset = 0;
  733. }
  734. if (!pls->id3_found) {
  735. /* initial ID3 tags */
  736. av_assert0(!pls->id3_deferred_extra);
  737. pls->id3_found = 1;
  738. /* get picture attachment and set text metadata */
  739. if (pls->ctx->nb_streams)
  740. ff_id3v2_parse_apic(pls->ctx, &extra_meta);
  741. else
  742. /* demuxer not yet opened, defer picture attachment */
  743. pls->id3_deferred_extra = extra_meta;
  744. av_dict_copy(&pls->ctx->metadata, metadata, 0);
  745. pls->id3_initial = metadata;
  746. } else {
  747. if (!pls->id3_changed && id3_has_changed_values(pls, metadata, apic)) {
  748. avpriv_report_missing_feature(pls->ctx, "Changing ID3 metadata in HLS audio elementary stream");
  749. pls->id3_changed = 1;
  750. }
  751. av_dict_free(&metadata);
  752. }
  753. if (!pls->id3_deferred_extra)
  754. ff_id3v2_free_extra_meta(&extra_meta);
  755. }
  756. /* Intercept and handle ID3 tags between URLContext and AVIOContext */
  757. static void intercept_id3(struct playlist *pls, uint8_t *buf,
  758. int buf_size, int *len)
  759. {
  760. /* intercept id3 tags, we do not want to pass them to the raw
  761. * demuxer on all segment switches */
  762. int bytes;
  763. int id3_buf_pos = 0;
  764. int fill_buf = 0;
  765. /* gather all the id3 tags */
  766. while (1) {
  767. /* see if we can retrieve enough data for ID3 header */
  768. if (*len < ID3v2_HEADER_SIZE && buf_size >= ID3v2_HEADER_SIZE) {
  769. bytes = read_from_url(pls, buf + *len, ID3v2_HEADER_SIZE - *len, READ_COMPLETE);
  770. if (bytes > 0) {
  771. if (bytes == ID3v2_HEADER_SIZE - *len)
  772. /* no EOF yet, so fill the caller buffer again after
  773. * we have stripped the ID3 tags */
  774. fill_buf = 1;
  775. *len += bytes;
  776. } else if (*len <= 0) {
  777. /* error/EOF */
  778. *len = bytes;
  779. fill_buf = 0;
  780. }
  781. }
  782. if (*len < ID3v2_HEADER_SIZE)
  783. break;
  784. if (ff_id3v2_match(buf, ID3v2_DEFAULT_MAGIC)) {
  785. struct segment *seg = pls->segments[pls->cur_seq_no - pls->start_seq_no];
  786. int64_t maxsize = seg->size >= 0 ? seg->size : 1024*1024;
  787. int taglen = ff_id3v2_tag_len(buf);
  788. int tag_got_bytes = FFMIN(taglen, *len);
  789. int remaining = taglen - tag_got_bytes;
  790. if (taglen > maxsize) {
  791. av_log(pls->ctx, AV_LOG_ERROR, "Too large HLS ID3 tag (%d > %"PRId64" bytes)\n",
  792. taglen, maxsize);
  793. break;
  794. }
  795. /*
  796. * Copy the id3 tag to our temporary id3 buffer.
  797. * We could read a small id3 tag directly without memcpy, but
  798. * we would still need to copy the large tags, and handling
  799. * both of those cases together with the possibility for multiple
  800. * tags would make the handling a bit complex.
  801. */
  802. pls->id3_buf = av_fast_realloc(pls->id3_buf, &pls->id3_buf_size, id3_buf_pos + taglen);
  803. if (!pls->id3_buf)
  804. break;
  805. memcpy(pls->id3_buf + id3_buf_pos, buf, tag_got_bytes);
  806. id3_buf_pos += tag_got_bytes;
  807. /* strip the intercepted bytes */
  808. *len -= tag_got_bytes;
  809. memmove(buf, buf + tag_got_bytes, *len);
  810. av_log(pls->ctx, AV_LOG_DEBUG, "Stripped %d HLS ID3 bytes\n", tag_got_bytes);
  811. if (remaining > 0) {
  812. /* read the rest of the tag in */
  813. if (read_from_url(pls, pls->id3_buf + id3_buf_pos, remaining, READ_COMPLETE) != remaining)
  814. break;
  815. id3_buf_pos += remaining;
  816. av_log(pls->ctx, AV_LOG_DEBUG, "Stripped additional %d HLS ID3 bytes\n", remaining);
  817. }
  818. } else {
  819. /* no more ID3 tags */
  820. break;
  821. }
  822. }
  823. /* re-fill buffer for the caller unless EOF */
  824. if (*len >= 0 && (fill_buf || *len == 0)) {
  825. bytes = read_from_url(pls, buf + *len, buf_size - *len, READ_NORMAL);
  826. /* ignore error if we already had some data */
  827. if (bytes >= 0)
  828. *len += bytes;
  829. else if (*len == 0)
  830. *len = bytes;
  831. }
  832. if (pls->id3_buf) {
  833. /* Now parse all the ID3 tags */
  834. AVIOContext id3ioctx;
  835. ffio_init_context(&id3ioctx, pls->id3_buf, id3_buf_pos, 0, NULL, NULL, NULL, NULL);
  836. handle_id3(&id3ioctx, pls);
  837. }
  838. if (pls->is_id3_timestamped == -1)
  839. pls->is_id3_timestamped = (pls->id3_mpegts_timestamp != AV_NOPTS_VALUE);
  840. }
  841. static void update_options(char **dest, const char *name, void *src)
  842. {
  843. av_freep(dest);
  844. av_opt_get(src, name, 0, (uint8_t**)dest);
  845. if (*dest && !strlen(*dest))
  846. av_freep(dest);
  847. }
  848. static int open_input(HLSContext *c, struct playlist *pls)
  849. {
  850. AVDictionary *opts = NULL;
  851. AVDictionary *opts2 = NULL;
  852. int ret;
  853. struct segment *seg = pls->segments[pls->cur_seq_no - pls->start_seq_no];
  854. // broker prior HTTP options that should be consistent across requests
  855. av_dict_set(&opts, "user-agent", c->user_agent, 0);
  856. av_dict_set(&opts, "cookies", c->cookies, 0);
  857. av_dict_set(&opts, "headers", c->headers, 0);
  858. av_dict_set(&opts, "seekable", "0", 0);
  859. // Same opts for key request (ffurl_open mutilates the opts so it cannot be used twice)
  860. av_dict_copy(&opts2, opts, 0);
  861. if (seg->size >= 0) {
  862. /* try to restrict the HTTP request to the part we want
  863. * (if this is in fact a HTTP request) */
  864. av_dict_set_int(&opts, "offset", seg->url_offset, 0);
  865. av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
  866. }
  867. av_log(pls->parent, AV_LOG_VERBOSE, "HLS request for url '%s', offset %"PRId64", playlist %d\n",
  868. seg->url, seg->url_offset, pls->index);
  869. if (seg->key_type == KEY_NONE) {
  870. ret = open_url(pls->parent->priv_data, &pls->input, seg->url, opts);
  871. } else if (seg->key_type == KEY_AES_128) {
  872. // HLSContext *c = var->parent->priv_data;
  873. char iv[33], key[33], url[MAX_URL_SIZE];
  874. if (strcmp(seg->key, pls->key_url)) {
  875. URLContext *uc;
  876. if (open_url(pls->parent->priv_data, &uc, seg->key, opts2) == 0) {
  877. if (ffurl_read_complete(uc, pls->key, sizeof(pls->key))
  878. != sizeof(pls->key)) {
  879. av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
  880. seg->key);
  881. }
  882. update_options(&c->cookies, "cookies", uc->priv_data);
  883. av_dict_set(&opts, "cookies", c->cookies, 0);
  884. ffurl_close(uc);
  885. } else {
  886. av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
  887. seg->key);
  888. }
  889. av_strlcpy(pls->key_url, seg->key, sizeof(pls->key_url));
  890. }
  891. ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
  892. ff_data_to_hex(key, pls->key, sizeof(pls->key), 0);
  893. iv[32] = key[32] = '\0';
  894. if (strstr(seg->url, "://"))
  895. snprintf(url, sizeof(url), "crypto+%s", seg->url);
  896. else
  897. snprintf(url, sizeof(url), "crypto:%s", seg->url);
  898. if ((ret = ffurl_alloc(&pls->input, url, AVIO_FLAG_READ,
  899. &pls->parent->interrupt_callback)) < 0)
  900. goto cleanup;
  901. av_opt_set(pls->input->priv_data, "key", key, 0);
  902. av_opt_set(pls->input->priv_data, "iv", iv, 0);
  903. if ((ret = url_connect(pls, c->avio_opts, opts)) < 0) {
  904. goto cleanup;
  905. }
  906. ret = 0;
  907. } else if (seg->key_type == KEY_SAMPLE_AES) {
  908. av_log(pls->parent, AV_LOG_ERROR,
  909. "SAMPLE-AES encryption is not supported yet\n");
  910. ret = AVERROR_PATCHWELCOME;
  911. }
  912. else
  913. ret = AVERROR(ENOSYS);
  914. /* Seek to the requested position. If this was a HTTP request, the offset
  915. * should already be where want it to, but this allows e.g. local testing
  916. * without a HTTP server. */
  917. if (ret == 0 && seg->key_type == KEY_NONE && seg->url_offset) {
  918. int seekret = ffurl_seek(pls->input, seg->url_offset, SEEK_SET);
  919. if (seekret < 0) {
  920. av_log(pls->parent, AV_LOG_ERROR, "Unable to seek to offset %"PRId64" of HLS segment '%s'\n", seg->url_offset, seg->url);
  921. ret = seekret;
  922. ffurl_close(pls->input);
  923. pls->input = NULL;
  924. }
  925. }
  926. cleanup:
  927. av_dict_free(&opts);
  928. av_dict_free(&opts2);
  929. pls->cur_seg_offset = 0;
  930. return ret;
  931. }
  932. static int64_t default_reload_interval(struct playlist *pls)
  933. {
  934. return pls->n_segments > 0 ?
  935. pls->segments[pls->n_segments - 1]->duration :
  936. pls->target_duration;
  937. }
  938. static int read_data(void *opaque, uint8_t *buf, int buf_size)
  939. {
  940. struct playlist *v = opaque;
  941. HLSContext *c = v->parent->priv_data;
  942. int ret, i;
  943. int just_opened = 0;
  944. restart:
  945. if (!v->needed)
  946. return AVERROR_EOF;
  947. if (!v->input) {
  948. int64_t reload_interval;
  949. /* Check that the playlist is still needed before opening a new
  950. * segment. */
  951. if (v->ctx && v->ctx->nb_streams &&
  952. v->parent->nb_streams >= v->stream_offset + v->ctx->nb_streams) {
  953. v->needed = 0;
  954. for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;
  955. i++) {
  956. if (v->parent->streams[i]->discard < AVDISCARD_ALL)
  957. v->needed = 1;
  958. }
  959. }
  960. if (!v->needed) {
  961. av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
  962. v->index);
  963. return AVERROR_EOF;
  964. }
  965. /* If this is a live stream and the reload interval has elapsed since
  966. * the last playlist reload, reload the playlists now. */
  967. reload_interval = default_reload_interval(v);
  968. reload:
  969. if (!v->finished &&
  970. av_gettime_relative() - v->last_load_time >= reload_interval) {
  971. if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {
  972. av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",
  973. v->index);
  974. return ret;
  975. }
  976. /* If we need to reload the playlist again below (if
  977. * there's still no more segments), switch to a reload
  978. * interval of half the target duration. */
  979. reload_interval = v->target_duration / 2;
  980. }
  981. if (v->cur_seq_no < v->start_seq_no) {
  982. av_log(NULL, AV_LOG_WARNING,
  983. "skipping %d segments ahead, expired from playlists\n",
  984. v->start_seq_no - v->cur_seq_no);
  985. v->cur_seq_no = v->start_seq_no;
  986. }
  987. if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
  988. if (v->finished)
  989. return AVERROR_EOF;
  990. while (av_gettime_relative() - v->last_load_time < reload_interval) {
  991. if (ff_check_interrupt(c->interrupt_callback))
  992. return AVERROR_EXIT;
  993. av_usleep(100*1000);
  994. }
  995. /* Enough time has elapsed since the last reload */
  996. goto reload;
  997. }
  998. ret = open_input(c, v);
  999. if (ret < 0) {
  1000. if (ff_check_interrupt(c->interrupt_callback))
  1001. return AVERROR_EXIT;
  1002. av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n",
  1003. v->index);
  1004. v->cur_seq_no += 1;
  1005. goto reload;
  1006. }
  1007. just_opened = 1;
  1008. }
  1009. ret = read_from_url(v, buf, buf_size, READ_NORMAL);
  1010. if (ret > 0) {
  1011. if (just_opened && v->is_id3_timestamped != 0) {
  1012. /* Intercept ID3 tags here, elementary audio streams are required
  1013. * to convey timestamps using them in the beginning of each segment. */
  1014. intercept_id3(v, buf, buf_size, &ret);
  1015. }
  1016. return ret;
  1017. }
  1018. ffurl_close(v->input);
  1019. v->input = NULL;
  1020. v->cur_seq_no++;
  1021. c->cur_seq_no = v->cur_seq_no;
  1022. goto restart;
  1023. }
  1024. static int playlist_in_multiple_variants(HLSContext *c, struct playlist *pls)
  1025. {
  1026. int variant_count = 0;
  1027. int i, j;
  1028. for (i = 0; i < c->n_variants && variant_count < 2; i++) {
  1029. struct variant *v = c->variants[i];
  1030. for (j = 0; j < v->n_playlists; j++) {
  1031. if (v->playlists[j] == pls) {
  1032. variant_count++;
  1033. break;
  1034. }
  1035. }
  1036. }
  1037. return variant_count >= 2;
  1038. }
  1039. static void add_renditions_to_variant(HLSContext *c, struct variant *var,
  1040. enum AVMediaType type, const char *group_id)
  1041. {
  1042. int i;
  1043. for (i = 0; i < c->n_renditions; i++) {
  1044. struct rendition *rend = c->renditions[i];
  1045. if (rend->type == type && !strcmp(rend->group_id, group_id)) {
  1046. if (rend->playlist)
  1047. /* rendition is an external playlist
  1048. * => add the playlist to the variant */
  1049. dynarray_add(&var->playlists, &var->n_playlists, rend->playlist);
  1050. else
  1051. /* rendition is part of the variant main Media Playlist
  1052. * => add the rendition to the main Media Playlist */
  1053. dynarray_add(&var->playlists[0]->renditions,
  1054. &var->playlists[0]->n_renditions,
  1055. rend);
  1056. }
  1057. }
  1058. }
  1059. static void add_metadata_from_renditions(AVFormatContext *s, struct playlist *pls,
  1060. enum AVMediaType type)
  1061. {
  1062. int rend_idx = 0;
  1063. int i;
  1064. for (i = 0; i < pls->ctx->nb_streams; i++) {
  1065. AVStream *st = s->streams[pls->stream_offset + i];
  1066. if (st->codec->codec_type != type)
  1067. continue;
  1068. for (; rend_idx < pls->n_renditions; rend_idx++) {
  1069. struct rendition *rend = pls->renditions[rend_idx];
  1070. if (rend->type != type)
  1071. continue;
  1072. if (rend->language[0])
  1073. av_dict_set(&st->metadata, "language", rend->language, 0);
  1074. if (rend->name[0])
  1075. av_dict_set(&st->metadata, "comment", rend->name, 0);
  1076. st->disposition |= rend->disposition;
  1077. }
  1078. if (rend_idx >=pls->n_renditions)
  1079. break;
  1080. }
  1081. }
  1082. /* if timestamp was in valid range: returns 1 and sets seq_no
  1083. * if not: returns 0 and sets seq_no to closest segment */
  1084. static int find_timestamp_in_playlist(HLSContext *c, struct playlist *pls,
  1085. int64_t timestamp, int *seq_no)
  1086. {
  1087. int i;
  1088. int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
  1089. 0 : c->first_timestamp;
  1090. if (timestamp < pos) {
  1091. *seq_no = pls->start_seq_no;
  1092. return 0;
  1093. }
  1094. for (i = 0; i < pls->n_segments; i++) {
  1095. int64_t diff = pos + pls->segments[i]->duration - timestamp;
  1096. if (diff > 0) {
  1097. *seq_no = pls->start_seq_no + i;
  1098. return 1;
  1099. }
  1100. pos += pls->segments[i]->duration;
  1101. }
  1102. *seq_no = pls->start_seq_no + pls->n_segments - 1;
  1103. return 0;
  1104. }
  1105. static int select_cur_seq_no(HLSContext *c, struct playlist *pls)
  1106. {
  1107. int seq_no;
  1108. if (!pls->finished && !c->first_packet &&
  1109. av_gettime_relative() - pls->last_load_time >= default_reload_interval(pls))
  1110. /* reload the playlist since it was suspended */
  1111. parse_playlist(c, pls->url, pls, NULL);
  1112. /* If playback is already in progress (we are just selecting a new
  1113. * playlist) and this is a complete file, find the matching segment
  1114. * by counting durations. */
  1115. if (pls->finished && c->cur_timestamp != AV_NOPTS_VALUE) {
  1116. find_timestamp_in_playlist(c, pls, c->cur_timestamp, &seq_no);
  1117. return seq_no;
  1118. }
  1119. if (!pls->finished) {
  1120. if (!c->first_packet && /* we are doing a segment selection during playback */
  1121. c->cur_seq_no >= pls->start_seq_no &&
  1122. c->cur_seq_no < pls->start_seq_no + pls->n_segments)
  1123. /* While spec 3.4.3 says that we cannot assume anything about the
  1124. * content at the same sequence number on different playlists,
  1125. * in practice this seems to work and doing it otherwise would
  1126. * require us to download a segment to inspect its timestamps. */
  1127. return c->cur_seq_no;
  1128. /* If this is a live stream, start live_start_index segments from the
  1129. * start or end */
  1130. if (c->live_start_index < 0)
  1131. return pls->start_seq_no + FFMAX(pls->n_segments + c->live_start_index, 0);
  1132. else
  1133. return pls->start_seq_no + FFMIN(c->live_start_index, pls->n_segments - 1);
  1134. }
  1135. /* Otherwise just start on the first segment. */
  1136. return pls->start_seq_no;
  1137. }
  1138. static int save_avio_options(AVFormatContext *s)
  1139. {
  1140. HLSContext *c = s->priv_data;
  1141. const char *opts[] = { "headers", "user_agent", "user-agent", "cookies", NULL }, **opt = opts;
  1142. uint8_t *buf;
  1143. int ret = 0;
  1144. while (*opt) {
  1145. if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN, &buf) >= 0) {
  1146. ret = av_dict_set(&c->avio_opts, *opt, buf,
  1147. AV_DICT_DONT_STRDUP_VAL);
  1148. if (ret < 0)
  1149. return ret;
  1150. }
  1151. opt++;
  1152. }
  1153. return ret;
  1154. }
  1155. static int hls_read_header(AVFormatContext *s)
  1156. {
  1157. URLContext *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb->opaque;
  1158. HLSContext *c = s->priv_data;
  1159. int ret = 0, i, j, stream_offset = 0;
  1160. c->interrupt_callback = &s->interrupt_callback;
  1161. c->first_packet = 1;
  1162. c->first_timestamp = AV_NOPTS_VALUE;
  1163. c->cur_timestamp = AV_NOPTS_VALUE;
  1164. // if the URL context is good, read important options we must broker later
  1165. if (u && u->prot->priv_data_class) {
  1166. // get the previous user agent & set back to null if string size is zero
  1167. update_options(&c->user_agent, "user-agent", u->priv_data);
  1168. // get the previous cookies & set back to null if string size is zero
  1169. update_options(&c->cookies, "cookies", u->priv_data);
  1170. // get the previous headers & set back to null if string size is zero
  1171. update_options(&c->headers, "headers", u->priv_data);
  1172. }
  1173. if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
  1174. goto fail;
  1175. if ((ret = save_avio_options(s)) < 0)
  1176. goto fail;
  1177. /* Some HLS servers don't like being sent the range header */
  1178. av_dict_set(&c->avio_opts, "seekable", "0", 0);
  1179. if (c->n_variants == 0) {
  1180. av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
  1181. ret = AVERROR_EOF;
  1182. goto fail;
  1183. }
  1184. /* If the playlist only contained playlists (Master Playlist),
  1185. * parse each individual playlist. */
  1186. if (c->n_playlists > 1 || c->playlists[0]->n_segments == 0) {
  1187. for (i = 0; i < c->n_playlists; i++) {
  1188. struct playlist *pls = c->playlists[i];
  1189. if ((ret = parse_playlist(c, pls->url, pls, NULL)) < 0)
  1190. goto fail;
  1191. }
  1192. }
  1193. if (c->variants[0]->playlists[0]->n_segments == 0) {
  1194. av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
  1195. ret = AVERROR_EOF;
  1196. goto fail;
  1197. }
  1198. /* If this isn't a live stream, calculate the total duration of the
  1199. * stream. */
  1200. if (c->variants[0]->playlists[0]->finished) {
  1201. int64_t duration = 0;
  1202. for (i = 0; i < c->variants[0]->playlists[0]->n_segments; i++)
  1203. duration += c->variants[0]->playlists[0]->segments[i]->duration;
  1204. s->duration = duration;
  1205. }
  1206. /* Associate renditions with variants */
  1207. for (i = 0; i < c->n_variants; i++) {
  1208. struct variant *var = c->variants[i];
  1209. if (var->audio_group[0])
  1210. add_renditions_to_variant(c, var, AVMEDIA_TYPE_AUDIO, var->audio_group);
  1211. if (var->video_group[0])
  1212. add_renditions_to_variant(c, var, AVMEDIA_TYPE_VIDEO, var->video_group);
  1213. if (var->subtitles_group[0])
  1214. add_renditions_to_variant(c, var, AVMEDIA_TYPE_SUBTITLE, var->subtitles_group);
  1215. }
  1216. /* Open the demuxer for each playlist */
  1217. for (i = 0; i < c->n_playlists; i++) {
  1218. struct playlist *pls = c->playlists[i];
  1219. AVInputFormat *in_fmt = NULL;
  1220. if (!(pls->ctx = avformat_alloc_context())) {
  1221. ret = AVERROR(ENOMEM);
  1222. goto fail;
  1223. }
  1224. if (pls->n_segments == 0)
  1225. continue;
  1226. pls->index = i;
  1227. pls->needed = 1;
  1228. pls->parent = s;
  1229. pls->cur_seq_no = select_cur_seq_no(c, pls);
  1230. pls->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
  1231. if (!pls->read_buffer){
  1232. ret = AVERROR(ENOMEM);
  1233. avformat_free_context(pls->ctx);
  1234. pls->ctx = NULL;
  1235. goto fail;
  1236. }
  1237. ffio_init_context(&pls->pb, pls->read_buffer, INITIAL_BUFFER_SIZE, 0, pls,
  1238. read_data, NULL, NULL);
  1239. pls->pb.seekable = 0;
  1240. ret = av_probe_input_buffer(&pls->pb, &in_fmt, pls->segments[0]->url,
  1241. NULL, 0, 0);
  1242. if (ret < 0) {
  1243. /* Free the ctx - it isn't initialized properly at this point,
  1244. * so avformat_close_input shouldn't be called. If
  1245. * avformat_open_input fails below, it frees and zeros the
  1246. * context, so it doesn't need any special treatment like this. */
  1247. av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", pls->segments[0]->url);
  1248. avformat_free_context(pls->ctx);
  1249. pls->ctx = NULL;
  1250. goto fail;
  1251. }
  1252. pls->ctx->pb = &pls->pb;
  1253. pls->stream_offset = stream_offset;
  1254. if ((ret = ff_copy_whitelists(pls->ctx, s)) < 0)
  1255. goto fail;
  1256. ret = avformat_open_input(&pls->ctx, pls->segments[0]->url, in_fmt, NULL);
  1257. if (ret < 0)
  1258. goto fail;
  1259. if (pls->id3_deferred_extra && pls->ctx->nb_streams == 1) {
  1260. ff_id3v2_parse_apic(pls->ctx, &pls->id3_deferred_extra);
  1261. avformat_queue_attached_pictures(pls->ctx);
  1262. ff_id3v2_free_extra_meta(&pls->id3_deferred_extra);
  1263. pls->id3_deferred_extra = NULL;
  1264. }
  1265. pls->ctx->ctx_flags &= ~AVFMTCTX_NOHEADER;
  1266. ret = avformat_find_stream_info(pls->ctx, NULL);
  1267. if (ret < 0)
  1268. goto fail;
  1269. if (pls->is_id3_timestamped == -1)
  1270. av_log(s, AV_LOG_WARNING, "No expected HTTP requests have been made\n");
  1271. /* Create new AVStreams for each stream in this playlist */
  1272. for (j = 0; j < pls->ctx->nb_streams; j++) {
  1273. AVStream *st = avformat_new_stream(s, NULL);
  1274. AVStream *ist = pls->ctx->streams[j];
  1275. if (!st) {
  1276. ret = AVERROR(ENOMEM);
  1277. goto fail;
  1278. }
  1279. st->id = i;
  1280. avcodec_copy_context(st->codec, pls->ctx->streams[j]->codec);
  1281. if (pls->is_id3_timestamped) /* custom timestamps via id3 */
  1282. avpriv_set_pts_info(st, 33, 1, MPEG_TIME_BASE);
  1283. else
  1284. avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
  1285. }
  1286. add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_AUDIO);
  1287. add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_VIDEO);
  1288. add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_SUBTITLE);
  1289. stream_offset += pls->ctx->nb_streams;
  1290. }
  1291. /* Create a program for each variant */
  1292. for (i = 0; i < c->n_variants; i++) {
  1293. struct variant *v = c->variants[i];
  1294. AVProgram *program;
  1295. program = av_new_program(s, i);
  1296. if (!program)
  1297. goto fail;
  1298. av_dict_set_int(&program->metadata, "variant_bitrate", v->bandwidth, 0);
  1299. for (j = 0; j < v->n_playlists; j++) {
  1300. struct playlist *pls = v->playlists[j];
  1301. int is_shared = playlist_in_multiple_variants(c, pls);
  1302. int k;
  1303. for (k = 0; k < pls->ctx->nb_streams; k++) {
  1304. struct AVStream *st = s->streams[pls->stream_offset + k];
  1305. ff_program_add_stream_index(s, i, pls->stream_offset + k);
  1306. /* Set variant_bitrate for streams unique to this variant */
  1307. if (!is_shared && v->bandwidth)
  1308. av_dict_set_int(&st->metadata, "variant_bitrate", v->bandwidth, 0);
  1309. }
  1310. }
  1311. }
  1312. return 0;
  1313. fail:
  1314. free_playlist_list(c);
  1315. free_variant_list(c);
  1316. free_rendition_list(c);
  1317. return ret;
  1318. }
  1319. static int recheck_discard_flags(AVFormatContext *s, int first)
  1320. {
  1321. HLSContext *c = s->priv_data;
  1322. int i, changed = 0;
  1323. /* Check if any new streams are needed */
  1324. for (i = 0; i < c->n_playlists; i++)
  1325. c->playlists[i]->cur_needed = 0;
  1326. for (i = 0; i < s->nb_streams; i++) {
  1327. AVStream *st = s->streams[i];
  1328. struct playlist *pls = c->playlists[s->streams[i]->id];
  1329. if (st->discard < AVDISCARD_ALL)
  1330. pls->cur_needed = 1;
  1331. }
  1332. for (i = 0; i < c->n_playlists; i++) {
  1333. struct playlist *pls = c->playlists[i];
  1334. if (pls->cur_needed && !pls->needed) {
  1335. pls->needed = 1;
  1336. changed = 1;
  1337. pls->cur_seq_no = select_cur_seq_no(c, pls);
  1338. pls->pb.eof_reached = 0;
  1339. if (c->cur_timestamp != AV_NOPTS_VALUE) {
  1340. /* catch up */
  1341. pls->seek_timestamp = c->cur_timestamp;
  1342. pls->seek_flags = AVSEEK_FLAG_ANY;
  1343. pls->seek_stream_index = -1;
  1344. }
  1345. av_log(s, AV_LOG_INFO, "Now receiving playlist %d, segment %d\n", i, pls->cur_seq_no);
  1346. } else if (first && !pls->cur_needed && pls->needed) {
  1347. if (pls->input)
  1348. ffurl_close(pls->input);
  1349. pls->input = NULL;
  1350. pls->needed = 0;
  1351. changed = 1;
  1352. av_log(s, AV_LOG_INFO, "No longer receiving playlist %d\n", i);
  1353. }
  1354. }
  1355. return changed;
  1356. }
  1357. static void fill_timing_for_id3_timestamped_stream(struct playlist *pls)
  1358. {
  1359. if (pls->id3_offset >= 0) {
  1360. pls->pkt.dts = pls->id3_mpegts_timestamp +
  1361. av_rescale_q(pls->id3_offset,
  1362. pls->ctx->streams[pls->pkt.stream_index]->time_base,
  1363. MPEG_TIME_BASE_Q);
  1364. if (pls->pkt.duration)
  1365. pls->id3_offset += pls->pkt.duration;
  1366. else
  1367. pls->id3_offset = -1;
  1368. } else {
  1369. /* there have been packets with unknown duration
  1370. * since the last id3 tag, should not normally happen */
  1371. pls->pkt.dts = AV_NOPTS_VALUE;
  1372. }
  1373. if (pls->pkt.duration)
  1374. pls->pkt.duration = av_rescale_q(pls->pkt.duration,
  1375. pls->ctx->streams[pls->pkt.stream_index]->time_base,
  1376. MPEG_TIME_BASE_Q);
  1377. pls->pkt.pts = AV_NOPTS_VALUE;
  1378. }
  1379. static AVRational get_timebase(struct playlist *pls)
  1380. {
  1381. if (pls->is_id3_timestamped)
  1382. return MPEG_TIME_BASE_Q;
  1383. return pls->ctx->streams[pls->pkt.stream_index]->time_base;
  1384. }
  1385. static int compare_ts_with_wrapdetect(int64_t ts_a, struct playlist *pls_a,
  1386. int64_t ts_b, struct playlist *pls_b)
  1387. {
  1388. int64_t scaled_ts_a = av_rescale_q(ts_a, get_timebase(pls_a), MPEG_TIME_BASE_Q);
  1389. int64_t scaled_ts_b = av_rescale_q(ts_b, get_timebase(pls_b), MPEG_TIME_BASE_Q);
  1390. return av_compare_mod(scaled_ts_a, scaled_ts_b, 1LL << 33);
  1391. }
  1392. static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
  1393. {
  1394. HLSContext *c = s->priv_data;
  1395. int ret, i, minplaylist = -1;
  1396. recheck_discard_flags(s, c->first_packet);
  1397. for (i = 0; i < c->n_playlists; i++) {
  1398. struct playlist *pls = c->playlists[i];
  1399. /* Make sure we've got one buffered packet from each open playlist
  1400. * stream */
  1401. if (pls->needed && !pls->pkt.data) {
  1402. while (1) {
  1403. int64_t ts_diff;
  1404. AVRational tb;
  1405. ret = av_read_frame(pls->ctx, &pls->pkt);
  1406. if (ret < 0) {
  1407. if (!avio_feof(&pls->pb) && ret != AVERROR_EOF)
  1408. return ret;
  1409. reset_packet(&pls->pkt);
  1410. break;
  1411. } else {
  1412. /* stream_index check prevents matching picture attachments etc. */
  1413. if (pls->is_id3_timestamped && pls->pkt.stream_index == 0) {
  1414. /* audio elementary streams are id3 timestamped */
  1415. fill_timing_for_id3_timestamped_stream(pls);
  1416. }
  1417. if (c->first_timestamp == AV_NOPTS_VALUE &&
  1418. pls->pkt.dts != AV_NOPTS_VALUE)
  1419. c->first_timestamp = av_rescale_q(pls->pkt.dts,
  1420. get_timebase(pls), AV_TIME_BASE_Q);
  1421. }
  1422. if (pls->seek_timestamp == AV_NOPTS_VALUE)
  1423. break;
  1424. if (pls->seek_stream_index < 0 ||
  1425. pls->seek_stream_index == pls->pkt.stream_index) {
  1426. if (pls->pkt.dts == AV_NOPTS_VALUE) {
  1427. pls->seek_timestamp = AV_NOPTS_VALUE;
  1428. break;
  1429. }
  1430. tb = get_timebase(pls);
  1431. ts_diff = av_rescale_rnd(pls->pkt.dts, AV_TIME_BASE,
  1432. tb.den, AV_ROUND_DOWN) -
  1433. pls->seek_timestamp;
  1434. if (ts_diff >= 0 && (pls->seek_flags & AVSEEK_FLAG_ANY ||
  1435. pls->pkt.flags & AV_PKT_FLAG_KEY)) {
  1436. pls->seek_timestamp = AV_NOPTS_VALUE;
  1437. break;
  1438. }
  1439. }
  1440. av_free_packet(&pls->pkt);
  1441. reset_packet(&pls->pkt);
  1442. }
  1443. }
  1444. /* Check if this stream has the packet with the lowest dts */
  1445. if (pls->pkt.data) {
  1446. struct playlist *minpls = minplaylist < 0 ?
  1447. NULL : c->playlists[minplaylist];
  1448. if (minplaylist < 0) {
  1449. minplaylist = i;
  1450. } else {
  1451. int64_t dts = pls->pkt.dts;
  1452. int64_t mindts = minpls->pkt.dts;
  1453. if (dts == AV_NOPTS_VALUE ||
  1454. (mindts != AV_NOPTS_VALUE && compare_ts_with_wrapdetect(dts, pls, mindts, minpls) < 0))
  1455. minplaylist = i;
  1456. }
  1457. }
  1458. }
  1459. /* If we got a packet, return it */
  1460. if (minplaylist >= 0) {
  1461. struct playlist *pls = c->playlists[minplaylist];
  1462. *pkt = pls->pkt;
  1463. pkt->stream_index += pls->stream_offset;
  1464. reset_packet(&c->playlists[minplaylist]->pkt);
  1465. if (pkt->dts != AV_NOPTS_VALUE)
  1466. c->cur_timestamp = av_rescale_q(pkt->dts,
  1467. pls->ctx->streams[pls->pkt.stream_index]->time_base,
  1468. AV_TIME_BASE_Q);
  1469. return 0;
  1470. }
  1471. return AVERROR_EOF;
  1472. }
  1473. static int hls_close(AVFormatContext *s)
  1474. {
  1475. HLSContext *c = s->priv_data;
  1476. free_playlist_list(c);
  1477. free_variant_list(c);
  1478. free_rendition_list(c);
  1479. av_dict_free(&c->avio_opts);
  1480. return 0;
  1481. }
  1482. static int hls_read_seek(AVFormatContext *s, int stream_index,
  1483. int64_t timestamp, int flags)
  1484. {
  1485. HLSContext *c = s->priv_data;
  1486. struct playlist *seek_pls = NULL;
  1487. int i, seq_no;
  1488. int64_t first_timestamp, seek_timestamp, duration;
  1489. if ((flags & AVSEEK_FLAG_BYTE) ||
  1490. !(c->variants[0]->playlists[0]->finished || c->variants[0]->playlists[0]->type == PLS_TYPE_EVENT))
  1491. return AVERROR(ENOSYS);
  1492. first_timestamp = c->first_timestamp == AV_NOPTS_VALUE ?
  1493. 0 : c->first_timestamp;
  1494. seek_timestamp = av_rescale_rnd(timestamp, AV_TIME_BASE,
  1495. s->streams[stream_index]->time_base.den,
  1496. flags & AVSEEK_FLAG_BACKWARD ?
  1497. AV_ROUND_DOWN : AV_ROUND_UP);
  1498. duration = s->duration == AV_NOPTS_VALUE ?
  1499. 0 : s->duration;
  1500. if (0 < duration && duration < seek_timestamp - first_timestamp)
  1501. return AVERROR(EIO);
  1502. /* find the playlist with the specified stream */
  1503. for (i = 0; i < c->n_playlists; i++) {
  1504. struct playlist *pls = c->playlists[i];
  1505. if (stream_index >= pls->stream_offset &&
  1506. stream_index - pls->stream_offset < pls->ctx->nb_streams) {
  1507. seek_pls = pls;
  1508. break;
  1509. }
  1510. }
  1511. /* check if the timestamp is valid for the playlist with the
  1512. * specified stream index */
  1513. if (!seek_pls || !find_timestamp_in_playlist(c, seek_pls, seek_timestamp, &seq_no))
  1514. return AVERROR(EIO);
  1515. /* set segment now so we do not need to search again below */
  1516. seek_pls->cur_seq_no = seq_no;
  1517. seek_pls->seek_stream_index = stream_index - seek_pls->stream_offset;
  1518. for (i = 0; i < c->n_playlists; i++) {
  1519. /* Reset reading */
  1520. struct playlist *pls = c->playlists[i];
  1521. if (pls->input) {
  1522. ffurl_close(pls->input);
  1523. pls->input = NULL;
  1524. }
  1525. av_free_packet(&pls->pkt);
  1526. reset_packet(&pls->pkt);
  1527. pls->pb.eof_reached = 0;
  1528. /* Clear any buffered data */
  1529. pls->pb.buf_end = pls->pb.buf_ptr = pls->pb.buffer;
  1530. /* Reset the pos, to let the mpegts demuxer know we've seeked. */
  1531. pls->pb.pos = 0;
  1532. /* Flush the packet queue of the subdemuxer. */
  1533. ff_read_frame_flush(pls->ctx);
  1534. pls->seek_timestamp = seek_timestamp;
  1535. pls->seek_flags = flags;
  1536. if (pls != seek_pls) {
  1537. /* set closest segment seq_no for playlists not handled above */
  1538. find_timestamp_in_playlist(c, pls, seek_timestamp, &pls->cur_seq_no);
  1539. /* seek the playlist to the given position without taking
  1540. * keyframes into account since this playlist does not have the
  1541. * specified stream where we should look for the keyframes */
  1542. pls->seek_stream_index = -1;
  1543. pls->seek_flags |= AVSEEK_FLAG_ANY;
  1544. }
  1545. }
  1546. c->cur_timestamp = seek_timestamp;
  1547. return 0;
  1548. }
  1549. static int hls_probe(AVProbeData *p)
  1550. {
  1551. /* Require #EXTM3U at the start, and either one of the ones below
  1552. * somewhere for a proper match. */
  1553. if (strncmp(p->buf, "#EXTM3U", 7))
  1554. return 0;
  1555. if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
  1556. strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
  1557. strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
  1558. return AVPROBE_SCORE_MAX;
  1559. return 0;
  1560. }
  1561. #define OFFSET(x) offsetof(HLSContext, x)
  1562. #define FLAGS AV_OPT_FLAG_DECODING_PARAM
  1563. static const AVOption hls_options[] = {
  1564. {"live_start_index", "segment index to start live streams at (negative values are from the end)",
  1565. OFFSET(live_start_index), AV_OPT_TYPE_INT, {.i64 = -3}, INT_MIN, INT_MAX, FLAGS},
  1566. {NULL}
  1567. };
  1568. static const AVClass hls_class = {
  1569. .class_name = "hls,applehttp",
  1570. .item_name = av_default_item_name,
  1571. .option = hls_options,
  1572. .version = LIBAVUTIL_VERSION_INT,
  1573. };
  1574. AVInputFormat ff_hls_demuxer = {
  1575. .name = "hls,applehttp",
  1576. .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
  1577. .priv_class = &hls_class,
  1578. .priv_data_size = sizeof(HLSContext),
  1579. .read_probe = hls_probe,
  1580. .read_header = hls_read_header,
  1581. .read_packet = hls_read_packet,
  1582. .read_close = hls_close,
  1583. .read_seek = hls_read_seek,
  1584. };