FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
hlsenc.c
Go to the documentation of this file.
1 /*
2  * Apple HTTP Live Streaming segmenter
3  * Copyright (c) 2012, Luca Barbato
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 #include "config.h"
23 #include <float.h>
24 #include <stdint.h>
25 #if HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28 
29 #include "libavutil/avassert.h"
30 #include "libavutil/mathematics.h"
31 #include "libavutil/parseutils.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/log.h"
35 
36 #include "avformat.h"
37 #include "internal.h"
38 #include "os_support.h"
39 
40 typedef struct HLSSegment {
41  char filename[1024];
42  double duration; /* in seconds */
43  int64_t pos;
44  int64_t size;
45 
46  struct HLSSegment *next;
47 } HLSSegment;
48 
49 typedef enum HLSFlags {
50  // Generate a single media file and use byte ranges in the playlist.
51  HLS_SINGLE_FILE = (1 << 0),
52  HLS_DELETE_SEGMENTS = (1 << 1),
53 } HLSFlags;
54 
55 typedef struct HLSContext {
56  const AVClass *class; // Class for private options.
57  unsigned number;
58  int64_t sequence;
59  int64_t start_sequence;
61 
63 
64  float time; // Set by a private option.
65  int max_nb_segments; // Set by a private option.
66  int wrap; // Set by a private option.
67  uint32_t flags; // enum HLSFlags
69 
71  int64_t recording_time;
72  int has_video;
73  int64_t start_pts;
74  int64_t end_pts;
75  double duration; // last segment duration computed so far, in seconds
76  int64_t start_pos; // last segment starting position
77  int64_t size; // last segment size
79 
83 
84  char *basename;
85  char *baseurl;
88 } HLSContext;
89 
91 
92  HLSSegment *segment, *previous_segment = NULL;
93  float playlist_duration = 0.0f;
94  int ret = 0, path_size;
95  char *dirname = NULL, *p, *path;
96 
97  segment = hls->segments;
98  while (segment) {
99  playlist_duration += segment->duration;
100  segment = segment->next;
101  }
102 
103  segment = hls->old_segments;
104  while (segment) {
105  playlist_duration -= segment->duration;
106  previous_segment = segment;
107  segment = previous_segment->next;
108  if (playlist_duration <= -previous_segment->duration) {
109  previous_segment->next = NULL;
110  break;
111  }
112  }
113 
114  if (segment) {
115  if (hls->segment_filename) {
116  dirname = av_strdup(hls->segment_filename);
117  } else {
118  dirname = av_strdup(hls->avf->filename);
119  }
120  if (!dirname) {
121  ret = AVERROR(ENOMEM);
122  goto fail;
123  }
124  p = (char *)av_basename(dirname);
125  *p = '\0';
126  }
127 
128  while (segment) {
129  av_log(hls, AV_LOG_DEBUG, "deleting old segment %s\n",
130  segment->filename);
131  path_size = strlen(dirname) + strlen(segment->filename) + 1;
132  path = av_malloc(path_size);
133  if (!path) {
134  ret = AVERROR(ENOMEM);
135  goto fail;
136  }
137  av_strlcpy(path, dirname, path_size);
138  av_strlcat(path, segment->filename, path_size);
139  if (unlink(path) < 0) {
140  av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
141  path, strerror(errno));
142  }
143  av_free(path);
144  previous_segment = segment;
145  segment = previous_segment->next;
146  av_free(previous_segment);
147  }
148 
149 fail:
150  av_free(dirname);
151 
152  return ret;
153 }
154 
156 {
157  HLSContext *hls = s->priv_data;
158  AVFormatContext *oc;
159  int i, ret;
160 
161  ret = avformat_alloc_output_context2(&hls->avf, hls->oformat, NULL, NULL);
162  if (ret < 0)
163  return ret;
164  oc = hls->avf;
165 
166  oc->oformat = hls->oformat;
168  oc->max_delay = s->max_delay;
169  av_dict_copy(&oc->metadata, s->metadata, 0);
170 
171  for (i = 0; i < s->nb_streams; i++) {
172  AVStream *st;
173  if (!(st = avformat_new_stream(oc, NULL)))
174  return AVERROR(ENOMEM);
177  st->time_base = s->streams[i]->time_base;
178  }
179  hls->start_pos = 0;
180 
181  return 0;
182 }
183 
184 /* Create a new segment and append it to the segment list */
185 static int hls_append_segment(HLSContext *hls, double duration, int64_t pos,
186  int64_t size)
187 {
188  HLSSegment *en = av_malloc(sizeof(*en));
189  int ret;
190 
191  if (!en)
192  return AVERROR(ENOMEM);
193 
194  av_strlcpy(en->filename, av_basename(hls->avf->filename), sizeof(en->filename));
195 
196  en->duration = duration;
197  en->pos = pos;
198  en->size = size;
199  en->next = NULL;
200 
201  if (!hls->segments)
202  hls->segments = en;
203  else
204  hls->last_segment->next = en;
205 
206  hls->last_segment = en;
207 
208  if (hls->max_nb_segments && hls->nb_entries >= hls->max_nb_segments) {
209  en = hls->segments;
210  hls->segments = en->next;
211  if (en && hls->flags & HLS_DELETE_SEGMENTS &&
212  !(hls->flags & HLS_SINGLE_FILE || hls->wrap)) {
213  en->next = hls->old_segments;
214  hls->old_segments = en;
215  if ((ret = hls_delete_old_segments(hls)) < 0)
216  return ret;
217  } else
218  av_free(en);
219  } else
220  hls->nb_entries++;
221 
222  hls->sequence++;
223 
224  return 0;
225 }
226 
228 {
229  HLSSegment *en;
230 
231  while(p) {
232  en = p;
233  p = p->next;
234  av_free(en);
235  }
236 }
237 
238 static int hls_window(AVFormatContext *s, int last)
239 {
240  HLSContext *hls = s->priv_data;
241  HLSSegment *en;
242  int target_duration = 0;
243  int ret = 0;
244  AVIOContext *out = NULL;
245  char temp_filename[1024];
246  int64_t sequence = FFMAX(hls->start_sequence, hls->sequence - hls->nb_entries);
247  int version = hls->flags & HLS_SINGLE_FILE ? 4 : 3;
248  const char *proto = avio_find_protocol_name(s->filename);
249  int use_rename = proto && !strcmp(proto, "file");
250  static unsigned warned_non_file;
251 
252  if (!use_rename && !warned_non_file++)
253  av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporarly partial files\n");
254 
255  snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->filename);
256  if ((ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE,
257  &s->interrupt_callback, NULL)) < 0)
258  goto fail;
259 
260  for (en = hls->segments; en; en = en->next) {
261  if (target_duration < en->duration)
262  target_duration = ceil(en->duration);
263  }
264 
265  avio_printf(out, "#EXTM3U\n");
266  avio_printf(out, "#EXT-X-VERSION:%d\n", version);
267  if (hls->allowcache == 0 || hls->allowcache == 1) {
268  avio_printf(out, "#EXT-X-ALLOW-CACHE:%s\n", hls->allowcache == 0 ? "NO" : "YES");
269  }
270  avio_printf(out, "#EXT-X-TARGETDURATION:%d\n", target_duration);
271  avio_printf(out, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
272 
273  av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%"PRId64"\n",
274  sequence);
275 
276  for (en = hls->segments; en; en = en->next) {
277  avio_printf(out, "#EXTINF:%f,\n", en->duration);
278  if (hls->flags & HLS_SINGLE_FILE)
279  avio_printf(out, "#EXT-X-BYTERANGE:%"PRIi64"@%"PRIi64"\n",
280  en->size, en->pos);
281  if (hls->baseurl)
282  avio_printf(out, "%s", hls->baseurl);
283  avio_printf(out, "%s\n", en->filename);
284  }
285 
286  if (last)
287  avio_printf(out, "#EXT-X-ENDLIST\n");
288 
289 fail:
290  avio_closep(&out);
291  if (ret >= 0 && use_rename)
292  ff_rename(temp_filename, s->filename, s);
293  return ret;
294 }
295 
297 {
298  HLSContext *c = s->priv_data;
299  AVFormatContext *oc = c->avf;
300  int err = 0;
301 
302  if (c->flags & HLS_SINGLE_FILE)
303  av_strlcpy(oc->filename, c->basename,
304  sizeof(oc->filename));
305  else
306  if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
307  c->basename, c->wrap ? c->sequence % c->wrap : c->sequence) < 0) {
308  av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", c->basename);
309  return AVERROR(EINVAL);
310  }
311  c->number++;
312 
313  if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
314  &s->interrupt_callback, NULL)) < 0)
315  return err;
316 
317  if (oc->oformat->priv_class && oc->priv_data)
318  av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
319 
320  return 0;
321 }
322 
324 {
325  HLSContext *hls = s->priv_data;
326  int ret, i;
327  char *p;
328  const char *pattern = "%d.ts";
330  int basename_size;
331 
332  hls->sequence = hls->start_sequence;
333  hls->recording_time = hls->time * AV_TIME_BASE;
334  hls->start_pts = AV_NOPTS_VALUE;
335 
336  if (hls->format_options_str) {
337  ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
338  if (ret < 0) {
339  av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n", hls->format_options_str);
340  goto fail;
341  }
342  }
343 
344  for (i = 0; i < s->nb_streams; i++)
345  hls->has_video +=
347 
348  if (hls->has_video > 1)
350  "More than a single video stream present, "
351  "expect issues decoding it.\n");
352 
353  hls->oformat = av_guess_format("mpegts", NULL, NULL);
354 
355  if (!hls->oformat) {
357  goto fail;
358  }
359 
360  if (hls->segment_filename) {
361  hls->basename = av_strdup(hls->segment_filename);
362  if (!hls->basename) {
363  ret = AVERROR(ENOMEM);
364  goto fail;
365  }
366  } else {
367  if (hls->flags & HLS_SINGLE_FILE)
368  pattern = ".ts";
369 
370  basename_size = strlen(s->filename) + strlen(pattern) + 1;
371  hls->basename = av_malloc(basename_size);
372  if (!hls->basename) {
373  ret = AVERROR(ENOMEM);
374  goto fail;
375  }
376 
377  av_strlcpy(hls->basename, s->filename, basename_size);
378 
379  p = strrchr(hls->basename, '.');
380  if (p)
381  *p = '\0';
382  av_strlcat(hls->basename, pattern, basename_size);
383  }
384 
385  if ((ret = hls_mux_init(s)) < 0)
386  goto fail;
387 
388  if ((ret = hls_start(s)) < 0)
389  goto fail;
390 
391  av_dict_copy(&options, hls->format_options, 0);
392  ret = avformat_write_header(hls->avf, &options);
393  if (av_dict_count(options)) {
394  av_log(s, AV_LOG_ERROR, "Some of provided format options in '%s' are not recognized\n", hls->format_options_str);
395  ret = AVERROR(EINVAL);
396  goto fail;
397  }
398  av_assert0(s->nb_streams == hls->avf->nb_streams);
399  for (i = 0; i < s->nb_streams; i++) {
400  AVStream *inner_st = hls->avf->streams[i];
401  AVStream *outer_st = s->streams[i];
402  avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
403  }
404 fail:
405 
406  av_dict_free(&options);
407  if (ret < 0) {
408  av_freep(&hls->basename);
409  if (hls->avf)
411  }
412  return ret;
413 }
414 
416 {
417  HLSContext *hls = s->priv_data;
418  AVFormatContext *oc = hls->avf;
419  AVStream *st = s->streams[pkt->stream_index];
420  int64_t end_pts = hls->recording_time * hls->number;
421  int is_ref_pkt = 1;
422  int ret, can_split = 1;
423 
424  if (hls->start_pts == AV_NOPTS_VALUE) {
425  hls->start_pts = pkt->pts;
426  hls->end_pts = pkt->pts;
427  }
428 
429  if (hls->has_video) {
430  can_split = st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
431  pkt->flags & AV_PKT_FLAG_KEY;
432  is_ref_pkt = st->codec->codec_type == AVMEDIA_TYPE_VIDEO;
433  }
434  if (pkt->pts == AV_NOPTS_VALUE)
435  is_ref_pkt = can_split = 0;
436 
437  if (is_ref_pkt)
438  hls->duration = (double)(pkt->pts - hls->end_pts)
439  * st->time_base.num / st->time_base.den;
440 
441  if (can_split && av_compare_ts(pkt->pts - hls->start_pts, st->time_base,
442  end_pts, AV_TIME_BASE_Q) >= 0) {
443  int64_t new_start_pos;
444  av_write_frame(oc, NULL); /* Flush any buffered data */
445 
446  new_start_pos = avio_tell(hls->avf->pb);
447  hls->size = new_start_pos - hls->start_pos;
448  ret = hls_append_segment(hls, hls->duration, hls->start_pos, hls->size);
449  hls->start_pos = new_start_pos;
450  if (ret < 0)
451  return ret;
452 
453  hls->end_pts = pkt->pts;
454  hls->duration = 0;
455 
456  if (hls->flags & HLS_SINGLE_FILE) {
457  if (hls->avf->oformat->priv_class && hls->avf->priv_data)
458  av_opt_set(hls->avf->priv_data, "mpegts_flags", "resend_headers", 0);
459  hls->number++;
460  } else {
461  avio_closep(&oc->pb);
462 
463  ret = hls_start(s);
464  }
465 
466  if (ret < 0)
467  return ret;
468 
469  oc = hls->avf;
470 
471  if ((ret = hls_window(s, 0)) < 0)
472  return ret;
473  }
474 
475  ret = ff_write_chained(oc, pkt->stream_index, pkt, s, 0);
476 
477  return ret;
478 }
479 
481 {
482  HLSContext *hls = s->priv_data;
483  AVFormatContext *oc = hls->avf;
484 
485  av_write_trailer(oc);
486  if (oc->pb) {
487  hls->size = avio_tell(hls->avf->pb) - hls->start_pos;
488  avio_closep(&oc->pb);
489  hls_append_segment(hls, hls->duration, hls->start_pos, hls->size);
490  }
491  av_freep(&hls->basename);
493  hls->avf = NULL;
494  hls_window(s, 1);
495 
498  return 0;
499 }
500 
501 #define OFFSET(x) offsetof(HLSContext, x)
502 #define E AV_OPT_FLAG_ENCODING_PARAM
503 static const AVOption options[] = {
504  {"start_number", "set first number in the sequence", OFFSET(start_sequence),AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, E},
505  {"hls_time", "set segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E},
506  {"hls_list_size", "set maximum number of playlist entries", OFFSET(max_nb_segments), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
507  {"hls_ts_options","set hls mpegts list of options for the container format used for hls", OFFSET(format_options_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
508  {"hls_wrap", "set number after which the index wraps", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
509  {"hls_allow_cache", "explicitly set whether the client MAY (1) or MUST NOT (0) cache media segments", OFFSET(allowcache), AV_OPT_TYPE_INT, {.i64 = -1}, INT_MIN, INT_MAX, E},
510  {"hls_base_url", "url to prepend to each playlist entry", OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
511  {"hls_segment_filename", "filename template for segment files", OFFSET(segment_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
512  {"hls_flags", "set flags affecting HLS playlist and media file generation", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0 }, 0, UINT_MAX, E, "flags"},
513  {"single_file", "generate a single media file indexed with byte ranges", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_SINGLE_FILE }, 0, UINT_MAX, E, "flags"},
514  {"delete_segments", "delete segment files that are no longer part of the playlist", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_DELETE_SEGMENTS }, 0, UINT_MAX, E, "flags"},
515 
516  { NULL },
517 };
518 
519 static const AVClass hls_class = {
520  .class_name = "hls muxer",
521  .item_name = av_default_item_name,
522  .option = options,
523  .version = LIBAVUTIL_VERSION_INT,
524 };
525 
526 
528  .name = "hls",
529  .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
530  .extensions = "m3u8",
531  .priv_data_size = sizeof(HLSContext),
532  .audio_codec = AV_CODEC_ID_AAC,
533  .video_codec = AV_CODEC_ID_H264,
538  .priv_class = &hls_class,
539 };