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