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.

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