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.

2150 lines
71KB

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