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.

2335 lines
78KB

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