]> git.sesse.net Git - ffmpeg/blob - libavformat/segment.c
1e928a7ebf7e772a4436fc84dfeba199d1f4cef9
[ffmpeg] / libavformat / segment.c
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;  /**< Class for private options. */
35     int number;
36     AVOutputFormat *oformat;
37     AVFormatContext *avf;
38     char *format;          /**< Set by a private option. */
39     char *list;            /**< Set by a private option. */
40     float time;            /**< Set by a private option. */
41     int  size;             /**< Set by a private option. */
42     int  wrap;             /**< Set by a private option. */
43     int  individual_header_trailer; /**< Set by a private option. */
44     int  write_header_trailer; /**< Set by a private option. */
45     int64_t offset_time;
46     int64_t recording_time;
47     int has_video;
48     AVIOContext *pb;
49 } SegmentContext;
50
51 static int segment_mux_init(AVFormatContext *s)
52 {
53     SegmentContext *seg = s->priv_data;
54     AVFormatContext *oc;
55     int i;
56
57     seg->avf = oc = avformat_alloc_context();
58     if (!oc)
59         return AVERROR(ENOMEM);
60
61     oc->oformat            = seg->oformat;
62     oc->interrupt_callback = s->interrupt_callback;
63
64     for (i = 0; i < s->nb_streams; i++) {
65         AVStream *st;
66         if (!(st = avformat_new_stream(oc, NULL)))
67             return AVERROR(ENOMEM);
68         avcodec_copy_context(st->codec, s->streams[i]->codec);
69         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
70     }
71
72     return 0;
73 }
74
75 static int segment_start(AVFormatContext *s, int write_header)
76 {
77     SegmentContext *c = s->priv_data;
78     AVFormatContext *oc = c->avf;
79     int err = 0;
80
81     if (write_header) {
82         avformat_free_context(oc);
83         c->avf = NULL;
84         if ((err = segment_mux_init(s)) < 0)
85             return err;
86         oc = c->avf;
87     }
88
89     if (c->wrap)
90         c->number %= c->wrap;
91
92     if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
93                               s->filename, c->number++) < 0)
94         return AVERROR(EINVAL);
95
96     if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
97                           &s->interrupt_callback, NULL)) < 0)
98         return err;
99
100     if (oc->oformat->priv_class && oc->priv_data)
101         av_opt_set(oc->priv_data, "resend_headers", "1", 0);
102
103     if (write_header) {
104         if ((err = avformat_write_header(oc, NULL)) < 0)
105             return err;
106     }
107
108     return 0;
109 }
110
111 static int segment_end(AVFormatContext *oc, int write_trailer)
112 {
113     int ret = 0;
114
115     av_write_frame(oc, NULL); /* Flush any buffered data */
116     if (write_trailer)
117         av_write_trailer(oc);
118     avio_close(oc->pb);
119
120     return ret;
121 }
122
123 static int open_null_ctx(AVIOContext **ctx)
124 {
125     int buf_size = 32768;
126     uint8_t *buf = av_malloc(buf_size);
127     if (!buf)
128         return AVERROR(ENOMEM);
129     *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
130     if (!*ctx) {
131         av_free(buf);
132         return AVERROR(ENOMEM);
133     }
134     return 0;
135 }
136
137 static void close_null_ctx(AVIOContext *pb)
138 {
139     av_free(pb->buffer);
140     av_free(pb);
141 }
142
143 static int seg_write_header(AVFormatContext *s)
144 {
145     SegmentContext *seg = s->priv_data;
146     AVFormatContext *oc = NULL;
147     int ret, i;
148
149     seg->number = 0;
150     seg->offset_time = 0;
151     seg->recording_time = seg->time * 1000000;
152     if (!seg->write_header_trailer)
153         seg->individual_header_trailer = 0;
154
155     if (seg->list)
156         if ((ret = avio_open2(&seg->pb, seg->list, AVIO_FLAG_WRITE,
157                               &s->interrupt_callback, NULL)) < 0)
158             goto fail;
159
160     for (i = 0; i < s->nb_streams; i++)
161         seg->has_video +=
162             (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO);
163
164     if (seg->has_video > 1)
165         av_log(s, AV_LOG_WARNING,
166                "More than a single video stream present, "
167                "expect issues decoding it.\n");
168
169     seg->oformat = av_guess_format(seg->format, s->filename, NULL);
170
171     if (!seg->oformat) {
172         ret = AVERROR_MUXER_NOT_FOUND;
173         goto fail;
174     }
175     if (seg->oformat->flags & AVFMT_NOFILE) {
176         av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
177                oc->oformat->name);
178         ret = AVERROR(EINVAL);
179         goto fail;
180     }
181
182     if ((ret = segment_mux_init(s)) < 0)
183         goto fail;
184     oc = seg->avf;
185
186     if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
187                               s->filename, seg->number++) < 0) {
188         ret = AVERROR(EINVAL);
189         goto fail;
190     }
191
192     if (seg->write_header_trailer) {
193         if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
194                               &s->interrupt_callback, NULL)) < 0)
195             goto fail;
196     } else {
197         if ((ret = open_null_ctx(&oc->pb)) < 0)
198             goto fail;
199     }
200
201     if ((ret = avformat_write_header(oc, NULL)) < 0) {
202         avio_close(oc->pb);
203         goto fail;
204     }
205
206     if (!seg->write_header_trailer) {
207         close_null_ctx(oc->pb);
208         if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
209                               &s->interrupt_callback, NULL)) < 0)
210             goto fail;
211     }
212
213     if (seg->list) {
214         avio_printf(seg->pb, "%s\n", oc->filename);
215         avio_flush(seg->pb);
216     }
217
218 fail:
219     if (ret) {
220         if (seg->list)
221             avio_close(seg->pb);
222         if (seg->avf)
223             avformat_free_context(seg->avf);
224     }
225     return ret;
226 }
227
228 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
229 {
230     SegmentContext *seg = s->priv_data;
231     AVFormatContext *oc = seg->avf;
232     AVStream *st = s->streams[pkt->stream_index];
233     int64_t end_pts = seg->recording_time * seg->number;
234     int ret;
235
236     if ((seg->has_video && st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
237         av_compare_ts(pkt->pts, st->time_base,
238                       end_pts, AV_TIME_BASE_Q) >= 0 &&
239         pkt->flags & AV_PKT_FLAG_KEY) {
240
241         av_log(s, AV_LOG_DEBUG, "Next segment starts at %d %"PRId64"\n",
242                pkt->stream_index, pkt->pts);
243
244         ret = segment_end(oc, seg->individual_header_trailer);
245
246         if (!ret)
247             ret = segment_start(s, seg->individual_header_trailer);
248
249         if (ret)
250             goto fail;
251
252         oc = seg->avf;
253
254         if (seg->list) {
255             avio_printf(seg->pb, "%s\n", oc->filename);
256             avio_flush(seg->pb);
257             if (seg->size && !(seg->number % seg->size)) {
258                 avio_close(seg->pb);
259                 if ((ret = avio_open2(&seg->pb, seg->list, AVIO_FLAG_WRITE,
260                                       &s->interrupt_callback, NULL)) < 0)
261                     goto fail;
262             }
263         }
264     }
265
266     ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
267
268 fail:
269     if (ret < 0) {
270         if (seg->list)
271             avio_close(seg->pb);
272         avformat_free_context(oc);
273     }
274
275     return ret;
276 }
277
278 static int seg_write_trailer(struct AVFormatContext *s)
279 {
280     SegmentContext *seg = s->priv_data;
281     AVFormatContext *oc = seg->avf;
282     int ret;
283     if (!seg->write_header_trailer) {
284         ret = segment_end(oc, 0);
285         open_null_ctx(&oc->pb);
286         av_write_trailer(oc);
287         close_null_ctx(oc->pb);
288     } else {
289         ret = segment_end(oc, 1);
290     }
291     if (seg->list)
292         avio_close(seg->pb);
293     avformat_free_context(oc);
294     return ret;
295 }
296
297 #define OFFSET(x) offsetof(SegmentContext, x)
298 #define E AV_OPT_FLAG_ENCODING_PARAM
299 static const AVOption options[] = {
300     { "segment_format",    "container format used for the segments",  OFFSET(format),  AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E },
301     { "segment_time",      "segment length in seconds",               OFFSET(time),    AV_OPT_TYPE_FLOAT,  {.dbl = 2},     0, FLT_MAX, E },
302     { "segment_list",      "output the segment list",                 OFFSET(list),    AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E },
303     { "segment_list_size", "maximum number of playlist entries",      OFFSET(size),    AV_OPT_TYPE_INT,    {.i64 = 5},     0, INT_MAX, E },
304     { "segment_wrap",      "number after which the index wraps",      OFFSET(wrap),    AV_OPT_TYPE_INT,    {.i64 = 0},     0, INT_MAX, E },
305     { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
306     { "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 },
307     { NULL },
308 };
309
310 static const AVClass seg_class = {
311     .class_name = "segment muxer",
312     .item_name  = av_default_item_name,
313     .option     = options,
314     .version    = LIBAVUTIL_VERSION_INT,
315 };
316
317
318 AVOutputFormat ff_segment_muxer = {
319     .name           = "segment",
320     .long_name      = NULL_IF_CONFIG_SMALL("segment"),
321     .priv_data_size = sizeof(SegmentContext),
322     .flags          = AVFMT_GLOBALHEADER | AVFMT_NOFILE,
323     .write_header   = seg_write_header,
324     .write_packet   = seg_write_packet,
325     .write_trailer  = seg_write_trailer,
326     .priv_class     = &seg_class,
327 };