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  int list_type;
41  float time;
42  int size;
43  int wrap;
46  int64_t offset_time;
47  int64_t recording_time;
48  int has_video;
51 
52 enum {
55 };
56 
58 {
59  SegmentContext *seg = s->priv_data;
60  AVFormatContext *oc;
61  int i;
62 
63  seg->avf = oc = avformat_alloc_context();
64  if (!oc)
65  return AVERROR(ENOMEM);
66 
67  oc->oformat = seg->oformat;
69 
70  for (i = 0; i < s->nb_streams; i++) {
71  AVStream *st;
72  if (!(st = avformat_new_stream(oc, NULL)))
73  return AVERROR(ENOMEM);
76  }
77 
78  return 0;
79 }
80 
81 static int segment_hls_window(AVFormatContext *s, int last)
82 {
83  SegmentContext *seg = s->priv_data;
84  int i, ret = 0;
85  char buf[1024];
86 
87  if ((ret = avio_open2(&seg->pb, seg->list, AVIO_FLAG_WRITE,
88  &s->interrupt_callback, NULL)) < 0)
89  goto fail;
90 
91  avio_printf(seg->pb, "#EXTM3U\n");
92  avio_printf(seg->pb, "#EXT-X-VERSION:3\n");
93  avio_printf(seg->pb, "#EXT-X-TARGETDURATION:%d\n", (int)seg->time);
94  avio_printf(seg->pb, "#EXT-X-MEDIA-SEQUENCE:%d\n",
95  FFMAX(0, seg->number - seg->size));
96 
97  for (i = FFMAX(0, seg->number - seg->size);
98  i < seg->number; i++) {
99  avio_printf(seg->pb, "#EXTINF:%d,\n", (int)seg->time);
100  av_get_frame_filename(buf, sizeof(buf), s->filename, i);
101  avio_printf(seg->pb, "%s\n", buf);
102  }
103 
104  if (last)
105  avio_printf(seg->pb, "#EXT-X-ENDLIST\n");
106 fail:
107  avio_closep(&seg->pb);
108  return ret;
109 }
110 
112 {
113  SegmentContext *c = s->priv_data;
114  AVFormatContext *oc = c->avf;
115  int err = 0;
116 
117  if (write_header) {
119  c->avf = NULL;
120  if ((err = segment_mux_init(s)) < 0)
121  return err;
122  oc = c->avf;
123  }
124 
125  if (c->wrap)
126  c->number %= c->wrap;
127 
128  if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
129  s->filename, c->number++) < 0)
130  return AVERROR(EINVAL);
131 
132  if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
133  &s->interrupt_callback, NULL)) < 0)
134  return err;
135 
136  if (oc->oformat->priv_class && oc->priv_data)
137  av_opt_set(oc->priv_data, "resend_headers", "1", 0); /* mpegts specific */
138 
139  if (write_header) {
140  if ((err = avformat_write_header(oc, NULL)) < 0)
141  return err;
142  }
143 
144  return 0;
145 }
146 
148 {
149  int ret = 0;
150 
151  av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
152  if (write_trailer)
153  av_write_trailer(oc);
154  avio_close(oc->pb);
155 
156  return ret;
157 }
158 
159 static int open_null_ctx(AVIOContext **ctx)
160 {
161  int buf_size = 32768;
162  uint8_t *buf = av_malloc(buf_size);
163  if (!buf)
164  return AVERROR(ENOMEM);
165  *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
166  if (!*ctx) {
167  av_free(buf);
168  return AVERROR(ENOMEM);
169  }
170  return 0;
171 }
172 
173 static void close_null_ctx(AVIOContext *pb)
174 {
175  av_free(pb->buffer);
176  av_free(pb);
177 }
178 
180 {
181  SegmentContext *seg = s->priv_data;
182  AVFormatContext *oc = NULL;
183  int ret, i;
184 
185  seg->number = 0;
186  seg->offset_time = 0;
187  seg->recording_time = seg->time * 1000000;
188  if (!seg->write_header_trailer)
189  seg->individual_header_trailer = 0;
190 
191  if (seg->list && seg->list_type != LIST_HLS)
192  if ((ret = avio_open2(&seg->pb, seg->list, AVIO_FLAG_WRITE,
193  &s->interrupt_callback, NULL)) < 0)
194  goto fail;
195 
196  for (i = 0; i < s->nb_streams; i++)
197  seg->has_video +=
199 
200  if (seg->has_video > 1)
202  "More than a single video stream present, "
203  "expect issues decoding it.\n");
204 
205  seg->oformat = av_guess_format(seg->format, s->filename, NULL);
206 
207  if (!seg->oformat) {
209  goto fail;
210  }
211  if (seg->oformat->flags & AVFMT_NOFILE) {
212  av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
213  seg->oformat->name);
214  ret = AVERROR(EINVAL);
215  goto fail;
216  }
217 
218  if ((ret = segment_mux_init(s)) < 0)
219  goto fail;
220  oc = seg->avf;
221 
222  if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
223  s->filename, seg->number++) < 0) {
224  ret = AVERROR(EINVAL);
225  goto fail;
226  }
227 
228  if (seg->write_header_trailer) {
229  if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
230  &s->interrupt_callback, NULL)) < 0)
231  goto fail;
232  } else {
233  if ((ret = open_null_ctx(&oc->pb)) < 0)
234  goto fail;
235  }
236 
237  if ((ret = avformat_write_header(oc, NULL)) < 0) {
238  avio_close(oc->pb);
239  goto fail;
240  }
241 
242  if (!seg->write_header_trailer) {
243  close_null_ctx(oc->pb);
244  if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
245  &s->interrupt_callback, NULL)) < 0)
246  goto fail;
247  }
248 
249  if (seg->list) {
250  if (seg->list_type == LIST_HLS) {
251  if ((ret = segment_hls_window(s, 0)) < 0)
252  goto fail;
253  } else {
254  avio_printf(seg->pb, "%s\n", oc->filename);
255  avio_flush(seg->pb);
256  }
257  }
258 
259 fail:
260  if (ret) {
261  if (seg->list)
262  avio_close(seg->pb);
263  if (seg->avf)
265  }
266  return ret;
267 }
268 
270 {
271  SegmentContext *seg = s->priv_data;
272  AVFormatContext *oc = seg->avf;
273  AVStream *st = s->streams[pkt->stream_index];
274  int64_t end_pts = seg->recording_time * seg->number;
275  int ret, can_split = 1;
276 
277  if (seg->has_video) {
278  can_split = st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
279  pkt->flags & AV_PKT_FLAG_KEY;
280  }
281 
282  if (can_split && av_compare_ts(pkt->pts, st->time_base, end_pts,
283  AV_TIME_BASE_Q) >= 0) {
284  av_log(s, AV_LOG_DEBUG, "Next segment starts at %d %"PRId64"\n",
285  pkt->stream_index, pkt->pts);
286 
287  ret = segment_end(oc, seg->individual_header_trailer);
288 
289  if (!ret)
291 
292  if (ret)
293  goto fail;
294 
295  oc = seg->avf;
296 
297  if (seg->list) {
298  if (seg->list_type == LIST_HLS) {
299  if ((ret = segment_hls_window(s, 0)) < 0)
300  goto fail;
301  } else {
302  avio_printf(seg->pb, "%s\n", oc->filename);
303  avio_flush(seg->pb);
304  if (seg->size && !(seg->number % seg->size)) {
305  avio_closep(&seg->pb);
306  if ((ret = avio_open2(&seg->pb, seg->list, AVIO_FLAG_WRITE,
307  &s->interrupt_callback, NULL)) < 0)
308  goto fail;
309  }
310  }
311  }
312  }
313 
314  ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
315 
316 fail:
317  if (ret < 0) {
318  if (seg->list)
319  avio_close(seg->pb);
321  }
322 
323  return ret;
324 }
325 
326 static int seg_write_trailer(struct AVFormatContext *s)
327 {
328  SegmentContext *seg = s->priv_data;
329  AVFormatContext *oc = seg->avf;
330  int ret;
331  if (!seg->write_header_trailer) {
332  if ((ret = segment_end(oc, 0)) < 0)
333  goto fail;
334  open_null_ctx(&oc->pb);
335  ret = av_write_trailer(oc);
336  close_null_ctx(oc->pb);
337  } else {
338  ret = segment_end(oc, 1);
339  }
340 
341  if (ret < 0)
342  goto fail;
343 
344  if (seg->list && seg->list_type == LIST_HLS) {
345  if ((ret = segment_hls_window(s, 1) < 0))
346  goto fail;
347  }
348 
349 fail:
350  avio_close(seg->pb);
352  return ret;
353 }
354 
355 #define OFFSET(x) offsetof(SegmentContext, x)
356 #define E AV_OPT_FLAG_ENCODING_PARAM
357 static const AVOption options[] = {
358  { "segment_format", "container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
359  { "segment_time", "segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E },
360  { "segment_list", "output the segment list", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
361  { "segment_list_size", "maximum number of playlist entries", OFFSET(size), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E },
362  { "segment_list_type", "segment list format", OFFSET(list_type), AV_OPT_TYPE_INT, {.i64 = LIST_FLAT}, 0, 2, E, "list_type" },
363  { "flat", "plain list (default)", 0, AV_OPT_TYPE_CONST, {.i64 = LIST_FLAT}, 0, 0, E, "list_type" },
364  { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64 = LIST_HLS}, 0, 0, E, "list_type" },
365  { "segment_wrap", "number after which the index wraps", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
366  { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
367  { "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 },
368  { NULL },
369 };
370 
371 static const AVClass seg_class = {
372  .class_name = "segment muxer",
373  .item_name = av_default_item_name,
374  .option = options,
375  .version = LIBAVUTIL_VERSION_INT,
376 };
377 
378 
380  .name = "segment",
381  .long_name = NULL_IF_CONFIG_SMALL("segment"),
382  .priv_data_size = sizeof(SegmentContext),
383  .flags = AVFMT_NOFILE,
387  .priv_class = &seg_class,
388 };
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:1097
AVOption.
Definition: opt.h:233
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:302
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
Write a packet to an output media file.
Definition: mux.c:454
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:129
static int segment_start(AVFormatContext *s, int write_header)
Definition: segment.c:111
static int write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: assenc.c:58
int size
Set by a private option.
Definition: segment.c:42
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:747
#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:138
static int seg_write_header(AVFormatContext *s)
Definition: segment.c:179
static void close_null_ctx(AVIOContext *pb)
Definition: segment.c:173
static int segment_mux_init(AVFormatContext *s)
Definition: segment.c:57
Format I/O context.
Definition: avformat.h:871
static int segment_hls_window(AVFormatContext *s, int last)
Definition: segment.c:81
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:49
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:456
uint8_t
int wrap
Set by a private option.
Definition: segment.c:43
AVOptions.
static int seg_write_trailer(struct AVFormatContext *s)
Definition: segment.c:326
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:935
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition: options.c:98
int64_t offset_time
Definition: segment.c:46
static int flags
Definition: log.c:44
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:890
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1023
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:44
#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:142
int avio_close(AVIOContext *s)
Close the resource accessed by the AVIOContext s and free it.
Definition: aviobuf.c:794
#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:148
AVStream * avformat_new_stream(AVFormatContext *s, AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:2662
#define FFMAX(a, b)
Definition: common.h:55
#define OFFSET(x)
Definition: segment.c:355
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:127
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:702
float time
Set by a private option.
Definition: segment.c:41
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:923
int void avio_flush(AVIOContext *s)
Definition: aviobuf.c:180
char filename[1024]
input or output filename
Definition: avformat.h:943
static int segment_end(AVFormatContext *oc, int write_trailer)
Definition: segment.c:147
const char * name
Definition: avformat.h:437
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:118
const AVClass * priv_class
AVClass for the private context.
Definition: avformat.h:465
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:2959
static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: segment.c:269
Stream structure.
Definition: avformat.h:683
char * list
Set by a private option.
Definition: segment.c:39
NULL
Definition: eval.c:55
enum AVMediaType codec_type
Definition: avcodec.h:1062
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:240
AVIOContext * pb
I/O context.
Definition: avformat.h:913
av_default_item_name
Definition: dnxhdenc.c:45
int list_type
Set by a private option.
Definition: segment.c:40
AVOutputFormat ff_segment_muxer
Definition: segment.c:379
Describe the class of an AVClass context structure.
Definition: log.h:33
int has_video
Definition: segment.c:48
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:777
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:2595
misc parsing utilities
int write_header_trailer
Set by a private option.
Definition: segment.c:45
static const AVClass seg_class
Definition: segment.c:371
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:400
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:723
#define E
Definition: segment.c:356
int64_t recording_time
Definition: segment.c:47
void * priv_data
Format private data.
Definition: avformat.h:899
static const AVOption options[]
Definition: segment.c:357
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:684
static int open_null_ctx(AVIOContext **ctx)
Definition: segment.c:159
#define AVERROR_MUXER_NOT_FOUND
Muxer not found.
Definition: error.h:55
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:719
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:808
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition: opt.c:210
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