FFmpeg  2.1.1
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 
24 #include "libavutil/mathematics.h"
25 #include "libavutil/parseutils.h"
26 #include "libavutil/avstring.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/log.h"
29 
30 #include "avformat.h"
31 #include "internal.h"
32 
33 typedef struct ListEntry {
34  char name[1024];
35  int duration;
36  struct ListEntry *next;
37 } ListEntry;
38 
39 typedef struct HLSContext {
40  const AVClass *class; // Class for private options.
41  unsigned number;
42  int64_t sequence;
45  float time; // Set by a private option.
46  int size; // Set by a private option.
47  int wrap; // Set by a private option.
48  int64_t recording_time;
49  int has_video;
50  int64_t start_pts;
51  int64_t end_pts;
52  int64_t duration; // last segment duration computed so far, in seconds
56  char *basename;
58 } HLSContext;
59 
61 {
62  HLSContext *hls = s->priv_data;
63  AVFormatContext *oc;
64  int i;
65 
66  hls->avf = oc = avformat_alloc_context();
67  if (!oc)
68  return AVERROR(ENOMEM);
69 
70  oc->oformat = hls->oformat;
72 
73  for (i = 0; i < s->nb_streams; i++) {
74  AVStream *st;
75  if (!(st = avformat_new_stream(oc, NULL)))
76  return AVERROR(ENOMEM);
79  }
80 
81  return 0;
82 }
83 
84 static int append_entry(HLSContext *hls, uint64_t duration)
85 {
86  ListEntry *en = av_malloc(sizeof(*en));
87 
88  if (!en)
89  return AVERROR(ENOMEM);
90 
91  av_strlcpy(en->name, av_basename(hls->avf->filename), sizeof(en->name));
92 
93  en->duration = duration;
94  en->next = NULL;
95 
96  if (!hls->list)
97  hls->list = en;
98  else
99  hls->end_list->next = en;
100 
101  hls->end_list = en;
102 
103  if (hls->nb_entries >= hls->size) {
104  en = hls->list;
105  hls->list = en->next;
106  av_free(en);
107  } else
108  hls->nb_entries++;
109 
110  hls->sequence++;
111 
112  return 0;
113 }
114 
115 static void free_entries(HLSContext *hls)
116 {
117  ListEntry *p = hls->list, *en;
118 
119  while(p) {
120  en = p;
121  p = p->next;
122  av_free(en);
123  }
124 }
125 
126 static int hls_window(AVFormatContext *s, int last)
127 {
128  HLSContext *hls = s->priv_data;
129  ListEntry *en;
130  int target_duration = 0;
131  int ret = 0;
132 
133  if ((ret = avio_open2(&hls->pb, s->filename, AVIO_FLAG_WRITE,
134  &s->interrupt_callback, NULL)) < 0)
135  goto fail;
136 
137  for (en = hls->list; en; en = en->next) {
138  if (target_duration < en->duration)
139  target_duration = en->duration;
140  }
141 
142  avio_printf(hls->pb, "#EXTM3U\n");
143  avio_printf(hls->pb, "#EXT-X-VERSION:3\n");
144  avio_printf(hls->pb, "#EXT-X-TARGETDURATION:%d\n", target_duration);
145  avio_printf(hls->pb, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n",
146  FFMAX(0, hls->sequence - hls->size));
147 
148  for (en = hls->list; en; en = en->next) {
149  avio_printf(hls->pb, "#EXTINF:%d,\n", en->duration);
150  avio_printf(hls->pb, "%s\n", en->name);
151  }
152 
153  if (last)
154  avio_printf(hls->pb, "#EXT-X-ENDLIST\n");
155 
156 fail:
157  avio_closep(&hls->pb);
158  return ret;
159 }
160 
162 {
163  HLSContext *c = s->priv_data;
164  AVFormatContext *oc = c->avf;
165  int err = 0;
166 
167  if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
168  c->basename, c->wrap ? c->number % c->wrap : c->number) < 0) {
169  av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", c->basename);
170  return AVERROR(EINVAL);
171  }
172  c->number++;
173 
174  if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
175  &s->interrupt_callback, NULL)) < 0)
176  return err;
177 
178  if (oc->oformat->priv_class && oc->priv_data)
179  av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
180 
181  return 0;
182 }
183 
185 {
186  HLSContext *hls = s->priv_data;
187  int ret, i;
188  char *p;
189  const char *pattern = "%d.ts";
190  int basename_size = strlen(s->filename) + strlen(pattern) + 1;
191 
192  hls->number = 0;
193 
194  hls->recording_time = hls->time * AV_TIME_BASE;
195  hls->start_pts = AV_NOPTS_VALUE;
196 
197  for (i = 0; i < s->nb_streams; i++)
198  hls->has_video +=
200 
201  if (hls->has_video > 1)
203  "More than a single video stream present, "
204  "expect issues decoding it.\n");
205 
206  hls->oformat = av_guess_format("mpegts", NULL, NULL);
207 
208  if (!hls->oformat) {
210  goto fail;
211  }
212 
213  hls->basename = av_malloc(basename_size);
214 
215  if (!hls->basename) {
216  ret = AVERROR(ENOMEM);
217  goto fail;
218  }
219 
220  strcpy(hls->basename, s->filename);
221 
222  p = strrchr(hls->basename, '.');
223 
224  if (p)
225  *p = '\0';
226 
227  av_strlcat(hls->basename, pattern, basename_size);
228 
229  if ((ret = hls_mux_init(s)) < 0)
230  goto fail;
231 
232  if ((ret = hls_start(s)) < 0)
233  goto fail;
234 
235  if ((ret = avformat_write_header(hls->avf, NULL)) < 0)
236  return ret;
237 
238 
239 fail:
240  if (ret) {
241  av_free(hls->basename);
242  if (hls->avf)
244  }
245  return ret;
246 }
247 
249 {
250  HLSContext *hls = s->priv_data;
251  AVFormatContext *oc = hls->avf;
252  AVStream *st = s->streams[pkt->stream_index];
253  int64_t end_pts = hls->recording_time * hls->number;
254  int is_ref_pkt = 1;
255  int ret, can_split = 1;
256 
257  if (hls->start_pts == AV_NOPTS_VALUE) {
258  hls->start_pts = pkt->pts;
259  hls->end_pts = pkt->pts;
260  }
261 
262  if (hls->has_video) {
263  can_split = st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
264  pkt->flags & AV_PKT_FLAG_KEY;
265  is_ref_pkt = st->codec->codec_type == AVMEDIA_TYPE_VIDEO;
266  }
267  if (pkt->pts == AV_NOPTS_VALUE)
268  is_ref_pkt = can_split = 0;
269 
270  if (is_ref_pkt)
271  hls->duration = av_rescale(pkt->pts - hls->end_pts,
272  st->time_base.num, st->time_base.den);
273 
274  if (can_split && av_compare_ts(pkt->pts - hls->start_pts, st->time_base,
275  end_pts, AV_TIME_BASE_Q) >= 0) {
276  ret = append_entry(hls, hls->duration);
277  if (ret)
278  return ret;
279 
280  hls->end_pts = pkt->pts;
281  hls->duration = 0;
282 
283  av_write_frame(oc, NULL); /* Flush any buffered data */
284  avio_close(oc->pb);
285 
286  ret = hls_start(s);
287 
288  if (ret)
289  return ret;
290 
291  oc = hls->avf;
292 
293  if ((ret = hls_window(s, 0)) < 0)
294  return ret;
295  }
296 
297  ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
298 
299  return ret;
300 }
301 
303 {
304  HLSContext *hls = s->priv_data;
305  AVFormatContext *oc = hls->avf;
306 
307  av_write_trailer(oc);
308  avio_closep(&oc->pb);
310  av_free(hls->basename);
311  append_entry(hls, hls->duration);
312  hls_window(s, 1);
313 
314  free_entries(hls);
315  avio_close(hls->pb);
316  return 0;
317 }
318 
319 #define OFFSET(x) offsetof(HLSContext, x)
320 #define E AV_OPT_FLAG_ENCODING_PARAM
321 static const AVOption options[] = {
322  {"start_number", "set first number in the sequence", OFFSET(sequence),AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, E},
323  {"hls_time", "set segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E},
324  {"hls_list_size", "set maximum number of playlist entries", OFFSET(size), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
325  {"hls_wrap", "set number after which the index wraps", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
326  { NULL },
327 };
328 
329 static const AVClass hls_class = {
330  .class_name = "hls muxer",
331  .item_name = av_default_item_name,
332  .option = options,
333  .version = LIBAVUTIL_VERSION_INT,
334 };
335 
336 
338  .name = "hls",
339  .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
340  .extensions = "m3u8",
341  .priv_data_size = sizeof(HLSContext),
342  .audio_codec = AV_CODEC_ID_MP2,
343  .video_codec = AV_CODEC_ID_MPEG2VIDEO,
348  .priv_class = &hls_class,
349 };
float time
Definition: hlsenc.c:45
int wrap
Definition: hlsenc.c:47
const char * s
Definition: avisynth_c.h:668
Bytestream IO Context.
Definition: avio.h:68
int size
char * basename
Definition: hlsenc.c:56
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1161
AVOption.
Definition: opt.h:253
struct ListEntry * next
Definition: hlsenc.c:36
static int hls_write_trailer(struct AVFormatContext *s)
Definition: hlsenc.c:302
int avformat_write_header(AVFormatContext *s, AVDictionary **options)
Allocate the stream private data and write the stream header to an output media file.
Definition: mux.c:387
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
Write a packet to an output media file.
Definition: mux.c:548
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: avcodec.h:4153
#define LIBAVUTIL_VERSION_INT
Definition: avcodec.h:820
int avio_close(AVIOContext *s)
Close the resource accessed by the AVIOContext s and free it.
Definition: aviobuf.c:860
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:686
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:733
int num
numerator
Definition: rational.h:44
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...
#define wrap(func)
Definition: w64xmmtest.h:70
static int append_entry(HLSContext *hls, uint64_t duration)
Definition: hlsenc.c:84
int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src)
Copy the settings of the source AVCodecContext into the destination AVCodecContext.
Definition: options.c:185
static int hls_window(AVFormatContext *s, int last)
Definition: hlsenc.c:126
#define AVERROR_MUXER_NOT_FOUND
const AVClass * priv_class
AVClass for the private context.
Definition: avformat.h:423
if((e=av_dict_get(options,"", NULL, AV_DICT_IGNORE_SUFFIX)))
Definition: avfilter.c:965
Format I/O context.
Definition: avformat.h:968
ListEntry * list
Definition: hlsenc.c:54
const char * av_default_item_name(void *ctx)
Return the context name.
Definition: log.c:145
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:843
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:55
int64_t end_pts
Definition: hlsenc.c:51
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition: avformat.h:347
static int64_t duration
Definition: ffplay.c:306
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:3348
const OptionDef options[]
Definition: ffserver.c:4682
int avio_printf(AVIOContext *s, const char *fmt,...) av_printf_format(2
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1113
int avio_closep(AVIOContext **s)
Close the resource accessed by the AVIOContext *s, free it and set the pointer pointing to it to NULL...
Definition: aviobuf.c:878
static int hls_write_header(AVFormatContext *s)
Definition: hlsenc.c:184
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: avcodec.h:4147
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:219
#define OFFSET(x)
Definition: hlsenc.c:319
void * priv_data
Format private data.
Definition: avformat.h:988
char filename[1024]
input or output filename
Definition: avformat.h:1018
#define AVFMT_ALLOW_FLUSH
Format allows flushing.
Definition: avformat.h:363
AVIOContext * pb
Definition: hlsenc.c:57
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:151
int has_video
Definition: hlsenc.c:49
int64_t recording_time
Definition: hlsenc.c:48
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:82
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1069
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:135
goto fail
Definition: avfilter.c:963
int size
Definition: hlsenc.c:46
unsigned int nb_streams
A list of all streams in the file.
Definition: avformat.h:1015
unsigned number
Definition: hlsenc.c:41
static void free_entries(HLSContext *hls)
Definition: hlsenc.c:115
int64_t av_rescale(int64_t a, int64_t b, int64_t c) av_const
Rescale a 64-bit integer with rounding to nearest.
Definition: mathematics.c:118
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avcodec.h:2284
ret
Definition: avfilter.c:961
int64_t start_pts
Definition: hlsenc.c:50
AVStream ** streams
Definition: avformat.h:1016
static int write_trailer(AVFormatContext *s1)
Definition: v4l2enc.c:93
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:73
Definition: hls.c:96
static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: hlsenc.c:248
const char * name
Definition: avformat.h:395
#define E
Definition: hlsenc.c:320
preferred ID for MPEG-1/2 video decoding
Definition: avcodec.h:107
int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
Return in &#39;buf&#39; the path with &#39;d&#39; replaced by a number.
Definition: utils.c:3670
Stream structure.
Definition: avformat.h:667
enum AVMediaType codec_type
Definition: avcodec.h:1154
#define FFMAX(a, b)
Definition: avcodec.h:923
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avcodec.h:2290
int64_t duration
Definition: hlsenc.c:52
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:333
AVOutputFormat * oformat
Definition: hlsenc.c:43
AVIOContext * pb
I/O context.
Definition: avformat.h:1001
const char * av_basename(const char *path)
Thread safe basename.
Definition: avstring.c:233
Describe the class of an AVClass context structure.
Definition: log.h:50
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:3271
int64_t sequence
Definition: hlsenc.c:42
char name[1024]
Definition: hlsenc.c:34
size_t av_strlcat(char *dst, const char *src, size_t size)
Append the string src to the string dst, but to a total length of no more than size - 1 bytes...
Definition: avstring.c:92
static int flags
Definition: cpu.c:45
static int hls_mux_init(AVFormatContext *s)
Definition: hlsenc.c:60
int nb_entries
Definition: hlsenc.c:53
static double c[64]
int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt, AVFormatContext *src)
Write a packet to another muxer than the one the user originally intended.
Definition: mux.c:851
Main libavformat public API header.
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition: options.c:106
int den
denominator
Definition: rational.h:45
ListEntry * end_list
Definition: hlsenc.c:55
struct AVOutputFormat * oformat
Definition: avformat.h:982
AVOutputFormat * av_guess_format(const char *short_name, const char *filename, const char *mime_type)
Return the output format in the list of registered output formats which best matches the provided par...
Definition: format.c:115
static int hls_start(AVFormatContext *s)
Definition: hlsenc.c:161
static void write_header(FFV1Context *f)
Definition: ffv1enc.c:492
AVFormatContext * avf
Definition: hlsenc.c:44
#define AVERROR(e)
AVOutputFormat ff_hls_muxer
Definition: hlsenc.c:337
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition: mux.c:800
static AVPacket pkt
Definition: demuxing.c:52
int stream_index
Definition: avcodec.h:1065
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:703
static const AVClass hls_class
Definition: hlsenc.c:329
This structure stores compressed data.
Definition: avcodec.h:1040
static int write_packet(AVFormatContext *s1, AVPacket *pkt)
Definition: v4l2enc.c:85
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition: opt.c:255
int64_t pts
Presentation timestamp in AVStream-&gt;time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1056
int duration
Definition: hlsenc.c:35
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avcodec.h:2278