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 <float.h>
23 #include <stdint.h>
24 
25 #include "libavutil/mathematics.h"
26 #include "libavutil/parseutils.h"
27 #include "libavutil/avstring.h"
28 #include "libavutil/opt.h"
29 #include "libavutil/log.h"
30 
31 #include "avformat.h"
32 #include "internal.h"
33 
34 typedef struct HLSSegment {
35  char filename[1024];
36  double duration; /* in seconds */
37  int64_t pos;
38  int64_t size;
39 
40  struct HLSSegment *next;
41 } HLSSegment;
42 
43 typedef enum HLSFlags {
44  // Generate a single media file and use byte ranges in the playlist.
45  HLS_SINGLE_FILE = (1 << 0),
46 } HLSFlags;
47 
48 typedef struct HLSContext {
49  const AVClass *class; // Class for private options.
50  unsigned number;
51  int64_t sequence;
52  int64_t start_sequence;
54 
56 
57  float time; // Set by a private option.
58  int max_nb_segments; // Set by a private option.
59  int wrap; // Set by a private option.
60  uint32_t flags; // enum HLSFlags
61 
62  int64_t recording_time;
63  int has_video;
64  int64_t start_pts;
65  int64_t end_pts;
66  double duration; // last segment duration computed so far, in seconds
67  int64_t start_pos; // last segment starting position
68  int64_t size; // last segment size
70 
73 
74  char *basename;
75  char *baseurl;
78 
80 } HLSContext;
81 
83 {
84  HLSContext *hls = s->priv_data;
85  AVFormatContext *oc;
86  int i;
87 
88  hls->avf = oc = avformat_alloc_context();
89  if (!oc)
90  return AVERROR(ENOMEM);
91 
92  oc->oformat = hls->oformat;
94  av_dict_copy(&oc->metadata, s->metadata, 0);
95 
96  for (i = 0; i < s->nb_streams; i++) {
97  AVStream *st;
98  if (!(st = avformat_new_stream(oc, NULL)))
99  return AVERROR(ENOMEM);
102  }
103  hls->start_pos = 0;
104 
105  return 0;
106 }
107 
108 /* Create a new segment and append it to the segment list */
109 static int hls_append_segment(HLSContext *hls, double duration, int64_t pos,
110  int64_t size)
111 {
112  HLSSegment *en = av_malloc(sizeof(*en));
113 
114  if (!en)
115  return AVERROR(ENOMEM);
116 
117  av_strlcpy(en->filename, av_basename(hls->avf->filename), sizeof(en->filename));
118 
119  en->duration = duration;
120  en->pos = pos;
121  en->size = size;
122  en->next = NULL;
123 
124  if (!hls->segments)
125  hls->segments = en;
126  else
127  hls->last_segment->next = en;
128 
129  hls->last_segment = en;
130 
131  if (hls->max_nb_segments && hls->nb_entries >= hls->max_nb_segments) {
132  en = hls->segments;
133  hls->segments = en->next;
134  av_free(en);
135  } else
136  hls->nb_entries++;
137 
138  hls->sequence++;
139 
140  return 0;
141 }
142 
143 static void hls_free_segments(HLSContext *hls)
144 {
145  HLSSegment *p = hls->segments, *en;
146 
147  while(p) {
148  en = p;
149  p = p->next;
150  av_free(en);
151  }
152 }
153 
154 static int hls_window(AVFormatContext *s, int last)
155 {
156  HLSContext *hls = s->priv_data;
157  HLSSegment *en;
158  int target_duration = 0;
159  int ret = 0;
160  int64_t sequence = FFMAX(hls->start_sequence, hls->sequence - hls->nb_entries);
161  int version = hls->flags & HLS_SINGLE_FILE ? 4 : 3;
162 
163  if ((ret = avio_open2(&hls->pb, s->filename, AVIO_FLAG_WRITE,
164  &s->interrupt_callback, NULL)) < 0)
165  goto fail;
166 
167  for (en = hls->segments; en; en = en->next) {
168  if (target_duration < en->duration)
169  target_duration = ceil(en->duration);
170  }
171 
172  avio_printf(hls->pb, "#EXTM3U\n");
173  avio_printf(hls->pb, "#EXT-X-VERSION:%d\n", version);
174  avio_printf(hls->pb, "#EXT-X-TARGETDURATION:%d\n", target_duration);
175  avio_printf(hls->pb, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
176 
177  av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%"PRId64"\n",
178  sequence);
179 
180  for (en = hls->segments; en; en = en->next) {
181  avio_printf(hls->pb, "#EXTINF:%f,\n", en->duration);
182  if (hls->flags & HLS_SINGLE_FILE)
183  avio_printf(hls->pb, "#EXT-X-BYTERANGE:%"PRIi64"@%"PRIi64"\n",
184  en->size, en->pos);
185  if (hls->baseurl)
186  avio_printf(hls->pb, "%s", hls->baseurl);
187  avio_printf(hls->pb, "%s\n", en->filename);
188  }
189 
190  if (last)
191  avio_printf(hls->pb, "#EXT-X-ENDLIST\n");
192 
193 fail:
194  avio_closep(&hls->pb);
195  return ret;
196 }
197 
199 {
200  HLSContext *c = s->priv_data;
201  AVFormatContext *oc = c->avf;
202  int err = 0;
203 
204  if (c->flags & HLS_SINGLE_FILE)
205  av_strlcpy(oc->filename, c->basename,
206  sizeof(oc->filename));
207  else
208  if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
209  c->basename, c->wrap ? c->sequence % c->wrap : c->sequence) < 0) {
210  av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", c->basename);
211  return AVERROR(EINVAL);
212  }
213  c->number++;
214 
215  if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
216  &s->interrupt_callback, NULL)) < 0)
217  return err;
218 
219  if (oc->oformat->priv_class && oc->priv_data)
220  av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
221 
222  return 0;
223 }
224 
226 {
227  HLSContext *hls = s->priv_data;
228  int ret, i;
229  char *p;
230  const char *pattern = "%d.ts";
231  AVDictionary *options = NULL;
232  int basename_size = strlen(s->filename) + strlen(pattern) + 1;
233 
234  hls->sequence = hls->start_sequence;
235  hls->recording_time = hls->time * AV_TIME_BASE;
236  hls->start_pts = AV_NOPTS_VALUE;
237 
238  if (hls->flags & HLS_SINGLE_FILE)
239  pattern = ".ts";
240 
241  if (hls->format_options_str) {
242  ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
243  if (ret < 0) {
244  av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n", hls->format_options_str);
245  goto fail;
246  }
247  }
248 
249  for (i = 0; i < s->nb_streams; i++)
250  hls->has_video +=
252 
253  if (hls->has_video > 1)
255  "More than a single video stream present, "
256  "expect issues decoding it.\n");
257 
258  hls->oformat = av_guess_format("mpegts", NULL, NULL);
259 
260  if (!hls->oformat) {
262  goto fail;
263  }
264 
265  hls->basename = av_malloc(basename_size);
266 
267  if (!hls->basename) {
268  ret = AVERROR(ENOMEM);
269  goto fail;
270  }
271 
272  strcpy(hls->basename, s->filename);
273 
274  p = strrchr(hls->basename, '.');
275 
276  if (p)
277  *p = '\0';
278 
279  av_strlcat(hls->basename, pattern, basename_size);
280 
281  if ((ret = hls_mux_init(s)) < 0)
282  goto fail;
283 
284  if ((ret = hls_start(s)) < 0)
285  goto fail;
286 
287  av_dict_copy(&options, hls->format_options, 0);
288  ret = avformat_write_header(hls->avf, &options);
289  if (av_dict_count(options)) {
290  av_log(s, AV_LOG_ERROR, "Some of provided format options in '%s' are not recognized\n", hls->format_options_str);
291  ret = AVERROR(EINVAL);
292  goto fail;
293  }
294 
295 fail:
296 
297  av_dict_free(&options);
298  if (ret) {
299  av_free(hls->basename);
300  if (hls->avf)
302  }
303  return ret;
304 }
305 
307 {
308  HLSContext *hls = s->priv_data;
309  AVFormatContext *oc = hls->avf;
310  AVStream *st = s->streams[pkt->stream_index];
311  int64_t end_pts = hls->recording_time * hls->number;
312  int is_ref_pkt = 1;
313  int ret, can_split = 1;
314 
315  if (hls->start_pts == AV_NOPTS_VALUE) {
316  hls->start_pts = pkt->pts;
317  hls->end_pts = pkt->pts;
318  }
319 
320  if (hls->has_video) {
321  can_split = st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
322  pkt->flags & AV_PKT_FLAG_KEY;
323  is_ref_pkt = st->codec->codec_type == AVMEDIA_TYPE_VIDEO;
324  }
325  if (pkt->pts == AV_NOPTS_VALUE)
326  is_ref_pkt = can_split = 0;
327 
328  if (is_ref_pkt)
329  hls->duration = (double)(pkt->pts - hls->end_pts)
330  * st->time_base.num / st->time_base.den;
331 
332  if (can_split && av_compare_ts(pkt->pts - hls->start_pts, st->time_base,
333  end_pts, AV_TIME_BASE_Q) >= 0) {
334  int64_t new_start_pos;
335  av_write_frame(oc, NULL); /* Flush any buffered data */
336 
337  new_start_pos = avio_tell(hls->avf->pb);
338  hls->size = new_start_pos - hls->start_pos;
339  ret = hls_append_segment(hls, hls->duration, hls->start_pos, hls->size);
340  hls->start_pos = new_start_pos;
341  if (ret)
342  return ret;
343 
344  hls->end_pts = pkt->pts;
345  hls->duration = 0;
346 
347  if (hls->flags & HLS_SINGLE_FILE) {
348  if (hls->avf->oformat->priv_class && hls->avf->priv_data)
349  av_opt_set(hls->avf->priv_data, "mpegts_flags", "resend_headers", 0);
350  hls->number++;
351  } else {
352  avio_close(oc->pb);
353 
354  ret = hls_start(s);
355  }
356 
357  if (ret)
358  return ret;
359 
360  oc = hls->avf;
361 
362  if ((ret = hls_window(s, 0)) < 0)
363  return ret;
364  }
365 
366  ret = ff_write_chained(oc, pkt->stream_index, pkt, s, 0);
367 
368  return ret;
369 }
370 
372 {
373  HLSContext *hls = s->priv_data;
374  AVFormatContext *oc = hls->avf;
375 
376  av_write_trailer(oc);
377  hls->size = avio_tell(hls->avf->pb) - hls->start_pos;
378  avio_closep(&oc->pb);
380  av_free(hls->basename);
381  hls_append_segment(hls, hls->duration, hls->start_pos, hls->size);
382  hls_window(s, 1);
383 
384  hls_free_segments(hls);
385  avio_close(hls->pb);
386  return 0;
387 }
388 
389 #define OFFSET(x) offsetof(HLSContext, x)
390 #define E AV_OPT_FLAG_ENCODING_PARAM
391 static const AVOption options[] = {
392  {"start_number", "set first number in the sequence", OFFSET(start_sequence),AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, E},
393  {"hls_time", "set segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E},
394  {"hls_list_size", "set maximum number of playlist entries", OFFSET(max_nb_segments), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
395  {"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},
396  {"hls_wrap", "set number after which the index wraps", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
397  {"hls_base_url", "url to prepend to each playlist entry", OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
398  {"hls_flags", "set flags affecting HLS playlist and media file generation", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0 }, 0, UINT_MAX, E, "flags"},
399  {"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"},
400 
401  { NULL },
402 };
403 
404 static const AVClass hls_class = {
405  .class_name = "hls muxer",
406  .item_name = av_default_item_name,
407  .option = options,
408  .version = LIBAVUTIL_VERSION_INT,
409 };
410 
411 
413  .name = "hls",
414  .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
415  .extensions = "m3u8",
416  .priv_data_size = sizeof(HLSContext),
417  .audio_codec = AV_CODEC_ID_AAC,
418  .video_codec = AV_CODEC_ID_H264,
423  .priv_class = &hls_class,
424 };