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 
38  struct HLSSegment *next;
39 } HLSSegment;
40 
41 typedef struct HLSContext {
42  const AVClass *class; // Class for private options.
43  unsigned number;
44  int64_t sequence;
45  int64_t start_sequence;
47 
49 
50  float time; // Set by a private option.
51  int max_nb_segments; // Set by a private option.
52  int wrap; // Set by a private option.
53 
54  int64_t recording_time;
55  int has_video;
56  int64_t start_pts;
57  int64_t end_pts;
58  double duration; // last segment duration computed so far, in seconds
60 
63 
64  char *basename;
65  char *baseurl;
66 
68 } HLSContext;
69 
71 {
72  HLSContext *hls = s->priv_data;
73  AVFormatContext *oc;
74  int i;
75 
76  hls->avf = oc = avformat_alloc_context();
77  if (!oc)
78  return AVERROR(ENOMEM);
79 
80  oc->oformat = hls->oformat;
82  av_dict_copy(&oc->metadata, s->metadata, 0);
83 
84  for (i = 0; i < s->nb_streams; i++) {
85  AVStream *st;
86  if (!(st = avformat_new_stream(oc, NULL)))
87  return AVERROR(ENOMEM);
90  }
91 
92  return 0;
93 }
94 
95 /* Create a new segment and append it to the segment list */
96 static int hls_append_segment(HLSContext *hls, double duration)
97 {
98  HLSSegment *en = av_malloc(sizeof(*en));
99 
100  if (!en)
101  return AVERROR(ENOMEM);
102 
103  av_strlcpy(en->filename, av_basename(hls->avf->filename), sizeof(en->filename));
104 
105  en->duration = duration;
106  en->next = NULL;
107 
108  if (!hls->segments)
109  hls->segments = en;
110  else
111  hls->last_segment->next = en;
112 
113  hls->last_segment = en;
114 
115  if (hls->max_nb_segments && hls->nb_entries >= hls->max_nb_segments) {
116  en = hls->segments;
117  hls->segments = en->next;
118  av_free(en);
119  } else
120  hls->nb_entries++;
121 
122  hls->sequence++;
123 
124  return 0;
125 }
126 
127 static void hls_free_segments(HLSContext *hls)
128 {
129  HLSSegment *p = hls->segments, *en;
130 
131  while(p) {
132  en = p;
133  p = p->next;
134  av_free(en);
135  }
136 }
137 
138 static int hls_window(AVFormatContext *s, int last)
139 {
140  HLSContext *hls = s->priv_data;
141  HLSSegment *en;
142  int target_duration = 0;
143  int ret = 0;
144  int64_t sequence = FFMAX(hls->start_sequence, hls->sequence - hls->nb_entries);
145 
146  if ((ret = avio_open2(&hls->pb, s->filename, AVIO_FLAG_WRITE,
147  &s->interrupt_callback, NULL)) < 0)
148  goto fail;
149 
150  for (en = hls->segments; en; en = en->next) {
151  if (target_duration < en->duration)
152  target_duration = ceil(en->duration);
153  }
154 
155  avio_printf(hls->pb, "#EXTM3U\n");
156  avio_printf(hls->pb, "#EXT-X-VERSION:3\n");
157  avio_printf(hls->pb, "#EXT-X-TARGETDURATION:%d\n", target_duration);
158  avio_printf(hls->pb, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
159 
160  av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%"PRId64"\n",
161  sequence);
162 
163  for (en = hls->segments; en; en = en->next) {
164  avio_printf(hls->pb, "#EXTINF:%f,\n", en->duration);
165  if (hls->baseurl)
166  avio_printf(hls->pb, "%s", hls->baseurl);
167  avio_printf(hls->pb, "%s\n", en->filename);
168  }
169 
170  if (last)
171  avio_printf(hls->pb, "#EXT-X-ENDLIST\n");
172 
173 fail:
174  avio_closep(&hls->pb);
175  return ret;
176 }
177 
179 {
180  HLSContext *c = s->priv_data;
181  AVFormatContext *oc = c->avf;
182  int err = 0;
183 
184  if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
185  c->basename, c->wrap ? c->sequence % c->wrap : c->sequence) < 0) {
186  av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", c->basename);
187  return AVERROR(EINVAL);
188  }
189  c->number++;
190 
191  if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
192  &s->interrupt_callback, NULL)) < 0)
193  return err;
194 
195  if (oc->oformat->priv_class && oc->priv_data)
196  av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
197 
198  return 0;
199 }
200 
202 {
203  HLSContext *hls = s->priv_data;
204  int ret, i;
205  char *p;
206  const char *pattern = "%d.ts";
207  int basename_size = strlen(s->filename) + strlen(pattern) + 1;
208 
209  hls->sequence = hls->start_sequence;
210  hls->recording_time = hls->time * AV_TIME_BASE;
211  hls->start_pts = AV_NOPTS_VALUE;
212 
213  for (i = 0; i < s->nb_streams; i++)
214  hls->has_video +=
216 
217  if (hls->has_video > 1)
219  "More than a single video stream present, "
220  "expect issues decoding it.\n");
221 
222  hls->oformat = av_guess_format("mpegts", NULL, NULL);
223 
224  if (!hls->oformat) {
226  goto fail;
227  }
228 
229  hls->basename = av_malloc(basename_size);
230 
231  if (!hls->basename) {
232  ret = AVERROR(ENOMEM);
233  goto fail;
234  }
235 
236  strcpy(hls->basename, s->filename);
237 
238  p = strrchr(hls->basename, '.');
239 
240  if (p)
241  *p = '\0';
242 
243  av_strlcat(hls->basename, pattern, basename_size);
244 
245  if ((ret = hls_mux_init(s)) < 0)
246  goto fail;
247 
248  if ((ret = hls_start(s)) < 0)
249  goto fail;
250 
251  if ((ret = avformat_write_header(hls->avf, NULL)) < 0)
252  goto fail;
253 
254 
255 fail:
256  if (ret) {
257  av_free(hls->basename);
258  if (hls->avf)
260  }
261  return ret;
262 }
263 
265 {
266  HLSContext *hls = s->priv_data;
267  AVFormatContext *oc = hls->avf;
268  AVStream *st = s->streams[pkt->stream_index];
269  int64_t end_pts = hls->recording_time * hls->number;
270  int is_ref_pkt = 1;
271  int ret, can_split = 1;
272 
273  if (hls->start_pts == AV_NOPTS_VALUE) {
274  hls->start_pts = pkt->pts;
275  hls->end_pts = pkt->pts;
276  }
277 
278  if (hls->has_video) {
279  can_split = st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
280  pkt->flags & AV_PKT_FLAG_KEY;
281  is_ref_pkt = st->codec->codec_type == AVMEDIA_TYPE_VIDEO;
282  }
283  if (pkt->pts == AV_NOPTS_VALUE)
284  is_ref_pkt = can_split = 0;
285 
286  if (is_ref_pkt)
287  hls->duration = (double)(pkt->pts - hls->end_pts)
288  * st->time_base.num / st->time_base.den;
289 
290  if (can_split && av_compare_ts(pkt->pts - hls->start_pts, st->time_base,
291  end_pts, AV_TIME_BASE_Q) >= 0) {
292  ret = hls_append_segment(hls, hls->duration);
293  if (ret)
294  return ret;
295 
296  hls->end_pts = pkt->pts;
297  hls->duration = 0;
298 
299  av_write_frame(oc, NULL); /* Flush any buffered data */
300  avio_close(oc->pb);
301 
302  ret = hls_start(s);
303 
304  if (ret)
305  return ret;
306 
307  oc = hls->avf;
308 
309  if ((ret = hls_window(s, 0)) < 0)
310  return ret;
311  }
312 
313  ret = ff_write_chained(oc, pkt->stream_index, pkt, s, 0);
314 
315  return ret;
316 }
317 
319 {
320  HLSContext *hls = s->priv_data;
321  AVFormatContext *oc = hls->avf;
322 
323  av_write_trailer(oc);
324  avio_closep(&oc->pb);
326  av_free(hls->basename);
327  hls_append_segment(hls, hls->duration);
328  hls_window(s, 1);
329 
330  hls_free_segments(hls);
331  avio_close(hls->pb);
332  return 0;
333 }
334 
335 #define OFFSET(x) offsetof(HLSContext, x)
336 #define E AV_OPT_FLAG_ENCODING_PARAM
337 static const AVOption options[] = {
338  {"start_number", "set first number in the sequence", OFFSET(start_sequence),AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, E},
339  {"hls_time", "set segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E},
340  {"hls_list_size", "set maximum number of playlist entries", OFFSET(max_nb_segments), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
341  {"hls_wrap", "set number after which the index wraps", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
342  {"hls_base_url", "url to prepend to each playlist entry", OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
343  { NULL },
344 };
345 
346 static const AVClass hls_class = {
347  .class_name = "hls muxer",
348  .item_name = av_default_item_name,
349  .option = options,
350  .version = LIBAVUTIL_VERSION_INT,
351 };
352 
353 
355  .name = "hls",
356  .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
357  .extensions = "m3u8",
358  .priv_data_size = sizeof(HLSContext),
359  .audio_codec = AV_CODEC_ID_AAC,
360  .video_codec = AV_CODEC_ID_H264,
365  .priv_class = &hls_class,
366 };