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.

2174 lines
72KB

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