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.

1578 lines
53KB

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