Ticket #3024: hls.c

File hls.c, 28.2 KB (added by Kow, 13 years ago)

hls.c patched to keep user header during the whole hls streaming

Line 
1/*
2 * Apple HTTP Live Streaming demuxer
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 demuxer
25 * http://tools.ietf.org/html/draft-pantos-http-live-streaming
26 */
27
28#include "libavutil/avstring.h"
29#include "libavutil/intreadwrite.h"
30#include "libavutil/mathematics.h"
31#include "libavutil/opt.h"
32#include "libavutil/dict.h"
33#include "libavutil/time.h"
34#include "avformat.h"
35#include "internal.h"
36#include "avio_internal.h"
37#include "url.h"
38
39#define INITIAL_BUFFER_SIZE 32768
40
41/*
42 * An apple http stream consists of a playlist with media segment files,
43 * played sequentially. There may be several playlists with the same
44 * video content, in different bandwidth variants, that are played in
45 * parallel (preferably only one bandwidth variant at a time). In this case,
46 * the user supplied the url to a main playlist that only lists the variant
47 * playlists.
48 *
49 * If the main playlist doesn't point at any variants, we still create
50 * one anonymous toplevel variant for this, to maintain the structure.
51 */
52
53enum KeyType {
54 KEY_NONE,
55 KEY_AES_128,
56};
57
58struct segment {
59 int64_t duration;
60 char url[MAX_URL_SIZE];
61 char key[MAX_URL_SIZE];
62 enum KeyType key_type;
63 uint8_t iv[16];
64};
65
66/*
67 * Each variant has its own demuxer. If it currently is active,
68 * it has an open AVIOContext too, and potentially an AVPacket
69 * containing the next packet from this stream.
70 */
71struct variant {
72 int bandwidth;
73 char url[MAX_URL_SIZE];
74 AVIOContext pb;
75 uint8_t* read_buffer;
76 URLContext *input;
77 AVFormatContext *parent;
78 int index;
79 AVFormatContext *ctx;
80 AVPacket pkt;
81 int stream_offset;
82
83 int finished;
84 int64_t target_duration;
85 int start_seq_no;
86 int n_segments;
87 struct segment **segments;
88 int needed, cur_needed;
89 int cur_seq_no;
90 int64_t last_load_time;
91
92 char key_url[MAX_URL_SIZE];
93 uint8_t key[16];
94};
95
96typedef struct HLSContext {
97 int n_variants;
98 struct variant **variants;
99 int cur_seq_no;
100 int end_of_segment;
101 int first_packet;
102 int64_t first_timestamp;
103 int64_t seek_timestamp;
104 int seek_flags;
105 AVIOInterruptCB *interrupt_callback;
106 char *user_agent; ///< holds HTTP user agent set as an AVOption to the HTTP protocol context
107 char *cookies; ///< holds HTTP cookie values set in either the initial response or as an AVOption to the HTTP protocol context
108 char *headers; ///< holds HTTP headers set as an AVOption to the HTTP protocol context (kow|mitm)
109} HLSContext;
110
111static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
112{
113 int len = ff_get_line(s, buf, maxlen);
114 while (len > 0 && av_isspace(buf[len - 1]))
115 buf[--len] = '\0';
116 return len;
117}
118
119static void free_segment_list(struct variant *var)
120{
121 int i;
122 for (i = 0; i < var->n_segments; i++)
123 av_free(var->segments[i]);
124 av_freep(&var->segments);
125 var->n_segments = 0;
126}
127
128static void free_variant_list(HLSContext *c)
129{
130 int i;
131 for (i = 0; i < c->n_variants; i++) {
132 struct variant *var = c->variants[i];
133 free_segment_list(var);
134 av_free_packet(&var->pkt);
135 av_free(var->pb.buffer);
136 if (var->input)
137 ffurl_close(var->input);
138 if (var->ctx) {
139 var->ctx->pb = NULL;
140 avformat_close_input(&var->ctx);
141 }
142 av_free(var);
143 }
144 av_freep(&c->variants);
145 av_freep(&c->cookies);
146 av_freep(&c->user_agent);
147 c->n_variants = 0;
148}
149
150/*
151 * Used to reset a statically allocated AVPacket to a clean slate,
152 * containing no data.
153 */
154static void reset_packet(AVPacket *pkt)
155{
156 av_init_packet(pkt);
157 pkt->data = NULL;
158}
159
160static struct variant *new_variant(HLSContext *c, int bandwidth,
161 const char *url, const char *base)
162{
163 struct variant *var = av_mallocz(sizeof(struct variant));
164 if (!var)
165 return NULL;
166 reset_packet(&var->pkt);
167 var->bandwidth = bandwidth;
168 ff_make_absolute_url(var->url, sizeof(var->url), base, url);
169 dynarray_add(&c->variants, &c->n_variants, var);
170 return var;
171}
172
173struct variant_info {
174 char bandwidth[20];
175};
176
177static void handle_variant_args(struct variant_info *info, const char *key,
178 int key_len, char **dest, int *dest_len)
179{
180 if (!strncmp(key, "BANDWIDTH=", key_len)) {
181 *dest = info->bandwidth;
182 *dest_len = sizeof(info->bandwidth);
183 }
184}
185
186struct key_info {
187 char uri[MAX_URL_SIZE];
188 char method[10];
189 char iv[35];
190};
191
192static void handle_key_args(struct key_info *info, const char *key,
193 int key_len, char **dest, int *dest_len)
194{
195 if (!strncmp(key, "METHOD=", key_len)) {
196 *dest = info->method;
197 *dest_len = sizeof(info->method);
198 } else if (!strncmp(key, "URI=", key_len)) {
199 *dest = info->uri;
200 *dest_len = sizeof(info->uri);
201 } else if (!strncmp(key, "IV=", key_len)) {
202 *dest = info->iv;
203 *dest_len = sizeof(info->iv);
204 }
205}
206
207static int parse_playlist(HLSContext *c, const char *url,
208 struct variant *var, AVIOContext *in)
209{
210 int ret = 0, is_segment = 0, is_variant = 0, bandwidth = 0;
211 int64_t duration = 0;
212 enum KeyType key_type = KEY_NONE;
213 uint8_t iv[16] = "";
214 int has_iv = 0;
215 char key[MAX_URL_SIZE] = "";
216 char line[MAX_URL_SIZE];
217 const char *ptr;
218 int close_in = 0;
219
220 if (!in) {
221 AVDictionary *opts = NULL;
222 close_in = 1;
223 /* Some HLS servers don't like being sent the range header */
224 av_dict_set(&opts, "seekable", "0", 0);
225
226 // broker prior HTTP options that should be consistent across requests
227 av_dict_set(&opts, "user-agent", c->user_agent, 0);
228 av_dict_set(&opts, "cookies", c->cookies, 0);
229 av_dict_set(&opts, "headers", c->headers, 0); // (kow|mitm)
230
231 ret = avio_open2(&in, url, AVIO_FLAG_READ,
232 c->interrupt_callback, &opts);
233 av_dict_free(&opts);
234 if (ret < 0)
235 return ret;
236 }
237
238 read_chomp_line(in, line, sizeof(line));
239 if (strcmp(line, "#EXTM3U")) {
240 ret = AVERROR_INVALIDDATA;
241 goto fail;
242 }
243
244 if (var) {
245 free_segment_list(var);
246 var->finished = 0;
247 }
248 while (!url_feof(in)) {
249 read_chomp_line(in, line, sizeof(line));
250 if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
251 struct variant_info info = {{0}};
252 is_variant = 1;
253 ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
254 &info);
255 bandwidth = atoi(info.bandwidth);
256 } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
257 struct key_info info = {{0}};
258 ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,
259 &info);
260 key_type = KEY_NONE;
261 has_iv = 0;
262 if (!strcmp(info.method, "AES-128"))
263 key_type = KEY_AES_128;
264 if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
265 ff_hex_to_data(iv, info.iv + 2);
266 has_iv = 1;
267 }
268 av_strlcpy(key, info.uri, sizeof(key));
269 } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
270 if (!var) {
271 var = new_variant(c, 0, url, NULL);
272 if (!var) {
273 ret = AVERROR(ENOMEM);
274 goto fail;
275 }
276 }
277 var->target_duration = atoi(ptr) * AV_TIME_BASE;
278 } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
279 if (!var) {
280 var = new_variant(c, 0, url, NULL);
281 if (!var) {
282 ret = AVERROR(ENOMEM);
283 goto fail;
284 }
285 }
286 var->start_seq_no = atoi(ptr);
287 } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
288 if (var)
289 var->finished = 1;
290 } else if (av_strstart(line, "#EXTINF:", &ptr)) {
291 is_segment = 1;
292 duration = atof(ptr) * AV_TIME_BASE;
293 } else if (av_strstart(line, "#", NULL)) {
294 continue;
295 } else if (line[0]) {
296 if (is_variant) {
297 if (!new_variant(c, bandwidth, line, url)) {
298 ret = AVERROR(ENOMEM);
299 goto fail;
300 }
301 is_variant = 0;
302 bandwidth = 0;
303 }
304 if (is_segment) {
305 struct segment *seg;
306 if (!var) {
307 var = new_variant(c, 0, url, NULL);
308 if (!var) {
309 ret = AVERROR(ENOMEM);
310 goto fail;
311 }
312 }
313 seg = av_malloc(sizeof(struct segment));
314 if (!seg) {
315 ret = AVERROR(ENOMEM);
316 goto fail;
317 }
318 seg->duration = duration;
319 seg->key_type = key_type;
320 if (has_iv) {
321 memcpy(seg->iv, iv, sizeof(iv));
322 } else {
323 int seq = var->start_seq_no + var->n_segments;
324 memset(seg->iv, 0, sizeof(seg->iv));
325 AV_WB32(seg->iv + 12, seq);
326 }
327 ff_make_absolute_url(seg->key, sizeof(seg->key), url, key);
328 ff_make_absolute_url(seg->url, sizeof(seg->url), url, line);
329 dynarray_add(&var->segments, &var->n_segments, seg);
330 is_segment = 0;
331 }
332 }
333 }
334 if (var)
335 var->last_load_time = av_gettime();
336
337fail:
338 if (close_in)
339 avio_close(in);
340 return ret;
341}
342
343static int open_input(HLSContext *c, struct variant *var)
344{
345 AVDictionary *opts = NULL;
346 int ret;
347 struct segment *seg = var->segments[var->cur_seq_no - var->start_seq_no];
348
349 // broker prior HTTP options that should be consistent across requests
350 av_dict_set(&opts, "user-agent", c->user_agent, 0);
351 av_dict_set(&opts, "cookies", c->cookies, 0);
352 av_dict_set(&opts, "headers", c->headers, 0); // (kow|mitm)
353 av_dict_set(&opts, "seekable", "0", 0);
354
355 if (seg->key_type == KEY_NONE) {
356 ret = ffurl_open(&var->input, seg->url, AVIO_FLAG_READ,
357 &var->parent->interrupt_callback, &opts);
358 goto cleanup;
359 } else if (seg->key_type == KEY_AES_128) {
360 char iv[33], key[33], url[MAX_URL_SIZE];
361 if (strcmp(seg->key, var->key_url)) {
362 URLContext *uc;
363 if (ffurl_open(&uc, seg->key, AVIO_FLAG_READ,
364 &var->parent->interrupt_callback, &opts) == 0) {
365 if (ffurl_read_complete(uc, var->key, sizeof(var->key))
366 != sizeof(var->key)) {
367 av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
368 seg->key);
369 }
370 ffurl_close(uc);
371 } else {
372 av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
373 seg->key);
374 }
375 av_strlcpy(var->key_url, seg->key, sizeof(var->key_url));
376 }
377 ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
378 ff_data_to_hex(key, var->key, sizeof(var->key), 0);
379 iv[32] = key[32] = '\0';
380 if (strstr(seg->url, "://"))
381 snprintf(url, sizeof(url), "crypto+%s", seg->url);
382 else
383 snprintf(url, sizeof(url), "crypto:%s", seg->url);
384 if ((ret = ffurl_alloc(&var->input, url, AVIO_FLAG_READ,
385 &var->parent->interrupt_callback)) < 0)
386 goto cleanup;
387 av_opt_set(var->input->priv_data, "key", key, 0);
388 av_opt_set(var->input->priv_data, "iv", iv, 0);
389 /* Need to repopulate options */
390 av_dict_free(&opts);
391 av_dict_set(&opts, "seekable", "0", 0);
392 if ((ret = ffurl_connect(var->input, &opts)) < 0) {
393 ffurl_close(var->input);
394 var->input = NULL;
395 goto cleanup;
396 }
397 ret = 0;
398 }
399 else
400 ret = AVERROR(ENOSYS);
401
402cleanup:
403 av_dict_free(&opts);
404 return ret;
405}
406
407static int read_data(void *opaque, uint8_t *buf, int buf_size)
408{
409 struct variant *v = opaque;
410 HLSContext *c = v->parent->priv_data;
411 int ret, i;
412
413restart:
414 if (!v->input) {
415 /* If this is a live stream and the reload interval has elapsed since
416 * the last playlist reload, reload the variant playlists now. */
417 int64_t reload_interval = v->n_segments > 0 ?
418 v->segments[v->n_segments - 1]->duration :
419 v->target_duration;
420
421reload:
422 if (!v->finished &&
423 av_gettime() - v->last_load_time >= reload_interval) {
424 if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
425 return ret;
426 /* If we need to reload the playlist again below (if
427 * there's still no more segments), switch to a reload
428 * interval of half the target duration. */
429 reload_interval = v->target_duration / 2;
430 }
431 if (v->cur_seq_no < v->start_seq_no) {
432 av_log(NULL, AV_LOG_WARNING,
433 "skipping %d segments ahead, expired from playlists\n",
434 v->start_seq_no - v->cur_seq_no);
435 v->cur_seq_no = v->start_seq_no;
436 }
437 if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
438 if (v->finished)
439 return AVERROR_EOF;
440 while (av_gettime() - v->last_load_time < reload_interval) {
441 if (ff_check_interrupt(c->interrupt_callback))
442 return AVERROR_EXIT;
443 av_usleep(100*1000);
444 }
445 /* Enough time has elapsed since the last reload */
446 goto reload;
447 }
448
449 ret = open_input(c, v);
450 if (ret < 0)
451 return ret;
452 }
453 ret = ffurl_read(v->input, buf, buf_size);
454 if (ret > 0)
455 return ret;
456 ffurl_close(v->input);
457 v->input = NULL;
458 v->cur_seq_no++;
459
460 c->end_of_segment = 1;
461 c->cur_seq_no = v->cur_seq_no;
462
463 if (v->ctx && v->ctx->nb_streams &&
464 v->parent->nb_streams >= v->stream_offset + v->ctx->nb_streams) {
465 v->needed = 0;
466 for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;
467 i++) {
468 if (v->parent->streams[i]->discard < AVDISCARD_ALL)
469 v->needed = 1;
470 }
471 }
472 if (!v->needed) {
473 av_log(v->parent, AV_LOG_INFO, "No longer receiving variant %d\n",
474 v->index);
475 return AVERROR_EOF;
476 }
477 goto restart;
478}
479
480static int hls_read_header(AVFormatContext *s)
481{
482 URLContext *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb->opaque;
483 HLSContext *c = s->priv_data;
484 int ret = 0, i, j, stream_offset = 0;
485
486 c->interrupt_callback = &s->interrupt_callback;
487
488 // if the URL context is good, read important options we must broker later
489 if (u && u->prot->priv_data_class) {
490 // get the previous user agent & set back to null if string size is zero
491 av_freep(&c->user_agent);
492 av_opt_get(u->priv_data, "user-agent", 0, (uint8_t**)&(c->user_agent));
493 if (c->user_agent && !strlen(c->user_agent))
494 av_freep(&c->user_agent);
495
496 // get the previous cookies & set back to null if string size is zero
497 av_freep(&c->cookies);
498 av_opt_get(u->priv_data, "cookies", 0, (uint8_t**)&(c->cookies));
499 if (c->cookies && !strlen(c->cookies))
500 av_freep(&c->cookies);
501
502 // get the previous headers & set back to null if string size is zero (kow|mitm)
503 av_freep(&c->headers);
504 av_opt_get(u->priv_data, "headers", 0, (uint8_t**)&(c->headers));
505 if (c->headers && !strlen(c->headers))
506 av_freep(&c->headers);
507 //
508 }
509
510 if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
511 goto fail;
512
513 if (c->n_variants == 0) {
514 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
515 ret = AVERROR_EOF;
516 goto fail;
517 }
518 /* If the playlist only contained variants, parse each individual
519 * variant playlist. */
520 if (c->n_variants > 1 || c->variants[0]->n_segments == 0) {
521 for (i = 0; i < c->n_variants; i++) {
522 struct variant *v = c->variants[i];
523 if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
524 goto fail;
525 }
526 }
527
528 if (c->variants[0]->n_segments == 0) {
529 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
530 ret = AVERROR_EOF;
531 goto fail;
532 }
533
534 /* If this isn't a live stream, calculate the total duration of the
535 * stream. */
536 if (c->variants[0]->finished) {
537 int64_t duration = 0;
538 for (i = 0; i < c->variants[0]->n_segments; i++)
539 duration += c->variants[0]->segments[i]->duration;
540 s->duration = duration;
541 }
542
543 /* Open the demuxer for each variant */
544 for (i = 0; i < c->n_variants; i++) {
545 struct variant *v = c->variants[i];
546 AVInputFormat *in_fmt = NULL;
547 char bitrate_str[20];
548 AVProgram *program;
549
550 if (v->n_segments == 0)
551 continue;
552
553 if (!(v->ctx = avformat_alloc_context())) {
554 ret = AVERROR(ENOMEM);
555 goto fail;
556 }
557
558 v->index = i;
559 v->needed = 1;
560 v->parent = s;
561
562 /* If this is a live stream with more than 3 segments, start at the
563 * third last segment. */
564 v->cur_seq_no = v->start_seq_no;
565 if (!v->finished && v->n_segments > 3)
566 v->cur_seq_no = v->start_seq_no + v->n_segments - 3;
567
568 v->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
569 ffio_init_context(&v->pb, v->read_buffer, INITIAL_BUFFER_SIZE, 0, v,
570 read_data, NULL, NULL);
571 v->pb.seekable = 0;
572 ret = av_probe_input_buffer(&v->pb, &in_fmt, v->segments[0]->url,
573 NULL, 0, 0);
574 if (ret < 0) {
575 /* Free the ctx - it isn't initialized properly at this point,
576 * so avformat_close_input shouldn't be called. If
577 * avformat_open_input fails below, it frees and zeros the
578 * context, so it doesn't need any special treatment like this. */
579 av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", v->segments[0]->url);
580 avformat_free_context(v->ctx);
581 v->ctx = NULL;
582 goto fail;
583 }
584 v->ctx->pb = &v->pb;
585 v->stream_offset = stream_offset;
586 ret = avformat_open_input(&v->ctx, v->segments[0]->url, in_fmt, NULL);
587 if (ret < 0)
588 goto fail;
589
590 v->ctx->ctx_flags &= ~AVFMTCTX_NOHEADER;
591 ret = avformat_find_stream_info(v->ctx, NULL);
592 if (ret < 0)
593 goto fail;
594 snprintf(bitrate_str, sizeof(bitrate_str), "%d", v->bandwidth);
595
596 program = av_new_program(s, i);
597 if (!program)
598 goto fail;
599 av_dict_set(&program->metadata, "variant_bitrate", bitrate_str, 0);
600
601 /* Create new AVStreams for each stream in this variant */
602 for (j = 0; j < v->ctx->nb_streams; j++) {
603 AVStream *st = avformat_new_stream(s, NULL);
604 AVStream *ist = v->ctx->streams[j];
605 if (!st) {
606 ret = AVERROR(ENOMEM);
607 goto fail;
608 }
609 ff_program_add_stream_index(s, i, stream_offset + j);
610 st->id = i;
611 avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
612 avcodec_copy_context(st->codec, v->ctx->streams[j]->codec);
613 if (v->bandwidth)
614 av_dict_set(&st->metadata, "variant_bitrate", bitrate_str,
615 0);
616 }
617 stream_offset += v->ctx->nb_streams;
618 }
619
620 c->first_packet = 1;
621 c->first_timestamp = AV_NOPTS_VALUE;
622 c->seek_timestamp = AV_NOPTS_VALUE;
623
624 return 0;
625fail:
626 free_variant_list(c);
627 return ret;
628}
629
630static int recheck_discard_flags(AVFormatContext *s, int first)
631{
632 HLSContext *c = s->priv_data;
633 int i, changed = 0;
634
635 /* Check if any new streams are needed */
636 for (i = 0; i < c->n_variants; i++)
637 c->variants[i]->cur_needed = 0;
638
639 for (i = 0; i < s->nb_streams; i++) {
640 AVStream *st = s->streams[i];
641 struct variant *var = c->variants[s->streams[i]->id];
642 if (st->discard < AVDISCARD_ALL)
643 var->cur_needed = 1;
644 }
645 for (i = 0; i < c->n_variants; i++) {
646 struct variant *v = c->variants[i];
647 if (v->cur_needed && !v->needed) {
648 v->needed = 1;
649 changed = 1;
650 v->cur_seq_no = c->cur_seq_no;
651 v->pb.eof_reached = 0;
652 av_log(s, AV_LOG_INFO, "Now receiving variant %d\n", i);
653 } else if (first && !v->cur_needed && v->needed) {
654 if (v->input)
655 ffurl_close(v->input);
656 v->input = NULL;
657 v->needed = 0;
658 changed = 1;
659 av_log(s, AV_LOG_INFO, "No longer receiving variant %d\n", i);
660 }
661 }
662 return changed;
663}
664
665static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
666{
667 HLSContext *c = s->priv_data;
668 int ret, i, minvariant = -1;
669
670 if (c->first_packet) {
671 recheck_discard_flags(s, 1);
672 c->first_packet = 0;
673 }
674
675start:
676 c->end_of_segment = 0;
677 for (i = 0; i < c->n_variants; i++) {
678 struct variant *var = c->variants[i];
679 /* Make sure we've got one buffered packet from each open variant
680 * stream */
681 if (var->needed && !var->pkt.data) {
682 while (1) {
683 int64_t ts_diff;
684 AVStream *st;
685 ret = av_read_frame(var->ctx, &var->pkt);
686 if (ret < 0) {
687 if (!url_feof(&var->pb) && ret != AVERROR_EOF)
688 return ret;
689 reset_packet(&var->pkt);
690 break;
691 } else {
692 if (c->first_timestamp == AV_NOPTS_VALUE &&
693 var->pkt.dts != AV_NOPTS_VALUE)
694 c->first_timestamp = av_rescale_q(var->pkt.dts,
695 var->ctx->streams[var->pkt.stream_index]->time_base,
696 AV_TIME_BASE_Q);
697 }
698
699 if (c->seek_timestamp == AV_NOPTS_VALUE)
700 break;
701
702 if (var->pkt.dts == AV_NOPTS_VALUE) {
703 c->seek_timestamp = AV_NOPTS_VALUE;
704 break;
705 }
706
707 st = var->ctx->streams[var->pkt.stream_index];
708 ts_diff = av_rescale_rnd(var->pkt.dts, AV_TIME_BASE,
709 st->time_base.den, AV_ROUND_DOWN) -
710 c->seek_timestamp;
711 if (ts_diff >= 0 && (c->seek_flags & AVSEEK_FLAG_ANY ||
712 var->pkt.flags & AV_PKT_FLAG_KEY)) {
713 c->seek_timestamp = AV_NOPTS_VALUE;
714 break;
715 }
716 av_free_packet(&var->pkt);
717 reset_packet(&var->pkt);
718 }
719 }
720 /* Check if this stream still is on an earlier segment number, or
721 * has the packet with the lowest dts */
722 if (var->pkt.data) {
723 struct variant *minvar = c->variants[minvariant];
724 if (minvariant < 0 || var->cur_seq_no < minvar->cur_seq_no) {
725 minvariant = i;
726 } else if (var->cur_seq_no == minvar->cur_seq_no) {
727 int64_t dts = var->pkt.dts;
728 int64_t mindts = minvar->pkt.dts;
729 AVStream *st = var->ctx->streams[var->pkt.stream_index];
730 AVStream *minst = minvar->ctx->streams[minvar->pkt.stream_index];
731
732 if (dts == AV_NOPTS_VALUE) {
733 minvariant = i;
734 } else if (mindts != AV_NOPTS_VALUE) {
735 if (st->start_time != AV_NOPTS_VALUE)
736 dts -= st->start_time;
737 if (minst->start_time != AV_NOPTS_VALUE)
738 mindts -= minst->start_time;
739
740 if (av_compare_ts(dts, st->time_base,
741 mindts, minst->time_base) < 0)
742 minvariant = i;
743 }
744 }
745 }
746 }
747 if (c->end_of_segment) {
748 if (recheck_discard_flags(s, 0))
749 goto start;
750 }
751 /* If we got a packet, return it */
752 if (minvariant >= 0) {
753 *pkt = c->variants[minvariant]->pkt;
754 pkt->stream_index += c->variants[minvariant]->stream_offset;
755 reset_packet(&c->variants[minvariant]->pkt);
756 return 0;
757 }
758 return AVERROR_EOF;
759}
760
761static int hls_close(AVFormatContext *s)
762{
763 HLSContext *c = s->priv_data;
764
765 free_variant_list(c);
766 return 0;
767}
768
769static int hls_read_seek(AVFormatContext *s, int stream_index,
770 int64_t timestamp, int flags)
771{
772 HLSContext *c = s->priv_data;
773 int i, j, ret;
774
775 if ((flags & AVSEEK_FLAG_BYTE) || !c->variants[0]->finished)
776 return AVERROR(ENOSYS);
777
778 c->seek_flags = flags;
779 c->seek_timestamp = stream_index < 0 ? timestamp :
780 av_rescale_rnd(timestamp, AV_TIME_BASE,
781 s->streams[stream_index]->time_base.den,
782 flags & AVSEEK_FLAG_BACKWARD ?
783 AV_ROUND_DOWN : AV_ROUND_UP);
784 timestamp = av_rescale_rnd(timestamp, AV_TIME_BASE, stream_index >= 0 ?
785 s->streams[stream_index]->time_base.den :
786 AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
787 AV_ROUND_DOWN : AV_ROUND_UP);
788 if (s->duration < c->seek_timestamp) {
789 c->seek_timestamp = AV_NOPTS_VALUE;
790 return AVERROR(EIO);
791 }
792
793 ret = AVERROR(EIO);
794 for (i = 0; i < c->n_variants; i++) {
795 /* Reset reading */
796 struct variant *var = c->variants[i];
797 int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
798 0 : c->first_timestamp;
799 if (var->input) {
800 ffurl_close(var->input);
801 var->input = NULL;
802 }
803 av_free_packet(&var->pkt);
804 reset_packet(&var->pkt);
805 var->pb.eof_reached = 0;
806 /* Clear any buffered data */
807 var->pb.buf_end = var->pb.buf_ptr = var->pb.buffer;
808 /* Reset the pos, to let the mpegts demuxer know we've seeked. */
809 var->pb.pos = 0;
810
811 /* Locate the segment that contains the target timestamp */
812 for (j = 0; j < var->n_segments; j++) {
813 if (timestamp >= pos &&
814 timestamp < pos + var->segments[j]->duration) {
815 var->cur_seq_no = var->start_seq_no + j;
816 ret = 0;
817 break;
818 }
819 pos += var->segments[j]->duration;
820 }
821 if (ret)
822 c->seek_timestamp = AV_NOPTS_VALUE;
823 }
824 return ret;
825}
826
827static int hls_probe(AVProbeData *p)
828{
829 /* Require #EXTM3U at the start, and either one of the ones below
830 * somewhere for a proper match. */
831 if (strncmp(p->buf, "#EXTM3U", 7))
832 return 0;
833 if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
834 strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
835 strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
836 return AVPROBE_SCORE_MAX;
837 return 0;
838}
839
840AVInputFormat ff_hls_demuxer = {
841 .name = "hls,applehttp",
842 .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
843 .priv_data_size = sizeof(HLSContext),
844 .read_probe = hls_probe,
845 .read_header = hls_read_header,
846 .read_packet = hls_read_packet,
847 .read_close = hls_close,
848 .read_seek = hls_read_seek,
849};