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.

1727 lines
58KB

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