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.

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