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