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.

2287 lines
76KB

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