]> git.sesse.net Git - ffmpeg/blob - libavformat/webm_chunk.c
avformat/webm_chunk: Use API functions for child muxer
[ffmpeg] / libavformat / webm_chunk.c
1 /*
2  * Copyright (c) 2015, Vignesh Venkatasubramanian
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file WebM Chunk Muxer
23  * The chunk muxer enables writing WebM Live chunks where there is a header
24  * chunk, followed by data chunks where each Cluster is written out as a Chunk.
25  */
26
27 #include <float.h>
28 #include <time.h>
29
30 #include "avformat.h"
31 #include "avio.h"
32 #include "avio_internal.h"
33 #include "internal.h"
34
35 #include "libavutil/avassert.h"
36 #include "libavutil/log.h"
37 #include "libavutil/opt.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/parseutils.h"
40 #include "libavutil/mathematics.h"
41 #include "libavutil/time.h"
42 #include "libavutil/time_internal.h"
43 #include "libavutil/timestamp.h"
44
45 #define MAX_FILENAME_SIZE 1024
46
47 typedef struct WebMChunkContext {
48     const AVClass *class;
49     int chunk_start_index;
50     char *header_filename;
51     int chunk_duration;
52     int chunk_index;
53     char *http_method;
54     uint64_t duration_written;
55     int64_t prev_pts;
56     ff_const59 AVOutputFormat *oformat;
57     AVFormatContext *avf;
58 } WebMChunkContext;
59
60 static int chunk_mux_init(AVFormatContext *s)
61 {
62     WebMChunkContext *wc = s->priv_data;
63     AVFormatContext *oc;
64     AVStream *st, *ost = s->streams[0];
65     AVDictionary *dict = NULL;
66     int ret;
67
68     ret = avformat_alloc_output_context2(&wc->avf, wc->oformat, NULL, NULL);
69     if (ret < 0)
70         return ret;
71     oc = wc->avf;
72
73     oc->interrupt_callback = s->interrupt_callback;
74     oc->max_delay          = s->max_delay;
75     oc->flags                 = s->flags;
76     oc->strict_std_compliance = s->strict_std_compliance;
77     oc->avoid_negative_ts     = s->avoid_negative_ts;
78
79     av_dict_copy(&oc->metadata, s->metadata, 0);
80
81     if (!(st = avformat_new_stream(oc, NULL)))
82         return AVERROR(ENOMEM);
83
84     if ((ret = avcodec_parameters_copy(st->codecpar, ost->codecpar)) < 0 ||
85         (ret = av_dict_copy(&st->metadata, ost->metadata, 0))        < 0)
86         return ret;
87
88     st->sample_aspect_ratio = ost->sample_aspect_ratio;
89     st->disposition         = ost->disposition;
90     avpriv_set_pts_info(st, ost->pts_wrap_bits, ost->time_base.num,
91                                                 ost->time_base.den);
92
93     av_dict_set_int(&dict, "dash", 1, 0);
94     av_dict_set_int(&dict, "cluster_time_limit", wc->chunk_duration, 0);
95     av_dict_set_int(&dict, "live", 1, 0);
96
97     ret = avformat_init_output(oc, &dict);
98     av_dict_free(&dict);
99     if (ret < 0)
100         return ret;
101
102     // Copy the timing info back to the original stream
103     // so that the timestamps of the packets are directly usable
104     avpriv_set_pts_info(ost, st->pts_wrap_bits, st->time_base.num,
105                                                 st->time_base.den);
106
107     // This ensures that the timestamps will already be properly shifted
108     // when the packets arrive here, so we don't need to shift again.
109     s->avoid_negative_ts  = oc->avoid_negative_ts;
110     s->internal->avoid_negative_ts_use_pts =
111         oc->internal->avoid_negative_ts_use_pts;
112     oc->avoid_negative_ts = 0;
113
114     return 0;
115 }
116
117 static int get_chunk_filename(AVFormatContext *s, int is_header, char filename[MAX_FILENAME_SIZE])
118 {
119     WebMChunkContext *wc = s->priv_data;
120     if (!filename) {
121         return AVERROR(EINVAL);
122     }
123     if (is_header) {
124         int len;
125         if (!wc->header_filename) {
126             av_log(s, AV_LOG_ERROR, "No header filename provided\n");
127             return AVERROR(EINVAL);
128         }
129         len = av_strlcpy(filename, wc->header_filename, MAX_FILENAME_SIZE);
130         if (len >= MAX_FILENAME_SIZE) {
131             av_log(s, AV_LOG_ERROR, "Header filename too long\n");
132             return AVERROR(EINVAL);
133         }
134     } else {
135         if (av_get_frame_filename(filename, MAX_FILENAME_SIZE,
136                                   s->url, wc->chunk_index - 1) < 0) {
137             av_log(s, AV_LOG_ERROR, "Invalid chunk filename template '%s'\n", s->url);
138             return AVERROR(EINVAL);
139         }
140     }
141     return 0;
142 }
143
144 static int webm_chunk_write_header(AVFormatContext *s)
145 {
146     WebMChunkContext *wc = s->priv_data;
147     AVFormatContext *oc = NULL;
148     int ret;
149     AVDictionary *options = NULL;
150     char oc_filename[MAX_FILENAME_SIZE];
151     char *oc_url;
152
153     // DASH Streams can only have either one track per file.
154     if (s->nb_streams != 1) { return AVERROR_INVALIDDATA; }
155
156     wc->chunk_index = wc->chunk_start_index;
157     wc->oformat = av_guess_format("webm", s->url, "video/webm");
158     if (!wc->oformat)
159         return AVERROR_MUXER_NOT_FOUND;
160     wc->prev_pts = AV_NOPTS_VALUE;
161
162     ret = chunk_mux_init(s);
163     if (ret < 0)
164         return ret;
165     oc = wc->avf;
166     ret = get_chunk_filename(s, 1, oc_filename);
167     if (ret < 0)
168         return ret;
169     oc_url = av_strdup(oc_filename);
170     if (!oc_url)
171         return AVERROR(ENOMEM);
172     ff_format_set_url(oc, oc_url);
173     if (wc->http_method)
174         av_dict_set(&options, "method", wc->http_method, 0);
175     ret = s->io_open(s, &oc->pb, oc->url, AVIO_FLAG_WRITE, &options);
176     av_dict_free(&options);
177     if (ret < 0)
178         return ret;
179
180     oc->pb->seekable = 0;
181     ret = avformat_write_header(oc, NULL);
182     ff_format_io_close(s, &oc->pb);
183     if (ret < 0)
184         return ret;
185     return 0;
186 }
187
188 static int chunk_start(AVFormatContext *s)
189 {
190     WebMChunkContext *wc = s->priv_data;
191     AVFormatContext *oc = wc->avf;
192     int ret;
193
194     ret = avio_open_dyn_buf(&oc->pb);
195     if (ret < 0)
196         return ret;
197     wc->chunk_index++;
198     return 0;
199 }
200
201 static int chunk_end(AVFormatContext *s, int flush)
202 {
203     WebMChunkContext *wc = s->priv_data;
204     AVFormatContext *oc = wc->avf;
205     int ret;
206     int buffer_size;
207     uint8_t *buffer;
208     AVIOContext *pb;
209     char filename[MAX_FILENAME_SIZE];
210     AVDictionary *options = NULL;
211
212     if (!oc->pb)
213         return 0;
214
215     if (flush)
216         // Flush the cluster in WebM muxer.
217         av_write_frame(oc, NULL);
218     buffer_size = avio_close_dyn_buf(oc->pb, &buffer);
219     oc->pb = NULL;
220     ret = get_chunk_filename(s, 0, filename);
221     if (ret < 0)
222         goto fail;
223     if (wc->http_method)
224         av_dict_set(&options, "method", wc->http_method, 0);
225     ret = s->io_open(s, &pb, filename, AVIO_FLAG_WRITE, &options);
226     if (ret < 0)
227         goto fail;
228     avio_write(pb, buffer, buffer_size);
229     ff_format_io_close(s, &pb);
230 fail:
231     av_dict_free(&options);
232     av_free(buffer);
233     return (ret < 0) ? ret : 0;
234 }
235
236 static int webm_chunk_write_packet(AVFormatContext *s, AVPacket *pkt)
237 {
238     WebMChunkContext *wc = s->priv_data;
239     AVFormatContext *oc = wc->avf;
240     AVStream *st = s->streams[pkt->stream_index];
241     int ret;
242
243     if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
244         if (wc->prev_pts != AV_NOPTS_VALUE)
245             wc->duration_written += av_rescale_q(pkt->pts - wc->prev_pts,
246                                                  st->time_base,
247                                                  (AVRational) {1, 1000});
248         wc->prev_pts = pkt->pts;
249     }
250
251     // For video, a new chunk is started only on key frames. For audio, a new
252     // chunk is started based on chunk_duration. Also, a new chunk is started
253     // unconditionally if there is no currently open chunk.
254     if (!oc->pb || (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
255          (pkt->flags & AV_PKT_FLAG_KEY)) ||
256         (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
257          wc->duration_written >= wc->chunk_duration)) {
258         wc->duration_written = 0;
259         if ((ret = chunk_end(s, 1)) < 0 || (ret = chunk_start(s)) < 0) {
260             return ret;
261         }
262     }
263
264     // We only have one stream, so use the non-interleaving av_write_frame.
265     return av_write_frame(oc, pkt);
266 }
267
268 static int webm_chunk_write_trailer(AVFormatContext *s)
269 {
270     WebMChunkContext *wc = s->priv_data;
271     AVFormatContext *oc = wc->avf;
272     int ret;
273
274     if (!oc->pb) {
275         ret = chunk_start(s);
276         if (ret < 0)
277             goto fail;
278     }
279     av_write_trailer(oc);
280     ret = chunk_end(s, 0);
281 fail:
282     avformat_free_context(oc);
283     return ret;
284 }
285
286 #define OFFSET(x) offsetof(WebMChunkContext, x)
287 static const AVOption options[] = {
288     { "chunk_start_index",  "start index of the chunk", OFFSET(chunk_start_index), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
289     { "header", "filename of the header where the initialization data will be written", OFFSET(header_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM },
290     { "audio_chunk_duration", "duration of each chunk in milliseconds", OFFSET(chunk_duration), AV_OPT_TYPE_INT, {.i64 = 5000}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
291     { "method", "set the HTTP method", OFFSET(http_method), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0, AV_OPT_FLAG_ENCODING_PARAM },
292     { NULL },
293 };
294
295 #if CONFIG_WEBM_CHUNK_MUXER
296 static const AVClass webm_chunk_class = {
297     .class_name = "WebM Chunk Muxer",
298     .item_name  = av_default_item_name,
299     .option     = options,
300     .version    = LIBAVUTIL_VERSION_INT,
301 };
302
303 AVOutputFormat ff_webm_chunk_muxer = {
304     .name           = "webm_chunk",
305     .long_name      = NULL_IF_CONFIG_SMALL("WebM Chunk Muxer"),
306     .mime_type      = "video/webm",
307     .extensions     = "chk",
308     .flags          = AVFMT_NOFILE | AVFMT_GLOBALHEADER | AVFMT_NEEDNUMBER |
309                       AVFMT_TS_NONSTRICT,
310     .priv_data_size = sizeof(WebMChunkContext),
311     .write_header   = webm_chunk_write_header,
312     .write_packet   = webm_chunk_write_packet,
313     .write_trailer  = webm_chunk_write_trailer,
314     .priv_class     = &webm_chunk_class,
315 };
316 #endif