• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Apple HTTP Live Streaming Protocol Handler
3  * Copyright (c) 2010 Martin Storsjo
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 /**
23  * @file
24  * Apple HTTP Live Streaming Protocol Handler
25  * https://www.rfc-editor.org/rfc/rfc8216.txt
26  */
27 
28 #include "libavutil/avstring.h"
29 #include "libavutil/time.h"
30 #include "avformat.h"
31 #include "avio_internal.h"
32 #include "internal.h"
33 #include "url.h"
34 
35 /*
36  * An apple http stream consists of a playlist with media segment files,
37  * played sequentially. There may be several playlists with the same
38  * video content, in different bandwidth variants, that are played in
39  * parallel (preferably only one bandwidth variant at a time). In this case,
40  * the user supplied the url to a main playlist that only lists the variant
41  * playlists.
42  *
43  * If the main playlist doesn't point at any variants, we still create
44  * one anonymous toplevel variant for this, to maintain the structure.
45  */
46 
47 struct segment {
48     int64_t duration;
49     char url[MAX_URL_SIZE];
50 };
51 
52 struct variant {
53     int bandwidth;
54     char url[MAX_URL_SIZE];
55 };
56 
57 typedef struct HLSContext {
58     char playlisturl[MAX_URL_SIZE];
59     int64_t target_duration;
60     int start_seq_no;
61     int finished;
62     int n_segments;
63     struct segment **segments;
64     int n_variants;
65     struct variant **variants;
66     int cur_seq_no;
67     URLContext *seg_hd;
68     int64_t last_load_time;
69 } HLSContext;
70 
free_segment_list(HLSContext * s)71 static void free_segment_list(HLSContext *s)
72 {
73     int i;
74     for (i = 0; i < s->n_segments; i++)
75         av_freep(&s->segments[i]);
76     av_freep(&s->segments);
77     s->n_segments = 0;
78 }
79 
free_variant_list(HLSContext * s)80 static void free_variant_list(HLSContext *s)
81 {
82     int i;
83     for (i = 0; i < s->n_variants; i++)
84         av_freep(&s->variants[i]);
85     av_freep(&s->variants);
86     s->n_variants = 0;
87 }
88 
89 struct variant_info {
90     char bandwidth[20];
91 };
92 
handle_variant_args(struct variant_info * info,const char * key,int key_len,char ** dest,int * dest_len)93 static void handle_variant_args(struct variant_info *info, const char *key,
94                                 int key_len, char **dest, int *dest_len)
95 {
96     if (!strncmp(key, "BANDWIDTH=", key_len)) {
97         *dest     =        info->bandwidth;
98         *dest_len = sizeof(info->bandwidth);
99     }
100 }
101 
parse_playlist(URLContext * h,const char * url)102 static int parse_playlist(URLContext *h, const char *url)
103 {
104     HLSContext *s = h->priv_data;
105     AVIOContext *in;
106     int ret = 0, is_segment = 0, is_variant = 0, bandwidth = 0;
107     int64_t duration = 0;
108     char line[1024];
109     const char *ptr;
110 
111     if ((ret = ffio_open_whitelist(&in, url, AVIO_FLAG_READ,
112                                    &h->interrupt_callback, NULL,
113                                    h->protocol_whitelist, h->protocol_blacklist)) < 0)
114         return ret;
115 
116     ff_get_chomp_line(in, line, sizeof(line));
117     if (strcmp(line, "#EXTM3U")) {
118         ret = AVERROR_INVALIDDATA;
119         goto fail;
120     }
121 
122     free_segment_list(s);
123     s->finished = 0;
124     while (!avio_feof(in)) {
125         ff_get_chomp_line(in, line, sizeof(line));
126         if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
127             struct variant_info info = {{0}};
128             is_variant = 1;
129             ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
130                                &info);
131             bandwidth = atoi(info.bandwidth);
132         } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
133             s->target_duration = atoi(ptr) * AV_TIME_BASE;
134         } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
135             s->start_seq_no = atoi(ptr);
136         } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
137             s->finished = 1;
138         } else if (av_strstart(line, "#EXTINF:", &ptr)) {
139             is_segment = 1;
140             duration = atof(ptr) * AV_TIME_BASE;
141         } else if (av_strstart(line, "#", NULL)) {
142             continue;
143         } else if (line[0]) {
144             if (is_segment) {
145                 struct segment *seg = av_malloc(sizeof(struct segment));
146                 if (!seg) {
147                     ret = AVERROR(ENOMEM);
148                     goto fail;
149                 }
150                 seg->duration = duration;
151                 ff_make_absolute_url(seg->url, sizeof(seg->url), url, line);
152                 dynarray_add(&s->segments, &s->n_segments, seg);
153                 is_segment = 0;
154             } else if (is_variant) {
155                 struct variant *var = av_malloc(sizeof(struct variant));
156                 if (!var) {
157                     ret = AVERROR(ENOMEM);
158                     goto fail;
159                 }
160                 var->bandwidth = bandwidth;
161                 ff_make_absolute_url(var->url, sizeof(var->url), url, line);
162                 dynarray_add(&s->variants, &s->n_variants, var);
163                 is_variant = 0;
164             }
165         }
166     }
167     s->last_load_time = av_gettime_relative();
168 
169 fail:
170     avio_close(in);
171     return ret;
172 }
173 
hls_close(URLContext * h)174 static int hls_close(URLContext *h)
175 {
176     HLSContext *s = h->priv_data;
177 
178     free_segment_list(s);
179     free_variant_list(s);
180     ffurl_closep(&s->seg_hd);
181     return 0;
182 }
183 
hls_open(URLContext * h,const char * uri,int flags)184 static int hls_open(URLContext *h, const char *uri, int flags)
185 {
186     HLSContext *s = h->priv_data;
187     int ret, i;
188     const char *nested_url;
189 
190     if (flags & AVIO_FLAG_WRITE)
191         return AVERROR(ENOSYS);
192 
193     h->is_streamed = 1;
194 
195     if (av_strstart(uri, "hls+", &nested_url)) {
196         av_strlcpy(s->playlisturl, nested_url, sizeof(s->playlisturl));
197     } else if (av_strstart(uri, "hls://", &nested_url)) {
198         av_log(h, AV_LOG_ERROR,
199                "No nested protocol specified. Specify e.g. hls+http://%s\n",
200                nested_url);
201         ret = AVERROR(EINVAL);
202         goto fail;
203     } else {
204         av_log(h, AV_LOG_ERROR, "Unsupported url %s\n", uri);
205         ret = AVERROR(EINVAL);
206         goto fail;
207     }
208     av_log(h, AV_LOG_WARNING,
209            "Using the hls protocol is discouraged, please try using the "
210            "hls demuxer instead. The hls demuxer should be more complete "
211            "and work as well as the protocol implementation. (If not, "
212            "please report it.) To use the demuxer, simply use %s as url.\n",
213            s->playlisturl);
214 
215     if ((ret = parse_playlist(h, s->playlisturl)) < 0)
216         goto fail;
217 
218     if (s->n_segments == 0 && s->n_variants > 0) {
219         int max_bandwidth = 0, maxvar = -1;
220         for (i = 0; i < s->n_variants; i++) {
221             if (s->variants[i]->bandwidth > max_bandwidth || i == 0) {
222                 max_bandwidth = s->variants[i]->bandwidth;
223                 maxvar = i;
224             }
225         }
226         av_strlcpy(s->playlisturl, s->variants[maxvar]->url,
227                    sizeof(s->playlisturl));
228         if ((ret = parse_playlist(h, s->playlisturl)) < 0)
229             goto fail;
230     }
231 
232     if (s->n_segments == 0) {
233         av_log(h, AV_LOG_WARNING, "Empty playlist\n");
234         ret = AVERROR(EIO);
235         goto fail;
236     }
237     s->cur_seq_no = s->start_seq_no;
238     if (!s->finished && s->n_segments >= 3)
239         s->cur_seq_no = s->start_seq_no + s->n_segments - 3;
240 
241     return 0;
242 
243 fail:
244     hls_close(h);
245     return ret;
246 }
247 
hls_read(URLContext * h,uint8_t * buf,int size)248 static int hls_read(URLContext *h, uint8_t *buf, int size)
249 {
250     HLSContext *s = h->priv_data;
251     const char *url;
252     int ret;
253     int64_t reload_interval;
254 
255 start:
256     if (s->seg_hd) {
257         ret = ffurl_read(s->seg_hd, buf, size);
258         if (ret > 0)
259             return ret;
260     }
261     if (s->seg_hd) {
262         ffurl_closep(&s->seg_hd);
263         s->cur_seq_no++;
264     }
265     reload_interval = s->n_segments > 0 ?
266                       s->segments[s->n_segments - 1]->duration :
267                       s->target_duration;
268 retry:
269     if (!s->finished) {
270         int64_t now = av_gettime_relative();
271         if (now - s->last_load_time >= reload_interval) {
272             if ((ret = parse_playlist(h, s->playlisturl)) < 0)
273                 return ret;
274             /* If we need to reload the playlist again below (if
275              * there's still no more segments), switch to a reload
276              * interval of half the target duration. */
277             reload_interval = s->target_duration / 2;
278         }
279     }
280     if (s->cur_seq_no < s->start_seq_no) {
281         av_log(h, AV_LOG_WARNING,
282                "skipping %d segments ahead, expired from playlist\n",
283                s->start_seq_no - s->cur_seq_no);
284         s->cur_seq_no = s->start_seq_no;
285     }
286     if (s->cur_seq_no - s->start_seq_no >= s->n_segments) {
287         if (s->finished)
288             return AVERROR_EOF;
289         while (av_gettime_relative() - s->last_load_time < reload_interval) {
290             if (ff_check_interrupt(&h->interrupt_callback))
291                 return AVERROR_EXIT;
292             av_usleep(100*1000);
293         }
294         goto retry;
295     }
296     url = s->segments[s->cur_seq_no - s->start_seq_no]->url;
297     av_log(h, AV_LOG_DEBUG, "opening %s\n", url);
298     ret = ffurl_open_whitelist(&s->seg_hd, url, AVIO_FLAG_READ,
299                                &h->interrupt_callback, NULL,
300                                h->protocol_whitelist, h->protocol_blacklist, h);
301     if (ret < 0) {
302         if (ff_check_interrupt(&h->interrupt_callback))
303             return AVERROR_EXIT;
304         av_log(h, AV_LOG_WARNING, "Unable to open %s\n", url);
305         s->cur_seq_no++;
306         goto retry;
307     }
308     goto start;
309 }
310 
311 const URLProtocol ff_hls_protocol = {
312     .name           = "hls",
313     .url_open       = hls_open,
314     .url_read       = hls_read,
315     .url_close      = hls_close,
316     .flags          = URL_PROTOCOL_FLAG_NESTED_SCHEME,
317     .priv_data_size = sizeof(HLSContext),
318 };
319