FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
webm_chunk.c
Go to the documentation of this file.
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"
43 #include "libavutil/timestamp.h"
44 
45 #define MAX_FILENAME_SIZE 1024
46 
47 typedef struct WebMChunkContext {
48  const AVClass *class;
53  char *http_method;
54  uint64_t duration_written;
55  int prev_pts;
59 
61 {
62  WebMChunkContext *wc = s->priv_data;
63  AVFormatContext *oc;
64  int ret;
65 
67  if (ret < 0)
68  return ret;
69  oc = wc->avf;
70 
72  oc->max_delay = s->max_delay;
73  av_dict_copy(&oc->metadata, s->metadata, 0);
74 
75  *(const AVClass**)oc->priv_data = oc->oformat->priv_class;
77  av_opt_set_int(oc->priv_data, "dash", 1, 0);
78  av_opt_set_int(oc->priv_data, "cluster_time_limit", wc->chunk_duration, 0);
79  av_opt_set_int(oc->priv_data, "live", 1, 0);
80 
81  oc->streams = s->streams;
82  oc->nb_streams = s->nb_streams;
83 
84  return 0;
85 }
86 
87 static int get_chunk_filename(AVFormatContext *s, int is_header, char *filename)
88 {
89  WebMChunkContext *wc = s->priv_data;
90  AVFormatContext *oc = wc->avf;
91  if (!filename) {
92  return AVERROR(EINVAL);
93  }
94  if (is_header) {
95  if (!wc->header_filename) {
96  av_log(oc, AV_LOG_ERROR, "No header filename provided\n");
97  return AVERROR(EINVAL);
98  }
99  av_strlcpy(filename, wc->header_filename, strlen(wc->header_filename) + 1);
100  } else {
102  s->url, wc->chunk_index - 1) < 0) {
103  av_log(oc, AV_LOG_ERROR, "Invalid chunk filename template '%s'\n", s->url);
104  return AVERROR(EINVAL);
105  }
106  }
107  return 0;
108 }
109 
111 {
112  WebMChunkContext *wc = s->priv_data;
113  AVFormatContext *oc = NULL;
114  int ret;
115  int i;
117  char oc_filename[MAX_FILENAME_SIZE];
118  char *oc_url;
119 
120  // DASH Streams can only have either one track per file.
121  if (s->nb_streams != 1) { return AVERROR_INVALIDDATA; }
122 
123  wc->chunk_index = wc->chunk_start_index;
124  wc->oformat = av_guess_format("webm", s->url, "video/webm");
125  if (!wc->oformat)
127 
128  ret = chunk_mux_init(s);
129  if (ret < 0)
130  return ret;
131  oc = wc->avf;
132  ret = get_chunk_filename(s, 1, oc_filename);
133  if (ret < 0)
134  return ret;
135  oc_url = av_strdup(oc_filename);
136  if (!oc_url)
137  return AVERROR(ENOMEM);
138  ff_format_set_url(oc, oc_url);
139  if (wc->http_method)
140  av_dict_set(&options, "method", wc->http_method, 0);
141  ret = s->io_open(s, &oc->pb, oc->url, AVIO_FLAG_WRITE, &options);
142  av_dict_free(&options);
143  if (ret < 0)
144  return ret;
145 
146  oc->pb->seekable = 0;
147  ret = oc->oformat->write_header(oc);
148  if (ret < 0)
149  return ret;
150  ff_format_io_close(s, &oc->pb);
151  for (i = 0; i < s->nb_streams; i++) {
152  // ms precision is the de-facto standard timescale for mkv files.
153  avpriv_set_pts_info(s->streams[i], 64, 1, 1000);
154  }
155  return 0;
156 }
157 
159 {
160  WebMChunkContext *wc = s->priv_data;
161  AVFormatContext *oc = wc->avf;
162  int ret;
163 
164  ret = avio_open_dyn_buf(&oc->pb);
165  if (ret < 0)
166  return ret;
167  wc->chunk_index++;
168  return 0;
169 }
170 
172 {
173  WebMChunkContext *wc = s->priv_data;
174  AVFormatContext *oc = wc->avf;
175  int ret;
176  int buffer_size;
177  uint8_t *buffer;
178  AVIOContext *pb;
179  char filename[MAX_FILENAME_SIZE];
181 
182  if (wc->chunk_start_index == wc->chunk_index)
183  return 0;
184  // Flush the cluster in WebM muxer.
185  oc->oformat->write_packet(oc, NULL);
186  buffer_size = avio_close_dyn_buf(oc->pb, &buffer);
187  ret = get_chunk_filename(s, 0, filename);
188  if (ret < 0)
189  goto fail;
190  if (wc->http_method)
191  av_dict_set(&options, "method", wc->http_method, 0);
192  ret = s->io_open(s, &pb, filename, AVIO_FLAG_WRITE, &options);
193  if (ret < 0)
194  goto fail;
195  avio_write(pb, buffer, buffer_size);
196  ff_format_io_close(s, &pb);
197  oc->pb = NULL;
198 fail:
199  av_dict_free(&options);
200  av_free(buffer);
201  return (ret < 0) ? ret : 0;
202 }
203 
205 {
206  WebMChunkContext *wc = s->priv_data;
207  AVFormatContext *oc = wc->avf;
208  AVStream *st = s->streams[pkt->stream_index];
209  int ret;
210 
211  if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
212  wc->duration_written += av_rescale_q(pkt->pts - wc->prev_pts,
213  st->time_base,
214  (AVRational) {1, 1000});
215  wc->prev_pts = pkt->pts;
216  }
217 
218  // For video, a new chunk is started only on key frames. For audio, a new
219  // chunk is started based on chunk_duration.
220  if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
221  (pkt->flags & AV_PKT_FLAG_KEY)) ||
222  (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
223  (pkt->pts == 0 || wc->duration_written >= wc->chunk_duration))) {
224  wc->duration_written = 0;
225  if ((ret = chunk_end(s)) < 0 || (ret = chunk_start(s)) < 0) {
226  goto fail;
227  }
228  }
229 
230  ret = oc->oformat->write_packet(oc, pkt);
231  if (ret < 0)
232  goto fail;
233 
234 fail:
235  if (ret < 0) {
236  oc->streams = NULL;
237  oc->nb_streams = 0;
239  }
240 
241  return ret;
242 }
243 
245 {
246  WebMChunkContext *wc = s->priv_data;
247  AVFormatContext *oc = wc->avf;
248  oc->oformat->write_trailer(oc);
249  chunk_end(s);
250  oc->streams = NULL;
251  oc->nb_streams = 0;
253  return 0;
254 }
255 
256 #define OFFSET(x) offsetof(WebMChunkContext, x)
257 static const AVOption options[] = {
258  { "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 },
259  { "header", "filename of the header where the initialization data will be written", OFFSET(header_filename), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_ENCODING_PARAM },
260  { "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 },
261  { "method", "set the HTTP method", OFFSET(http_method), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM },
262  { NULL },
263 };
264 
265 #if CONFIG_WEBM_CHUNK_MUXER
266 static const AVClass webm_chunk_class = {
267  .class_name = "WebM Chunk Muxer",
268  .item_name = av_default_item_name,
269  .option = options,
270  .version = LIBAVUTIL_VERSION_INT,
271 };
272 
274  .name = "webm_chunk",
275  .long_name = NULL_IF_CONFIG_SMALL("WebM Chunk Muxer"),
276  .mime_type = "video/webm",
277  .extensions = "chk",
280  .priv_data_size = sizeof(WebMChunkContext),
284  .priv_class = &webm_chunk_class,
285 };
286 #endif
static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int unqueue)
Definition: ffmpeg.c:689
#define NULL
Definition: coverity.c:32
Bytestream IO Context.
Definition: avio.h:161
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
Buffered I/O operations.
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1629
int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition: aviobuf.c:1420
AVOption.
Definition: opt.h:246
static int chunk_start(AVFormatContext *s)
Definition: webm_chunk.c:158
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:4882
void av_opt_set_defaults(void *s)
Set the values of all AVOption fields to their default values.
Definition: opt.c:1305
AVFormatContext * avf
Definition: webm_chunk.c:57
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:191
uint64_t duration_written
Definition: webm_chunk.c:54
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:655
int av_dict_copy(AVDictionary **dst, const AVDictionary *src, int flags)
Copy entries from one AVDictionary struct into another.
Definition: dict.c:217
int(* write_packet)(struct AVFormatContext *, AVPacket *pkt)
Write a packet.
Definition: avformat.h:558
static AVPacket pkt
int avio_open_dyn_buf(AVIOContext **s)
Open a write only memory stream.
Definition: aviobuf.c:1391
char * http_method
Definition: webm_chunk.c:53
#define AVFMT_TS_NONSTRICT
Format does not require strictly increasing timestamps, but they must still be monotonic.
Definition: avformat.h:479
Format I/O context.
Definition: avformat.h:1351
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:72
uint8_t
AVOptions.
timestamp utils, mostly useful for debugging/logging purposes
void ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
Definition: utils.c:5670
#define MAX_FILENAME_SIZE
Definition: webm_chunk.c:45
static int get_chunk_filename(AVFormatContext *s, int is_header, char *filename)
Definition: webm_chunk.c:87
char * header_filename
Definition: webm_chunk.c:50
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1419
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:218
AVOutputFormat * oformat
Definition: webm_chunk.c:56
#define av_log(a,...)
#define AV_OPT_FLAG_ENCODING_PARAM
a generic parameter which can be set by the user for muxing or encoding
Definition: opt.h:276
struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:1370
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1477
int avformat_alloc_output_context2(AVFormatContext **ctx, AVOutputFormat *oformat, const char *format_name, const char *filename)
Allocate an AVFormatContext for an output format.
Definition: mux.c:148
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:142
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1591
#define AVERROR(e)
Definition: error.h:43
static const AVOption options[]
Definition: webm_chunk.c:257
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:186
int(* write_header)(struct AVFormatContext *)
Definition: avformat.h:550
char * url
input or output URL.
Definition: avformat.h:1447
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values. ...
Definition: dict.c:203
enum AVMediaType codec_type
General type of the encoded data.
Definition: avcodec.h:3896
int av_opt_set_int(void *obj, const char *name, int64_t val, int search_flags)
Definition: opt.c:568
static int chunk_mux_init(AVFormatContext *s)
Definition: webm_chunk.c:60
simple assert() macros that are a bit more flexible than ISO C assert().
size_t av_strlcpy(char *dst, const char *src, size_t size)
Copy the string src to dst, but no more than size - 1 bytes, and null-terminate dst.
Definition: avstring.c:83
#define fail()
Definition: checkasm.h:117
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1451
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1407
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:260
static int write_trailer(AVFormatContext *s1)
Definition: v4l2enc.c:94
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition: avformat.h:468
const char * name
Definition: avformat.h:507
#define OFFSET(x)
Definition: webm_chunk.c:256
#define s(width, name)
Definition: cbs_vp9.c:257
static int webm_chunk_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: webm_chunk.c:204
void ff_format_set_url(AVFormatContext *s, char *url)
Set AVFormatContext url field to the provided pointer.
Definition: utils.c:5830
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:51
const AVClass * priv_class
AVClass for the private context.
Definition: avformat.h:535
int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
Definition: utils.c:4723
Stream structure.
Definition: avformat.h:874
char * av_strdup(const char *s)
Duplicate a string.
Definition: mem.c:251
AVIOContext * pb
I/O context.
Definition: avformat.h:1393
static int webm_chunk_write_header(AVFormatContext *s)
Definition: webm_chunk.c:110
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:70
Describe the class of an AVClass context structure.
Definition: log.h:67
AVOutputFormat ff_webm_chunk_muxer
Rational number (pair of numerator and denominator).
Definition: rational.h:58
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:4389
misc parsing utilities
static int chunk_end(AVFormatContext *s)
Definition: webm_chunk.c:171
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:465
static int webm_chunk_write_trailer(AVFormatContext *s)
Definition: webm_chunk.c:244
#define av_free(p)
void * priv_data
Format private data.
Definition: avformat.h:1379
static void write_header(FFV1Context *f)
Definition: ffv1enc.c:337
#define AVERROR_MUXER_NOT_FOUND
Muxer not found.
Definition: error.h:60
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:1021
int stream_index
Definition: avcodec.h:1447
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:903
int(* io_open)(struct AVFormatContext *s, AVIOContext **pb, const char *url, int flags, AVDictionary **options)
A callback for opening new IO streams.
Definition: avformat.h:1933
This structure stores compressed data.
Definition: avcodec.h:1422
int(* write_trailer)(struct AVFormatContext *)
Definition: avformat.h:559
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1438
GLuint buffer
Definition: opengl_enc.c:102
#define AVFMT_NEEDNUMBER
Needs 'd' in filename.
Definition: avformat.h:466