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.

1754 lines
59KB

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