]> git.sesse.net Git - ffmpeg/blob - libavformat/webm_chunk.c
avformat/webm_chunk: Add deinit function
[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     char *header_filename;
50     int chunk_duration;
51     int chunk_index;
52     char *http_method;
53     uint64_t duration_written;
54     int64_t prev_pts;
55     AVFormatContext *avf;
56 } WebMChunkContext;
57
58 static int webm_chunk_init(AVFormatContext *s)
59 {
60     WebMChunkContext *wc = s->priv_data;
61     ff_const59 AVOutputFormat *oformat;
62     AVFormatContext *oc;
63     AVStream *st, *ost = s->streams[0];
64     AVDictionary *dict = NULL;
65     int ret;
66
67     // DASH Streams can only have one track per file.
68     if (s->nb_streams != 1)
69         return AVERROR(EINVAL);
70
71     if (!wc->header_filename) {
72         av_log(s, AV_LOG_ERROR, "No header filename provided\n");
73         return AVERROR(EINVAL);
74     }
75
76     wc->prev_pts = AV_NOPTS_VALUE;
77
78     oformat = av_guess_format("webm", s->url, "video/webm");
79     if (!oformat)
80         return AVERROR_MUXER_NOT_FOUND;
81
82     ret = avformat_alloc_output_context2(&wc->avf, oformat, NULL, NULL);
83     if (ret < 0)
84         return ret;
85     oc = wc->avf;
86
87     ff_format_set_url(oc, wc->header_filename);
88     wc->header_filename = NULL;
89
90     oc->interrupt_callback = s->interrupt_callback;
91     oc->max_delay          = s->max_delay;
92     oc->flags                 = s->flags & ~AVFMT_FLAG_FLUSH_PACKETS;
93     oc->strict_std_compliance = s->strict_std_compliance;
94     oc->avoid_negative_ts     = s->avoid_negative_ts;
95
96     oc->flush_packets         = 0;
97
98     av_dict_copy(&oc->metadata, s->metadata, 0);
99
100     if (!(st = avformat_new_stream(oc, NULL)))
101         return AVERROR(ENOMEM);
102
103     if ((ret = avcodec_parameters_copy(st->codecpar, ost->codecpar)) < 0 ||
104         (ret = av_dict_copy(&st->metadata, ost->metadata, 0))        < 0)
105         return ret;
106
107     st->sample_aspect_ratio = ost->sample_aspect_ratio;
108     st->disposition         = ost->disposition;
109     avpriv_set_pts_info(st, ost->pts_wrap_bits, ost->time_base.num,
110                                                 ost->time_base.den);
111
112     av_dict_set_int(&dict, "dash", 1, 0);
113     av_dict_set_int(&dict, "cluster_time_limit", wc->chunk_duration, 0);
114     av_dict_set_int(&dict, "live", 1, 0);
115
116     ret = avformat_init_output(oc, &dict);
117     av_dict_free(&dict);
118     if (ret < 0)
119         return ret;
120
121     // Copy the timing info back to the original stream
122     // so that the timestamps of the packets are directly usable
123     avpriv_set_pts_info(ost, st->pts_wrap_bits, st->time_base.num,
124                                                 st->time_base.den);
125
126     // This ensures that the timestamps will already be properly shifted
127     // when the packets arrive here, so we don't need to shift again.
128     s->avoid_negative_ts  = oc->avoid_negative_ts;
129     s->internal->avoid_negative_ts_use_pts =
130         oc->internal->avoid_negative_ts_use_pts;
131     oc->avoid_negative_ts = 0;
132
133     return 0;
134 }
135
136 static int get_chunk_filename(AVFormatContext *s, char filename[MAX_FILENAME_SIZE])
137 {
138     WebMChunkContext *wc = s->priv_data;
139     if (!filename) {
140         return AVERROR(EINVAL);
141     }
142         if (av_get_frame_filename(filename, MAX_FILENAME_SIZE,
143                                   s->url, wc->chunk_index - 1) < 0) {
144             av_log(s, AV_LOG_ERROR, "Invalid chunk filename template '%s'\n", s->url);
145             return AVERROR(EINVAL);
146         }
147     return 0;
148 }
149
150 static int webm_chunk_write_header(AVFormatContext *s)
151 {
152     WebMChunkContext *wc = s->priv_data;
153     AVFormatContext *oc = wc->avf;
154     int ret;
155     AVDictionary *options = NULL;
156
157     if (wc->http_method)
158         av_dict_set(&options, "method", wc->http_method, 0);
159     ret = s->io_open(s, &oc->pb, oc->url, AVIO_FLAG_WRITE, &options);
160     av_dict_free(&options);
161     if (ret < 0)
162         return ret;
163
164     oc->pb->seekable = 0;
165     ret = avformat_write_header(oc, NULL);
166     ff_format_io_close(s, &oc->pb);
167     if (ret < 0)
168         return ret;
169     return 0;
170 }
171
172 static int chunk_start(AVFormatContext *s)
173 {
174     WebMChunkContext *wc = s->priv_data;
175     AVFormatContext *oc = wc->avf;
176     int ret;
177
178     ret = avio_open_dyn_buf(&oc->pb);
179     if (ret < 0)
180         return ret;
181     wc->chunk_index++;
182     return 0;
183 }
184
185 static int chunk_end(AVFormatContext *s, int flush)
186 {
187     WebMChunkContext *wc = s->priv_data;
188     AVFormatContext *oc = wc->avf;
189     int ret;
190     int buffer_size;
191     uint8_t *buffer;
192     AVIOContext *pb;
193     char filename[MAX_FILENAME_SIZE];
194     AVDictionary *options = NULL;
195
196     if (!oc->pb)
197         return 0;
198
199     if (flush)
200         // Flush the cluster in WebM muxer.
201         av_write_frame(oc, NULL);
202     buffer_size = avio_close_dyn_buf(oc->pb, &buffer);
203     oc->pb = NULL;
204     ret = get_chunk_filename(s, filename);
205     if (ret < 0)
206         goto fail;
207     if (wc->http_method)
208         av_dict_set(&options, "method", wc->http_method, 0);
209     ret = s->io_open(s, &pb, filename, AVIO_FLAG_WRITE, &options);
210     if (ret < 0)
211         goto fail;
212     avio_write(pb, buffer, buffer_size);
213     ff_format_io_close(s, &pb);
214 fail:
215     av_dict_free(&options);
216     av_free(buffer);
217     return (ret < 0) ? ret : 0;
218 }
219
220 static int webm_chunk_write_packet(AVFormatContext *s, AVPacket *pkt)
221 {
222     WebMChunkContext *wc = s->priv_data;
223     AVFormatContext *oc = wc->avf;
224     AVStream *st = s->streams[pkt->stream_index];
225     int ret;
226
227     if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
228         if (wc->prev_pts != AV_NOPTS_VALUE)
229             wc->duration_written += av_rescale_q(pkt->pts - wc->prev_pts,
230                                                  st->time_base,
231                                                  (AVRational) {1, 1000});
232         wc->prev_pts = pkt->pts;
233     }
234
235     // For video, a new chunk is started only on key frames. For audio, a new
236     // chunk is started based on chunk_duration. Also, a new chunk is started
237     // unconditionally if there is no currently open chunk.
238     if (!oc->pb || (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
239          (pkt->flags & AV_PKT_FLAG_KEY)) ||
240         (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
241          wc->duration_written >= wc->chunk_duration)) {
242         wc->duration_written = 0;
243         if ((ret = chunk_end(s, 1)) < 0 || (ret = chunk_start(s)) < 0) {
244             return ret;
245         }
246     }
247
248     // We only have one stream, so use the non-interleaving av_write_frame.
249     return av_write_frame(oc, pkt);
250 }
251
252 static int webm_chunk_write_trailer(AVFormatContext *s)
253 {
254     WebMChunkContext *wc = s->priv_data;
255     AVFormatContext *oc = wc->avf;
256     int ret;
257
258     if (!oc->pb) {
259         ret = chunk_start(s);
260         if (ret < 0)
261             return ret;
262     }
263     av_write_trailer(oc);
264     return chunk_end(s, 0);
265 }
266
267 static void webm_chunk_deinit(AVFormatContext *s)
268 {
269     WebMChunkContext *wc = s->priv_data;
270
271     if (!wc->avf)
272         return;
273
274     ffio_free_dyn_buf(&wc->avf->pb);
275     avformat_free_context(wc->avf);
276     wc->avf = NULL;
277 }
278
279 #define OFFSET(x) offsetof(WebMChunkContext, x)
280 static const AVOption options[] = {
281     { "chunk_start_index",  "start index of the chunk", OFFSET(chunk_index), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
282     { "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 },
283     { "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 },
284     { "method", "set the HTTP method", OFFSET(http_method), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0, AV_OPT_FLAG_ENCODING_PARAM },
285     { NULL },
286 };
287
288 #if CONFIG_WEBM_CHUNK_MUXER
289 static const AVClass webm_chunk_class = {
290     .class_name = "WebM Chunk Muxer",
291     .item_name  = av_default_item_name,
292     .option     = options,
293     .version    = LIBAVUTIL_VERSION_INT,
294 };
295
296 AVOutputFormat ff_webm_chunk_muxer = {
297     .name           = "webm_chunk",
298     .long_name      = NULL_IF_CONFIG_SMALL("WebM Chunk Muxer"),
299     .mime_type      = "video/webm",
300     .extensions     = "chk",
301     .flags          = AVFMT_NOFILE | AVFMT_GLOBALHEADER | AVFMT_NEEDNUMBER |
302                       AVFMT_TS_NONSTRICT,
303     .priv_data_size = sizeof(WebMChunkContext),
304     .init           = webm_chunk_init,
305     .write_header   = webm_chunk_write_header,
306     .write_packet   = webm_chunk_write_packet,
307     .write_trailer  = webm_chunk_write_trailer,
308     .deinit         = webm_chunk_deinit,
309     .priv_class     = &webm_chunk_class,
310 };
311 #endif