Libav
segment.c
Go to the documentation of this file.
1 /*
2  * Generic segmenter
3  * Copyright (c) 2011, Luca Barbato
4  *
5  * This file is part of Libav.
6  *
7  * Libav 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  * Libav 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 Libav; 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 "avformat.h"
25 #include "internal.h"
26 
27 #include "libavutil/log.h"
28 #include "libavutil/opt.h"
29 #include "libavutil/avstring.h"
30 #include "libavutil/parseutils.h"
31 #include "libavutil/mathematics.h"
32 
33 typedef struct {
34  const AVClass *class;
35  int number;
38  char *format;
39  char *list;
40  char *entry_prefix;
41  int list_type;
42  float time;
43  int size;
44  int wrap;
47  int64_t offset_time;
48  int64_t recording_time;
49  int has_video;
52 
53 enum {
56 };
57 
59 {
60  SegmentContext *seg = s->priv_data;
61  AVFormatContext *oc;
62  int i;
63 
64  seg->avf = oc = avformat_alloc_context();
65  if (!oc)
66  return AVERROR(ENOMEM);
67 
68  oc->oformat = seg->oformat;
70 
71  for (i = 0; i < s->nb_streams; i++) {
72  AVStream *st;
73  if (!(st = avformat_new_stream(oc, NULL)))
74  return AVERROR(ENOMEM);
77  }
78 
79  return 0;
80 }
81 
82 static int segment_hls_window(AVFormatContext *s, int last)
83 {
84  SegmentContext *seg = s->priv_data;
85  int i, ret = 0;
86  char buf[1024];
87 
88  if ((ret = avio_open2(&seg->pb, seg->list, AVIO_FLAG_WRITE,
89  &s->interrupt_callback, NULL)) < 0)
90  goto fail;
91 
92  avio_printf(seg->pb, "#EXTM3U\n");
93  avio_printf(seg->pb, "#EXT-X-VERSION:3\n");
94  avio_printf(seg->pb, "#EXT-X-TARGETDURATION:%d\n", (int)seg->time);
95  avio_printf(seg->pb, "#EXT-X-MEDIA-SEQUENCE:%d\n",
96  FFMAX(0, seg->number - seg->size));
97 
98  av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%d\n",
99  FFMAX(0, seg->number - seg->size));
100 
101  for (i = FFMAX(0, seg->number - seg->size);
102  i < seg->number; i++) {
103  avio_printf(seg->pb, "#EXTINF:%d,\n", (int)seg->time);
104  if (seg->entry_prefix) {
105  avio_printf(seg->pb, "%s", seg->entry_prefix);
106  }
107  av_get_frame_filename(buf, sizeof(buf), s->filename, i);
108  avio_printf(seg->pb, "%s\n", buf);
109  }
110 
111  if (last)
112  avio_printf(seg->pb, "#EXT-X-ENDLIST\n");
113 fail:
114  avio_closep(&seg->pb);
115  return ret;
116 }
117 
119 {
120  SegmentContext *c = s->priv_data;
121  AVFormatContext *oc = c->avf;
122  int err = 0;
123 
124  if (write_header) {
126  c->avf = NULL;
127  if ((err = segment_mux_init(s)) < 0)
128  return err;
129  oc = c->avf;
130  }
131 
132  if (c->wrap)
133  c->number %= c->wrap;
134 
135  if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
136  s->filename, c->number++) < 0)
137  return AVERROR(EINVAL);
138 
139  if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
140  &s->interrupt_callback, NULL)) < 0)
141  return err;
142 
143  if (oc->oformat->priv_class && oc->priv_data)
144  av_opt_set(oc->priv_data, "resend_headers", "1", 0); /* mpegts specific */
145 
146  if (write_header) {
147  if ((err = avformat_write_header(oc, NULL)) < 0)
148  return err;
149  }
150 
151  return 0;
152 }
153 
155 {
156  int ret = 0;
157 
158  av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
159  if (write_trailer)
160  av_write_trailer(oc);
161  avio_close(oc->pb);
162 
163  return ret;
164 }
165 
166 static int open_null_ctx(AVIOContext **ctx)
167 {
168  int buf_size = 32768;
169  uint8_t *buf = av_malloc(buf_size);
170  if (!buf)
171  return AVERROR(ENOMEM);
172  *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
173  if (!*ctx) {
174  av_free(buf);
175  return AVERROR(ENOMEM);
176  }
177  return 0;
178 }
179 
180 static void close_null_ctx(AVIOContext *pb)
181 {
182  av_free(pb->buffer);
183  av_free(pb);
184 }
185 
187 {
188  avio_closep(&seg->pb);
190  seg->avf = NULL;
191 }
192 
194 {
195  SegmentContext *seg = s->priv_data;
196  AVFormatContext *oc = NULL;
197  int ret, i;
198 
199  seg->number = 0;
200  seg->offset_time = 0;
201  seg->recording_time = seg->time * 1000000;
202  if (!seg->write_header_trailer)
203  seg->individual_header_trailer = 0;
204 
205  if (seg->list && seg->list_type != LIST_HLS)
206  if ((ret = avio_open2(&seg->pb, seg->list, AVIO_FLAG_WRITE,
207  &s->interrupt_callback, NULL)) < 0)
208  goto fail;
209 
210  for (i = 0; i < s->nb_streams; i++)
211  seg->has_video +=
213 
214  if (seg->has_video > 1)
216  "More than a single video stream present, "
217  "expect issues decoding it.\n");
218 
219  seg->oformat = av_guess_format(seg->format, s->filename, NULL);
220 
221  if (!seg->oformat) {
223  goto fail;
224  }
225  if (seg->oformat->flags & AVFMT_NOFILE) {
226  av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
227  seg->oformat->name);
228  ret = AVERROR(EINVAL);
229  goto fail;
230  }
231 
232  if ((ret = segment_mux_init(s)) < 0)
233  goto fail;
234  oc = seg->avf;
235 
236  if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
237  s->filename, seg->number++) < 0) {
238  ret = AVERROR(EINVAL);
239  goto fail;
240  }
241 
242  if (seg->write_header_trailer) {
243  if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
244  &s->interrupt_callback, NULL)) < 0)
245  goto fail;
246  } else {
247  if ((ret = open_null_ctx(&oc->pb)) < 0)
248  goto fail;
249  }
250 
251  if ((ret = avformat_write_header(oc, NULL)) < 0) {
252  avio_close(oc->pb);
253  goto fail;
254  }
255 
256  if (!seg->write_header_trailer) {
257  close_null_ctx(oc->pb);
258  if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
259  &s->interrupt_callback, NULL)) < 0)
260  goto fail;
261  }
262 
263  if (seg->list) {
264  if (seg->list_type == LIST_HLS) {
265  if ((ret = segment_hls_window(s, 0)) < 0)
266  goto fail;
267  } else {
268  avio_printf(seg->pb, "%s\n", oc->filename);
269  avio_flush(seg->pb);
270  }
271  }
272 
273 fail:
274  if (ret < 0)
275  seg_free_context(seg);
276 
277  return ret;
278 }
279 
281 {
282  SegmentContext *seg = s->priv_data;
283  AVFormatContext *oc = seg->avf;
284  AVStream *st = s->streams[pkt->stream_index];
285  int64_t end_pts = seg->recording_time * seg->number;
286  int ret, can_split = 1;
287 
288  if (!oc)
289  return AVERROR(EINVAL);
290 
291  if (seg->has_video) {
292  can_split = st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
293  pkt->flags & AV_PKT_FLAG_KEY;
294  }
295 
296  if (can_split && av_compare_ts(pkt->pts, st->time_base, end_pts,
297  AV_TIME_BASE_Q) >= 0) {
298  av_log(s, AV_LOG_DEBUG, "Next segment starts at %d %"PRId64"\n",
299  pkt->stream_index, pkt->pts);
300 
301  ret = segment_end(oc, seg->individual_header_trailer);
302 
303  if (!ret)
305 
306  if (ret)
307  goto fail;
308 
309  oc = seg->avf;
310 
311  if (seg->list) {
312  if (seg->list_type == LIST_HLS) {
313  if ((ret = segment_hls_window(s, 0)) < 0)
314  goto fail;
315  } else {
316  avio_printf(seg->pb, "%s\n", oc->filename);
317  avio_flush(seg->pb);
318  if (seg->size && !(seg->number % seg->size)) {
319  avio_closep(&seg->pb);
320  if ((ret = avio_open2(&seg->pb, seg->list, AVIO_FLAG_WRITE,
321  &s->interrupt_callback, NULL)) < 0)
322  goto fail;
323  }
324  }
325  }
326  }
327 
328  ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
329 
330 fail:
331  if (ret < 0)
332  seg_free_context(seg);
333 
334  return ret;
335 }
336 
337 static int seg_write_trailer(struct AVFormatContext *s)
338 {
339  SegmentContext *seg = s->priv_data;
340  AVFormatContext *oc = seg->avf;
341  int ret = 0;
342 
343  if (!oc)
344  goto fail;
345 
346  if (!seg->write_header_trailer) {
347  if ((ret = segment_end(oc, 0)) < 0)
348  goto fail;
349  open_null_ctx(&oc->pb);
350  ret = av_write_trailer(oc);
351  close_null_ctx(oc->pb);
352  } else {
353  ret = segment_end(oc, 1);
354  }
355 
356  if (ret < 0)
357  goto fail;
358 
359  if (seg->list && seg->list_type == LIST_HLS) {
360  if ((ret = segment_hls_window(s, 1) < 0))
361  goto fail;
362  }
363 
364 fail:
365  avio_close(seg->pb);
367  return ret;
368 }
369 
370 #define OFFSET(x) offsetof(SegmentContext, x)
371 #define E AV_OPT_FLAG_ENCODING_PARAM
372 static const AVOption options[] = {
373  { "segment_format", "container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
374  { "segment_time", "segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E },
375  { "segment_list", "output the segment list", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
376  { "segment_list_size", "maximum number of playlist entries", OFFSET(size), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E },
377  { "segment_list_type", "segment list format", OFFSET(list_type), AV_OPT_TYPE_INT, {.i64 = LIST_FLAT}, 0, 2, E, "list_type" },
378  { "flat", "plain list (default)", 0, AV_OPT_TYPE_CONST, {.i64 = LIST_FLAT}, 0, 0, E, "list_type" },
379  { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64 = LIST_HLS}, 0, 0, E, "list_type" },
380  { "segment_wrap", "number after which the index wraps", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
381  { "segment_list_entry_prefix", "base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
382  { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
383  { "write_header_trailer", "write a header to the first segment and a trailer to the last one", OFFSET(write_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
384  { NULL },
385 };
386 
387 static const AVClass seg_class = {
388  .class_name = "segment muxer",
389  .item_name = av_default_item_name,
390  .option = options,
391  .version = LIBAVUTIL_VERSION_INT,
392 };
393 
394 
396  .name = "segment",
397  .long_name = NULL_IF_CONFIG_SMALL("segment"),
398  .priv_data_size = sizeof(SegmentContext),
399  .flags = AVFMT_NOFILE,
403  .priv_class = &seg_class,
404 };
void * av_malloc(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:62
AVFormatContext * avf
Definition: segment.c:37
Bytestream IO Context.
Definition: avio.h:68
int size
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1163
AVOption.
Definition: opt.h:234
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:238
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
Write a packet to an output media file.
Definition: mux.c:361
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:129
char * entry_prefix
Set by a private option.
Definition: segment.c:40
static int segment_start(AVFormatContext *s, int write_header)
Definition: segment.c:118
static int write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: assenc.c:58
int size
Set by a private option.
Definition: segment.c:43
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:769
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:293
unsigned char * buffer
Start of the buffer.
Definition: avio.h:82
int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src)
Copy the settings of the source AVCodecContext into the destination AVCodecContext.
Definition: options.c:154
static int seg_write_header(AVFormatContext *s)
Definition: segment.c:193
static void close_null_ctx(AVIOContext *pb)
Definition: segment.c:180
static int segment_mux_init(AVFormatContext *s)
Definition: segment.c:58
Format I/O context.
Definition: avformat.h:922
static int segment_hls_window(AVFormatContext *s, int last)
Definition: segment.c:82
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:38
AVIOContext * pb
Definition: segment.c:50
int flags
can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_RAWPICTURE, AVFMT_GLOBALHEADER, AVFMT_NOTIMESTAMPS, AVFMT_VARIABLE_FPS, AVFMT_NODIMENSIONS, AVFMT_NOSTREAMS, AVFMT_ALLOW_FLUSH, AVFMT_TS_NONSTRICT
Definition: avformat.h:465
uint8_t
int wrap
Set by a private option.
Definition: segment.c:44
AVOptions.
static int seg_write_trailer(struct AVFormatContext *s)
Definition: segment.c:337
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:2521
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:990
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition: options.c:98
int64_t offset_time
Definition: segment.c:47
static int flags
Definition: log.c:44
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:139
char * format
Set by a private option.
Definition: segment.c:38
static int write_trailer(AVFormatContext *s)
Definition: assenc.c:64
struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:941
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1019
AVIOContext * avio_alloc_context(unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int(*read_packet)(void *opaque, uint8_t *buf, int buf_size), int(*write_packet)(void *opaque, uint8_t *buf, int buf_size), int64_t(*seek)(void *opaque, int64_t offset, int whence))
Allocate and initialize an AVIOContext for buffered I/O.
Definition: aviobuf.c:107
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:123
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:186
int individual_header_trailer
Set by a private option.
Definition: segment.c:45
#define AVERROR(e)
Definition: error.h:43
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:150
int avio_close(AVIOContext *s)
Close the resource accessed by the AVIOContext s and free it.
Definition: aviobuf.c:800
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:144
#define wrap(func)
Definition: neontest.h:62
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:169
#define FFMAX(a, b)
Definition: common.h:55
#define OFFSET(x)
Definition: segment.c:370
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:979
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:134
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:718
float time
Set by a private option.
Definition: segment.c:42
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:978
int void avio_flush(AVIOContext *s)
Definition: aviobuf.c:180
char filename[1024]
input or output filename
Definition: avformat.h:998
static int segment_end(AVFormatContext *oc, int write_trailer)
Definition: segment.c:154
const char * name
Definition: avformat.h:446
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:104
const AVClass * priv_class
AVClass for the private context.
Definition: avformat.h:474
LIBAVUTIL_VERSION_INT
Definition: eval.c:55
int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
Return in 'buf' the path with 'd' replaced by a number.
Definition: utils.c:2660
static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: segment.c:280
Stream structure.
Definition: avformat.h:699
char * list
Set by a private option.
Definition: segment.c:39
NULL
Definition: eval.c:55
enum AVMediaType codec_type
Definition: avcodec.h:1058
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:240
AVIOContext * pb
I/O context.
Definition: avformat.h:964
av_default_item_name
Definition: dnxhdenc.c:52
int list_type
Set by a private option.
Definition: segment.c:41
AVOutputFormat ff_segment_muxer
Definition: segment.c:395
Describe the class of an AVClass context structure.
Definition: log.h:33
int has_video
Definition: segment.c:49
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:783
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:2445
misc parsing utilities
int write_header_trailer
Set by a private option.
Definition: segment.c:46
static const AVClass seg_class
Definition: segment.c:387
Main libavformat public API header.
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition: avformat.h:409
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:624
#define E
Definition: segment.c:371
int64_t recording_time
Definition: segment.c:48
void * priv_data
Format private data.
Definition: avformat.h:950
static const AVOption options[]
Definition: segment.c:372
static void write_header(FFV1Context *f)
Definition: ffv1enc.c:380
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition: mux.c:585
static int open_null_ctx(AVIOContext **ctx)
Definition: segment.c:166
#define AVERROR_MUXER_NOT_FOUND
Muxer not found.
Definition: error.h:55
static void seg_free_context(SegmentContext *seg)
Definition: segment.c:186
int stream_index
Definition: avcodec.h:975
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:741
This structure stores compressed data.
Definition: avcodec.h:950
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:814
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition: opt.c:212
AVOutputFormat * oformat
Definition: segment.c:36
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:966
int avio_printf(AVIOContext *s, const char *fmt,...) av_printf_format(2