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.

2053 lines
68KB

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