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.

2348 lines
79KB

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