Libav
hls.c
Go to the documentation of this file.
1 /*
2  * Apple HTTP Live Streaming demuxer
3  * Copyright (c) 2010 Martin Storsjo
4  *
5  * This file is part of Libav.
6  *
7  * Libav 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  * Libav 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 Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
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 
53 enum KeyType {
56 };
57 
58 struct segment {
59  int64_t duration;
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  */
71 struct variant {
72  int bandwidth;
78  int index;
82 
83  int finished;
84  int64_t target_duration;
87  struct segment **segments;
90  int64_t last_load_time;
91 
93  uint8_t key[16];
94 };
95 
96 typedef struct HLSContext {
98  struct variant **variants;
103  int64_t seek_timestamp;
106 } HLSContext;
107 
108 static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
109 {
110  int len = ff_get_line(s, buf, maxlen);
111  while (len > 0 && av_isspace(buf[len - 1]))
112  buf[--len] = '\0';
113  return len;
114 }
115 
116 static void free_segment_list(struct variant *var)
117 {
118  int i;
119  for (i = 0; i < var->n_segments; i++)
120  av_free(var->segments[i]);
121  av_freep(&var->segments);
122  var->n_segments = 0;
123 }
124 
126 {
127  int i;
128  for (i = 0; i < c->n_variants; i++) {
129  struct variant *var = c->variants[i];
130  free_segment_list(var);
131  av_free_packet(&var->pkt);
132  av_free(var->pb.buffer);
133  if (var->input)
134  ffurl_close(var->input);
135  if (var->ctx) {
136  var->ctx->pb = NULL;
137  avformat_close_input(&var->ctx);
138  }
139  av_free(var);
140  }
141  av_freep(&c->variants);
142  c->n_variants = 0;
143 }
144 
145 /*
146  * Used to reset a statically allocated AVPacket to a clean slate,
147  * containing no data.
148  */
149 static void reset_packet(AVPacket *pkt)
150 {
151  av_init_packet(pkt);
152  pkt->data = NULL;
153 }
154 
155 static struct variant *new_variant(HLSContext *c, int bandwidth,
156  const char *url, const char *base)
157 {
158  struct variant *var = av_mallocz(sizeof(struct variant));
159  if (!var)
160  return NULL;
161  reset_packet(&var->pkt);
162  var->bandwidth = bandwidth;
163  ff_make_absolute_url(var->url, sizeof(var->url), base, url);
164  dynarray_add(&c->variants, &c->n_variants, var);
165  return var;
166 }
167 
168 struct variant_info {
169  char bandwidth[20];
170 };
171 
172 static void handle_variant_args(struct variant_info *info, const char *key,
173  int key_len, char **dest, int *dest_len)
174 {
175  if (!strncmp(key, "BANDWIDTH=", key_len)) {
176  *dest = info->bandwidth;
177  *dest_len = sizeof(info->bandwidth);
178  }
179 }
180 
181 struct key_info {
183  char method[10];
184  char iv[35];
185 };
186 
187 static void handle_key_args(struct key_info *info, const char *key,
188  int key_len, char **dest, int *dest_len)
189 {
190  if (!strncmp(key, "METHOD=", key_len)) {
191  *dest = info->method;
192  *dest_len = sizeof(info->method);
193  } else if (!strncmp(key, "URI=", key_len)) {
194  *dest = info->uri;
195  *dest_len = sizeof(info->uri);
196  } else if (!strncmp(key, "IV=", key_len)) {
197  *dest = info->iv;
198  *dest_len = sizeof(info->iv);
199  }
200 }
201 
202 static int parse_playlist(HLSContext *c, const char *url,
203  struct variant *var, AVIOContext *in)
204 {
205  int ret = 0, is_segment = 0, is_variant = 0, bandwidth = 0;
206  int64_t duration = 0;
207  enum KeyType key_type = KEY_NONE;
208  uint8_t iv[16] = "";
209  int has_iv = 0;
210  char key[MAX_URL_SIZE] = "";
211  char line[1024];
212  const char *ptr;
213  int close_in = 0;
214  uint8_t *new_url = NULL;
215 
216  if (!in) {
217  close_in = 1;
218  if ((ret = avio_open2(&in, url, AVIO_FLAG_READ,
219  c->interrupt_callback, NULL)) < 0)
220  return ret;
221  }
222 
223  if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)
224  url = new_url;
225 
226  read_chomp_line(in, line, sizeof(line));
227  if (strcmp(line, "#EXTM3U")) {
228  ret = AVERROR_INVALIDDATA;
229  goto fail;
230  }
231 
232  if (var) {
233  free_segment_list(var);
234  var->finished = 0;
235  }
236  while (!in->eof_reached) {
237  read_chomp_line(in, line, sizeof(line));
238  if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
239  struct variant_info info = {{0}};
240  is_variant = 1;
242  &info);
243  bandwidth = atoi(info.bandwidth);
244  } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
245  struct key_info info = {{0}};
247  &info);
248  key_type = KEY_NONE;
249  has_iv = 0;
250  if (!strcmp(info.method, "AES-128"))
251  key_type = KEY_AES_128;
252  if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
253  ff_hex_to_data(iv, info.iv + 2);
254  has_iv = 1;
255  }
256  av_strlcpy(key, info.uri, sizeof(key));
257  } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
258  if (!var) {
259  var = new_variant(c, 0, url, NULL);
260  if (!var) {
261  ret = AVERROR(ENOMEM);
262  goto fail;
263  }
264  }
265  var->target_duration = atoi(ptr) * AV_TIME_BASE;
266  } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
267  if (!var) {
268  var = new_variant(c, 0, url, NULL);
269  if (!var) {
270  ret = AVERROR(ENOMEM);
271  goto fail;
272  }
273  }
274  var->start_seq_no = atoi(ptr);
275  } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
276  if (var)
277  var->finished = 1;
278  } else if (av_strstart(line, "#EXTINF:", &ptr)) {
279  is_segment = 1;
280  duration = atof(ptr) * AV_TIME_BASE;
281  } else if (av_strstart(line, "#", NULL)) {
282  continue;
283  } else if (line[0]) {
284  if (is_variant) {
285  if (!new_variant(c, bandwidth, line, url)) {
286  ret = AVERROR(ENOMEM);
287  goto fail;
288  }
289  is_variant = 0;
290  bandwidth = 0;
291  }
292  if (is_segment) {
293  struct segment *seg;
294  if (!var) {
295  var = new_variant(c, 0, url, NULL);
296  if (!var) {
297  ret = AVERROR(ENOMEM);
298  goto fail;
299  }
300  }
301  seg = av_malloc(sizeof(struct segment));
302  if (!seg) {
303  ret = AVERROR(ENOMEM);
304  goto fail;
305  }
306  seg->duration = duration;
307  seg->key_type = key_type;
308  if (has_iv) {
309  memcpy(seg->iv, iv, sizeof(iv));
310  } else {
311  int seq = var->start_seq_no + var->n_segments;
312  memset(seg->iv, 0, sizeof(seg->iv));
313  AV_WB32(seg->iv + 12, seq);
314  }
315  ff_make_absolute_url(seg->key, sizeof(seg->key), url, key);
316  ff_make_absolute_url(seg->url, sizeof(seg->url), url, line);
317  dynarray_add(&var->segments, &var->n_segments, seg);
318  is_segment = 0;
319  }
320  }
321  }
322  if (var)
323  var->last_load_time = av_gettime();
324 
325 fail:
326  av_free(new_url);
327  if (close_in)
328  avio_close(in);
329  return ret;
330 }
331 
332 static int open_input(struct variant *var)
333 {
334  struct segment *seg = var->segments[var->cur_seq_no - var->start_seq_no];
335  if (seg->key_type == KEY_NONE) {
336  return ffurl_open(&var->input, seg->url, AVIO_FLAG_READ,
337  &var->parent->interrupt_callback, NULL);
338  } else if (seg->key_type == KEY_AES_128) {
339  char iv[33], key[33], url[MAX_URL_SIZE];
340  int ret;
341  if (strcmp(seg->key, var->key_url)) {
342  URLContext *uc;
343  if (ffurl_open(&uc, seg->key, AVIO_FLAG_READ,
344  &var->parent->interrupt_callback, NULL) == 0) {
345  if (ffurl_read_complete(uc, var->key, sizeof(var->key))
346  != sizeof(var->key)) {
347  av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
348  seg->key);
349  }
350  ffurl_close(uc);
351  } else {
352  av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
353  seg->key);
354  }
355  av_strlcpy(var->key_url, seg->key, sizeof(var->key_url));
356  }
357  ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
358  ff_data_to_hex(key, var->key, sizeof(var->key), 0);
359  iv[32] = key[32] = '\0';
360  if (strstr(seg->url, "://"))
361  snprintf(url, sizeof(url), "crypto+%s", seg->url);
362  else
363  snprintf(url, sizeof(url), "crypto:%s", seg->url);
364  if ((ret = ffurl_alloc(&var->input, url, AVIO_FLAG_READ,
365  &var->parent->interrupt_callback)) < 0)
366  return ret;
367  av_opt_set(var->input->priv_data, "key", key, 0);
368  av_opt_set(var->input->priv_data, "iv", iv, 0);
369  if ((ret = ffurl_connect(var->input, NULL)) < 0) {
370  ffurl_close(var->input);
371  var->input = NULL;
372  return ret;
373  }
374  return 0;
375  }
376  return AVERROR(ENOSYS);
377 }
378 
379 static int read_data(void *opaque, uint8_t *buf, int buf_size)
380 {
381  struct variant *v = opaque;
382  HLSContext *c = v->parent->priv_data;
383  int ret, i;
384 
385 restart:
386  if (!v->input) {
387  /* If this is a live stream and the reload interval has elapsed since
388  * the last playlist reload, reload the variant playlists now. */
389  int64_t reload_interval = v->n_segments > 0 ?
390  v->segments[v->n_segments - 1]->duration :
391  v->target_duration;
392 
393 reload:
394  if (!v->finished &&
395  av_gettime() - v->last_load_time >= reload_interval) {
396  if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
397  return ret;
398  /* If we need to reload the playlist again below (if
399  * there's still no more segments), switch to a reload
400  * interval of half the target duration. */
401  reload_interval = v->target_duration / 2;
402  }
403  if (v->cur_seq_no < v->start_seq_no) {
405  "skipping %d segments ahead, expired from playlists\n",
406  v->start_seq_no - v->cur_seq_no);
407  v->cur_seq_no = v->start_seq_no;
408  }
409  if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
410  if (v->finished)
411  return AVERROR_EOF;
412  while (av_gettime() - v->last_load_time < reload_interval) {
414  return AVERROR_EXIT;
415  av_usleep(100*1000);
416  }
417  /* Enough time has elapsed since the last reload */
418  goto reload;
419  }
420 
421  ret = open_input(v);
422  if (ret < 0)
423  return ret;
424  }
425  ret = ffurl_read(v->input, buf, buf_size);
426  if (ret > 0)
427  return ret;
428  ffurl_close(v->input);
429  v->input = NULL;
430  v->cur_seq_no++;
431 
432  c->end_of_segment = 1;
433  c->cur_seq_no = v->cur_seq_no;
434 
435  if (v->ctx && v->ctx->nb_streams &&
436  v->parent->nb_streams >= v->stream_offset + v->ctx->nb_streams) {
437  v->needed = 0;
438  for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;
439  i++) {
440  if (v->parent->streams[i]->discard < AVDISCARD_ALL)
441  v->needed = 1;
442  }
443  }
444  if (!v->needed) {
445  av_log(v->parent, AV_LOG_INFO, "No longer receiving variant %d\n",
446  v->index);
447  return AVERROR_EOF;
448  }
449  goto restart;
450 }
451 
453 {
454  HLSContext *c = s->priv_data;
455  int ret = 0, i, j, stream_offset = 0;
456 
458 
459  if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
460  goto fail;
461 
462  if (c->n_variants == 0) {
463  av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
464  ret = AVERROR_EOF;
465  goto fail;
466  }
467  /* If the playlist only contained variants, parse each individual
468  * variant playlist. */
469  if (c->n_variants > 1 || c->variants[0]->n_segments == 0) {
470  for (i = 0; i < c->n_variants; i++) {
471  struct variant *v = c->variants[i];
472  if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
473  goto fail;
474  }
475  }
476 
477  if (c->variants[0]->n_segments == 0) {
478  av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
479  ret = AVERROR_EOF;
480  goto fail;
481  }
482 
483  /* If this isn't a live stream, calculate the total duration of the
484  * stream. */
485  if (c->variants[0]->finished) {
486  int64_t duration = 0;
487  for (i = 0; i < c->variants[0]->n_segments; i++)
488  duration += c->variants[0]->segments[i]->duration;
489  s->duration = duration;
490  }
491 
492  /* Open the demuxer for each variant */
493  for (i = 0; i < c->n_variants; i++) {
494  struct variant *v = c->variants[i];
495  AVInputFormat *in_fmt = NULL;
496  char bitrate_str[20];
497  AVProgram *program;
498 
499  if (v->n_segments == 0)
500  continue;
501 
502  if (!(v->ctx = avformat_alloc_context())) {
503  ret = AVERROR(ENOMEM);
504  goto fail;
505  }
506 
507  v->index = i;
508  v->needed = 1;
509  v->parent = s;
510 
511  /* If this is a live stream with more than 3 segments, start at the
512  * third last segment. */
513  v->cur_seq_no = v->start_seq_no;
514  if (!v->finished && v->n_segments > 3)
515  v->cur_seq_no = v->start_seq_no + v->n_segments - 3;
516 
519  read_data, NULL, NULL);
520  v->pb.seekable = 0;
521  ret = av_probe_input_buffer(&v->pb, &in_fmt, v->segments[0]->url,
522  NULL, 0, 0);
523  if (ret < 0) {
524  /* Free the ctx - it isn't initialized properly at this point,
525  * so avformat_close_input shouldn't be called. If
526  * avformat_open_input fails below, it frees and zeros the
527  * context, so it doesn't need any special treatment like this. */
529  v->ctx = NULL;
530  goto fail;
531  }
532  v->ctx->pb = &v->pb;
534  ret = avformat_open_input(&v->ctx, v->segments[0]->url, in_fmt, NULL);
535  if (ret < 0)
536  goto fail;
537 
540  if (ret < 0)
541  goto fail;
542  snprintf(bitrate_str, sizeof(bitrate_str), "%d", v->bandwidth);
543 
544  program = av_new_program(s, i);
545  if (!program)
546  goto fail;
547  av_dict_set(&program->metadata, "variant_bitrate", bitrate_str, 0);
548 
549  /* Create new AVStreams for each stream in this variant */
550  for (j = 0; j < v->ctx->nb_streams; j++) {
552  AVStream *ist = v->ctx->streams[j];
553  if (!st) {
554  ret = AVERROR(ENOMEM);
555  goto fail;
556  }
557  ff_program_add_stream_index(s, i, stream_offset + j);
558  st->id = i;
561  if (v->bandwidth)
562  av_dict_set(&st->metadata, "variant_bitrate", bitrate_str,
563  0);
564  }
565  stream_offset += v->ctx->nb_streams;
566  }
567 
568  c->first_packet = 1;
571 
572  return 0;
573 fail:
575  return ret;
576 }
577 
578 static int recheck_discard_flags(AVFormatContext *s, int first)
579 {
580  HLSContext *c = s->priv_data;
581  int i, changed = 0;
582 
583  /* Check if any new streams are needed */
584  for (i = 0; i < c->n_variants; i++)
585  c->variants[i]->cur_needed = 0;;
586 
587  for (i = 0; i < s->nb_streams; i++) {
588  AVStream *st = s->streams[i];
589  struct variant *var = c->variants[s->streams[i]->id];
590  if (st->discard < AVDISCARD_ALL)
591  var->cur_needed = 1;
592  }
593  for (i = 0; i < c->n_variants; i++) {
594  struct variant *v = c->variants[i];
595  if (v->cur_needed && !v->needed) {
596  v->needed = 1;
597  changed = 1;
598  v->cur_seq_no = c->cur_seq_no;
599  v->pb.eof_reached = 0;
600  av_log(s, AV_LOG_INFO, "Now receiving variant %d\n", i);
601  } else if (first && !v->cur_needed && v->needed) {
602  if (v->input)
603  ffurl_close(v->input);
604  v->input = NULL;
605  v->needed = 0;
606  changed = 1;
607  av_log(s, AV_LOG_INFO, "No longer receiving variant %d\n", i);
608  }
609  }
610  return changed;
611 }
612 
614 {
615  HLSContext *c = s->priv_data;
616  int ret, i, minvariant = -1;
617 
618  if (c->first_packet) {
619  recheck_discard_flags(s, 1);
620  c->first_packet = 0;
621  }
622 
623 start:
624  c->end_of_segment = 0;
625  for (i = 0; i < c->n_variants; i++) {
626  struct variant *var = c->variants[i];
627  /* Make sure we've got one buffered packet from each open variant
628  * stream */
629  if (var->needed && !var->pkt.data) {
630  while (1) {
631  int64_t ts_diff;
632  AVStream *st;
633  ret = av_read_frame(var->ctx, &var->pkt);
634  if (ret < 0) {
635  if (!var->pb.eof_reached)
636  return ret;
637  reset_packet(&var->pkt);
638  break;
639  } else {
640  if (c->first_timestamp == AV_NOPTS_VALUE &&
641  var->pkt.dts != AV_NOPTS_VALUE)
643  var->ctx->streams[var->pkt.stream_index]->time_base,
645  }
646 
647  if (c->seek_timestamp == AV_NOPTS_VALUE)
648  break;
649 
650  if (var->pkt.dts == AV_NOPTS_VALUE) {
652  break;
653  }
654 
655  st = var->ctx->streams[var->pkt.stream_index];
656  ts_diff = av_rescale_rnd(var->pkt.dts, AV_TIME_BASE,
657  st->time_base.den, AV_ROUND_DOWN) -
658  c->seek_timestamp;
659  if (ts_diff >= 0 && (c->seek_flags & AVSEEK_FLAG_ANY ||
660  var->pkt.flags & AV_PKT_FLAG_KEY)) {
662  break;
663  }
664  av_free_packet(&var->pkt);
665  reset_packet(&var->pkt);
666  }
667  }
668  /* Check if this stream still is on an earlier segment number, or
669  * has the packet with the lowest dts */
670  if (var->pkt.data) {
671  struct variant *minvar = minvariant < 0 ?
672  NULL : c->variants[minvariant];
673  if (minvariant < 0 || var->cur_seq_no < minvar->cur_seq_no) {
674  minvariant = i;
675  } else if (var->cur_seq_no == minvar->cur_seq_no) {
676  int64_t dts = var->pkt.dts;
677  int64_t mindts = minvar->pkt.dts;
678  AVStream *st = var->ctx->streams[var->pkt.stream_index];
679  AVStream *minst = minvar->ctx->streams[minvar->pkt.stream_index];
680 
681  if (dts == AV_NOPTS_VALUE) {
682  minvariant = i;
683  } else if (mindts != AV_NOPTS_VALUE) {
684  if (st->start_time != AV_NOPTS_VALUE)
685  dts -= st->start_time;
686  if (minst->start_time != AV_NOPTS_VALUE)
687  mindts -= minst->start_time;
688 
689  if (av_compare_ts(dts, st->time_base,
690  mindts, minst->time_base) < 0)
691  minvariant = i;
692  }
693  }
694  }
695  }
696  if (c->end_of_segment) {
697  if (recheck_discard_flags(s, 0))
698  goto start;
699  }
700  /* If we got a packet, return it */
701  if (minvariant >= 0) {
702  *pkt = c->variants[minvariant]->pkt;
703  pkt->stream_index += c->variants[minvariant]->stream_offset;
704  reset_packet(&c->variants[minvariant]->pkt);
705  return 0;
706  }
707  return AVERROR_EOF;
708 }
709 
711 {
712  HLSContext *c = s->priv_data;
713 
715  return 0;
716 }
717 
718 static int hls_read_seek(AVFormatContext *s, int stream_index,
719  int64_t timestamp, int flags)
720 {
721  HLSContext *c = s->priv_data;
722  int i, j, ret;
723 
724  if ((flags & AVSEEK_FLAG_BYTE) || !c->variants[0]->finished)
725  return AVERROR(ENOSYS);
726 
727  c->seek_flags = flags;
728  c->seek_timestamp = stream_index < 0 ? timestamp :
729  av_rescale_rnd(timestamp, AV_TIME_BASE,
730  s->streams[stream_index]->time_base.den,
731  flags & AVSEEK_FLAG_BACKWARD ?
733  timestamp = av_rescale_rnd(timestamp, AV_TIME_BASE, stream_index >= 0 ?
734  s->streams[stream_index]->time_base.den :
736  AV_ROUND_DOWN : AV_ROUND_UP);
737  if (s->duration < c->seek_timestamp) {
739  return AVERROR(EIO);
740  }
741 
742  ret = AVERROR(EIO);
743  for (i = 0; i < c->n_variants; i++) {
744  /* Reset reading */
745  struct variant *var = c->variants[i];
746  int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
747  0 : c->first_timestamp;
748  if (var->input) {
749  ffurl_close(var->input);
750  var->input = NULL;
751  }
752  av_free_packet(&var->pkt);
753  reset_packet(&var->pkt);
754  var->pb.eof_reached = 0;
755  /* Clear any buffered data */
756  var->pb.buf_end = var->pb.buf_ptr = var->pb.buffer;
757  /* Reset the pos, to let the mpegts demuxer know we've seeked. */
758  var->pb.pos = 0;
759 
760  /* Locate the segment that contains the target timestamp */
761  for (j = 0; j < var->n_segments; j++) {
762  if (timestamp >= pos &&
763  timestamp < pos + var->segments[j]->duration) {
764  var->cur_seq_no = var->start_seq_no + j;
765  ret = 0;
766  break;
767  }
768  pos += var->segments[j]->duration;
769  }
770  if (ret)
772  }
773  return ret;
774 }
775 
776 static int hls_probe(AVProbeData *p)
777 {
778  /* Require #EXTM3U at the start, and either one of the ones below
779  * somewhere for a proper match. */
780  if (strncmp(p->buf, "#EXTM3U", 7))
781  return 0;
782  if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
783  strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
784  strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
785  return AVPROBE_SCORE_MAX;
786  return 0;
787 }
788 
790  .name = "hls,applehttp",
791  .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
792  .priv_data_size = sizeof(HLSContext),
798 };
int needed
Definition: hls.c:88
void ff_make_absolute_url(char *buf, int size, const char *base, const char *rel)
Definition: url.c:80
Bytestream IO Context.
Definition: avio.h:68
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:54
int bandwidth
Definition: hls.c:72
URLContext * input
Definition: hls.c:76
int cur_needed
Definition: hls.c:88
void av_free_packet(AVPacket *pkt)
Free a packet.
Definition: avpacket.c:243
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1163
char key_url[MAX_URL_SIZE]
Definition: hls.c:92
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:525
int64_t av_rescale_rnd(int64_t a, int64_t b, int64_t c, enum AVRounding) av_const
Rescale a 64-bit integer with specified rounding.
Definition: mathematics.c:61
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:129
int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options)
Open an input stream and read the header.
Definition: utils.c:247
int avio_close(AVIOContext *s)
Close the resource accessed by the AVIOContext s and free it.
Definition: aviobuf.c:800
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:2821
int av_usleep(unsigned usec)
Sleep for a period of time.
Definition: time.c:54
static int read_seek(AVFormatContext *ctx, int stream_index, int64_t timestamp, int flags)
Definition: libcdio.c:153
int ffurl_connect(URLContext *uc, AVDictionary **options)
Connect an URLContext that has been allocated by ffurl_alloc.
Definition: avio.c:159
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:718
int finished
Definition: hls.c:83
int num
numerator
Definition: rational.h:44
uint8_t pi<< 24) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_U8, uint8_t,(*(constuint8_t *) pi-0x80)*(1.0f/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_U8, uint8_t,(*(constuint8_t *) pi-0x80)*(1.0/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S16, int16_t,(*(constint16_t *) pi >>8)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S16, int16_t,*(constint16_t *) pi *(1.0f/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S16, int16_t,*(constint16_t *) pi *(1.0/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S32, int32_t,(*(constint32_t *) pi >>24)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S32, int32_t,*(constint32_t *) pi *(1.0f/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S32, int32_t,*(constint32_t *) pi *(1.0/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_FLT, float, av_clip_uint8(lrintf(*(constfloat *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_FLT, float, av_clip_int16(lrintf(*(constfloat *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_FLT, float, av_clipl_int32(llrintf(*(constfloat *) pi *(1U<< 31)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_DBL, double, av_clip_uint8(lrint(*(constdouble *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_DBL, double, av_clip_int16(lrint(*(constdouble *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_DBL, double, av_clipl_int32(llrint(*(constdouble *) pi *(1U<< 31))))#defineSET_CONV_FUNC_GROUP(ofmt, ifmt) staticvoidset_generic_function(AudioConvert *ac){}voidff_audio_convert_free(AudioConvert **ac){if(!*ac) return;ff_dither_free(&(*ac) ->dc);av_freep(ac);}AudioConvert *ff_audio_convert_alloc(AVAudioResampleContext *avr, enumAVSampleFormatout_fmt, enumAVSampleFormatin_fmt, intchannels, intsample_rate, intapply_map){AudioConvert *ac;intin_planar, out_planar;ac=av_mallocz(sizeof(*ac));if(!ac) returnNULL;ac->avr=avr;ac->out_fmt=out_fmt;ac->in_fmt=in_fmt;ac->channels=channels;ac->apply_map=apply_map;if(avr->dither_method!=AV_RESAMPLE_DITHER_NONE &&av_get_packed_sample_fmt(out_fmt)==AV_SAMPLE_FMT_S16 &&av_get_bytes_per_sample(in_fmt)>2){ac->dc=ff_dither_alloc(avr, out_fmt, in_fmt, channels, sample_rate, apply_map);if(!ac->dc){av_free(ac);returnNULL;}returnac;}in_planar=ff_sample_fmt_is_planar(in_fmt, channels);out_planar=ff_sample_fmt_is_planar(out_fmt, channels);if(in_planar==out_planar){ac->func_type=CONV_FUNC_TYPE_FLAT;ac->planes=in_planar?ac->channels:1;}elseif(in_planar) ac->func_type=CONV_FUNC_TYPE_INTERLEAVE;elseac->func_type=CONV_FUNC_TYPE_DEINTERLEAVE;set_generic_function(ac);if(ARCH_AARCH64) ff_audio_convert_init_aarch64(ac);if(ARCH_ARM) ff_audio_convert_init_arm(ac);if(ARCH_X86) ff_audio_convert_init_x86(ac);returnac;}intff_audio_convert(AudioConvert *ac, AudioData *out, AudioData *in){intuse_generic=1;intlen=in->nb_samples;intp;if(ac->dc){av_dlog(ac->avr,"%dsamples-audio_convert:%sto%s(dithered)\n", len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt));returnff_convert_dither(ac-> in
void av_log(void *avcl, int level, const char *fmt,...) av_printf_format(3
Send the specified message to the log if the level is less than or equal to the current av_log_level...
int n_segments
Definition: hls.c:86
int64_t last_load_time
Definition: hls.c:90
discard all
Definition: avcodec.h:568
char url[MAX_URL_SIZE]
Definition: hls.c:60
int ctx_flags
Flags signalling stream properties.
Definition: avformat.h:971
static void reset_packet(AVPacket *pkt)
Definition: hls.c:149
int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src)
Copy the settings of the source AVCodecContext into the destination AVCodecContext.
Definition: options.c:154
static int64_t duration
Definition: avplay.c:246
void av_freep(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc() and set the pointer ...
Definition: mem.c:198
AVDictionary * metadata
Definition: avformat.h:771
Format I/O context.
Definition: avformat.h:922
#define MAX_URL_SIZE
Definition: internal.h:27
unsigned char * buffer
Start of the buffer.
Definition: avio.h:82
uint8_t iv[16]
Definition: hls.c:63
int avio_open2(AVIOContext **s, const char *url, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options)
Create and initialize a AVIOContext for accessing the resource indicated by url.
Definition: aviobuf.c:783
uint8_t
Round toward +infinity.
Definition: mathematics.h:53
int n_variants
Definition: hls.c:97
int start_seq_no
Definition: hls.c:85
#define AVSEEK_FLAG_BYTE
seeking based on position in bytes
Definition: avformat.h:1610
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:397
int id
Format-specific stream ID.
Definition: avformat.h:706
AVInputFormat ff_hls_demuxer
Definition: hls.c:789
static int read_data(void *opaque, uint8_t *buf, int buf_size)
Definition: hls.c:379
static int flags
Definition: log.c:44
int64_t seek_timestamp
Definition: hls.c:103
#define AVERROR_EOF
End of file.
Definition: error.h:51
static av_cold int read_close(AVFormatContext *ctx)
Definition: libcdio.c:145
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:2518
int end_of_segment
Definition: hls.c:100
char method[10]
Definition: hls.c:183
#define AV_WB32(p, d)
Definition: intreadwrite.h:239
static int open_input(struct variant *var)
Definition: hls.c:332
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1019
struct variant ** variants
Definition: hls.c:98
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq) av_const
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:129
Callback for checking whether to abort blocking functions.
Definition: avio.h:51
struct segment ** segments
Definition: hls.c:87
int index
Definition: hls.c:78
int ffurl_alloc(URLContext **puc, const char *filename, int flags, const AVIOInterruptCB *int_cb)
Create a URLContext for accessing to the resource indicated by url, but do not initiate the connectio...
Definition: avio.c:183
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:123
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:186
AVIOInterruptCB * interrupt_callback
Definition: hls.c:105
char bandwidth[20]
Definition: hls.c:169
static struct variant * new_variant(HLSContext *c, int bandwidth, const char *url, const char *base)
Definition: hls.c:155
static void handle_key_args(struct key_info *info, const char *key, int key_len, char **dest, int *dest_len)
Definition: hls.c:187
void * priv_data
Format private data.
Definition: avformat.h:950
char filename[1024]
input or output filename
Definition: avformat.h:998
#define AVERROR(e)
Definition: error.h:43
#define AVIO_FLAG_READ
read-only
Definition: avio.h:292
AVIOContext pb
Definition: hls.c:74
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:150
Definition: graph2dot.c:49
void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
int first_packet
Definition: hls.c:101
int av_isspace(int c)
Locale-independent conversion of ASCII isspace.
Definition: avstring.c:225
New fields can be added to the end with minor version bumps.
Definition: avformat.h:892
size_t av_strlcpy(char *dst, const char *src, size_t size)
Copy the string src to dst, but no more than size - 1 bytes, and null-terminate dst.
Definition: avstring.c:81
unsigned char * buf_end
End of the data, may be less than buffer+buffer_size if the read function returned less data than req...
Definition: avio.h:85
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:979
int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b)
Compare 2 timestamps each in its own timebases.
Definition: mathematics.c:134
Definition: hls.c:58
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:978
char url[MAX_URL_SIZE]
Definition: hls.c:73
int64_t av_gettime(void)
Get the current time in microseconds.
Definition: time.c:37
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:117
#define dynarray_add(tab, nb_ptr, elem)
Definition: internal.h:64
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:234
void(* ff_parse_key_val_cb)(void *context, const char *key, int key_len, char **dest, int *dest_len)
Callback function type for ff_parse_key_value.
Definition: internal.h:172
#define AV_OPT_SEARCH_CHILDREN
Search in possible children of the given object first.
Definition: opt.h:383
static int read_probe(AVProbeData *pd)
Definition: jvdec.c:55
#define AVSEEK_FLAG_ANY
seek to any frame, even non-keyframes
Definition: avformat.h:1611
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:990
int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt, const char *filename, void *logctx, unsigned int offset, unsigned int max_probe_size)
Probe a bytestream to determine the input format.
Definition: format.c:238
void * av_malloc(size_t size) av_malloc_attrib 1(1)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:62
Definition: hls.c:96
static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition: hls.c:613
int64_t target_duration
Definition: hls.c:84
Definition: hls.c:181
AVProgram * av_new_program(AVFormatContext *s, int id)
Definition: utils.c:2570
unsigned char * buf_ptr
Current position in the buffer.
Definition: avio.h:84
int ff_get_line(AVIOContext *s, char *buf, int maxlen)
Read a whole line of text from AVIOContext.
Definition: aviobuf.c:603
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
Definition: error.h:52
uint8_t * read_buffer
Definition: hls.c:75
static int read_header(FFV1Context *f)
Definition: ffv1dec.c:544
enum KeyType key_type
Definition: hls.c:62
static void free_segment_list(struct variant *var)
Definition: hls.c:116
Stream structure.
Definition: avformat.h:699
static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
Definition: hls.c:108
NULL
Definition: eval.c:55
int64_t first_timestamp
Definition: hls.c:102
#define AV_LOG_INFO
Standard information.
Definition: log.h:134
int ff_check_interrupt(AVIOInterruptCB *cb)
Check if the user has requested to interrup a blocking function associated with cb.
Definition: avio.c:381
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:240
#define AVFMTCTX_NOHEADER
signal that no header is present (streams are added dynamically)
Definition: avformat.h:901
int seek_flags
Definition: hls.c:104
static int hls_read_header(AVFormatContext *s)
Definition: hls.c:452
AVFormatContext * parent
Definition: hls.c:77
AVIOContext * pb
I/O context.
Definition: avformat.h:964
Definition: url.h:41
static int read_packet(AVFormatContext *ctx, AVPacket *pkt)
Definition: libcdio.c:114
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:68
#define AVSEEK_FLAG_BACKWARD
Definition: avformat.h:1609
void * priv_data
Definition: url.h:44
uint8_t * data
Definition: avcodec.h:973
char key[MAX_URL_SIZE]
Definition: hls.c:61
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:2445
This structure contains the data a format has to probe a file.
Definition: avformat.h:395
int ff_hex_to_data(uint8_t *data, const char *p)
Parse a string of hexadecimal strings.
Definition: utils.c:2793
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
Return the next frame of a stream.
Definition: utils.c:989
Round toward -infinity.
Definition: mathematics.h:52
AVDictionary * metadata
Definition: avformat.h:898
static void handle_variant_args(struct variant_info *info, const char *key, int key_len, char **dest, int *dest_len)
Definition: hls.c:172
KeyType
Definition: hls.c:53
int ffurl_close(URLContext *h)
Close the resource accessed by the URLContext h, and free the memory used by it.
Definition: avio.c:297
static int recheck_discard_flags(AVFormatContext *s, int first)
Definition: hls.c:578
void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf, void *context)
Parse a string with comma-separated key=value pairs.
Definition: utils.c:2844
#define AVPROBE_SCORE_MAX
maximum score
Definition: avformat.h:404
char iv[35]
Definition: hls.c:184
int av_strstart(const char *str, const char *pfx, const char **ptr)
Return non-zero if pfx is a prefix of str.
Definition: avstring.c:32
char uri[MAX_URL_SIZE]
Definition: hls.c:182
#define INITIAL_BUFFER_SIZE
Definition: hls.c:39
int ffio_init_context(AVIOContext *s, unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int(*read_packet)(void *opaque, uint8_t *buf, int buf_size), int(*write_packet)(void *opaque, uint8_t *buf, int buf_size), int64_t(*seek)(void *opaque, int64_t offset, int whence))
Definition: aviobuf.c:70
int ffurl_open(URLContext **puc, const char *filename, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options)
Create an URLContext for accessing to the resource indicated by url, and open it. ...
Definition: avio.c:211
int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
Read packets of a media file to get stream information.
Definition: utils.c:2052
int64_t start_time
Decoding: pts of the first frame of the stream, in stream time base.
Definition: avformat.h:749
static int parse_playlist(HLSContext *c, const char *url, struct variant *var, AVIOContext *in)
Definition: hls.c:202
int cur_seq_no
Definition: hls.c:99
int ffurl_read_complete(URLContext *h, unsigned char *buf, int size)
Read as many bytes as possible (up to size), calling the read function multiple times if necessary...
Definition: avio.c:269
Main libavformat public API header.
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition: options.c:98
int stream_offset
Definition: hls.c:81
int64_t pos
position in the file of the current buffer
Definition: avio.h:94
int pts_wrap_bits
number of bits in pts (used for wrapping control)
Definition: avformat.h:847
void av_init_packet(AVPacket *pkt)
Initialize optional fields of a packet with default values.
Definition: avpacket.c:47
int den
denominator
Definition: rational.h:45
int cur_seq_no
Definition: hls.c:89
void avformat_close_input(AVFormatContext **s)
Close an opened input AVFormatContext.
Definition: utils.c:2496
static int hls_probe(AVProbeData *p)
Definition: hls.c:776
static int hls_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
Definition: hls.c:718
int av_opt_get(void *obj, const char *name, int search_flags, uint8_t **out_val)
Definition: opt.c:328
int eof_reached
true if eof reached
Definition: avio.h:96
int len
Definition: hls.c:71
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:972
int64_t duration
Duration of the stream, in AV_TIME_BASE fractional seconds.
Definition: avformat.h:1017
unbuffered private I/O API
uint8_t key[16]
Definition: hls.c:93
int stream_index
Definition: avcodec.h:975
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:741
AVPacket pkt
Definition: hls.c:80
int64_t duration
Definition: hls.c:59
static void free_variant_list(HLSContext *c)
Definition: hls.c:125
enum AVDiscard discard
Selects which packets can be discarded at will and do not need to be demuxed.
Definition: avformat.h:762
static int hls_close(AVFormatContext *s)
Definition: hls.c:710
char * ff_data_to_hex(char *buf, const uint8_t *src, int size, int lowercase)
Definition: utils.c:2772
This structure stores compressed data.
Definition: avcodec.h:950
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition: opt.c:210
int ffurl_read(URLContext *h, unsigned char *buf, int size)
Read up to size bytes from the resource accessed by h, and store the read bytes in buf...
Definition: avio.c:262
Definition: hls.c:54
for(j=16;j >0;--j)
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:228
void * av_mallocz(size_t size) av_malloc_attrib 1(1)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:205
AVFormatContext * ctx
Definition: hls.c:79