webm_chunk.c 9.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/*
 * Copyright (c) 2015, Vignesh Venkatasubramanian
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/**
 * @file WebM Chunk Muxer
 * The chunk muxer enables writing WebM Live chunks where there is a header
 * chunk, followed by data chunks where each Cluster is written out as a Chunk.
 */

#include "avformat.h"
#include "avio.h"
29
#include "avio_internal.h"
30 31 32 33 34 35
#include "internal.h"

#include "libavutil/log.h"
#include "libavutil/opt.h"
#include "libavutil/mathematics.h"

36 37
#define MAX_FILENAME_SIZE 1024

38 39 40 41 42
typedef struct WebMChunkContext {
    const AVClass *class;
    char *header_filename;
    int chunk_duration;
    int chunk_index;
43
    char *http_method;
44
    uint64_t duration_written;
45
    int64_t prev_pts;
46
    AVFormatContext *avf;
47
    int header_written;
48 49
} WebMChunkContext;

50
static int webm_chunk_init(AVFormatContext *s)
51 52
{
    WebMChunkContext *wc = s->priv_data;
53
    ff_const59 AVOutputFormat *oformat;
54
    AVFormatContext *oc;
55 56
    AVStream *st, *ost = s->streams[0];
    AVDictionary *dict = NULL;
57 58
    int ret;

59 60 61 62
    // DASH Streams can only have one track per file.
    if (s->nb_streams != 1)
        return AVERROR(EINVAL);

63 64 65 66 67
    if (!wc->header_filename) {
        av_log(s, AV_LOG_ERROR, "No header filename provided\n");
        return AVERROR(EINVAL);
    }

68 69
    wc->prev_pts = AV_NOPTS_VALUE;

70 71 72 73 74
    oformat = av_guess_format("webm", s->url, "video/webm");
    if (!oformat)
        return AVERROR_MUXER_NOT_FOUND;

    ret = avformat_alloc_output_context2(&wc->avf, oformat, NULL, NULL);
75 76 77 78
    if (ret < 0)
        return ret;
    oc = wc->avf;

79 80 81
    ff_format_set_url(oc, wc->header_filename);
    wc->header_filename = NULL;

82 83
    oc->interrupt_callback    = s->interrupt_callback;
    oc->max_delay             = s->max_delay;
84
    oc->flags                 = s->flags & ~AVFMT_FLAG_FLUSH_PACKETS;
85
    oc->strict_std_compliance = s->strict_std_compliance;
86
    oc->avoid_negative_ts     = s->avoid_negative_ts;
87

88 89
    oc->flush_packets         = 0;

90 91
    if ((ret = av_dict_copy(&oc->metadata, s->metadata, 0)) < 0)
        return ret;
92

93 94 95 96 97 98 99 100 101 102 103 104
    if (!(st = avformat_new_stream(oc, NULL)))
        return AVERROR(ENOMEM);

    if ((ret = avcodec_parameters_copy(st->codecpar, ost->codecpar)) < 0 ||
        (ret = av_dict_copy(&st->metadata, ost->metadata, 0))        < 0)
        return ret;

    st->sample_aspect_ratio = ost->sample_aspect_ratio;
    st->disposition         = ost->disposition;
    avpriv_set_pts_info(st, ost->pts_wrap_bits, ost->time_base.num,
                                                ost->time_base.den);

105 106 107 108 109 110 111 112 113
    if (wc->http_method)
        if ((ret = av_dict_set(&dict, "method", wc->http_method, 0)) < 0)
            return ret;
    ret = s->io_open(s, &oc->pb, oc->url, AVIO_FLAG_WRITE, &dict);
    av_dict_free(&dict);
    if (ret < 0)
        return ret;
    oc->pb->seekable = 0;

114 115 116 117 118
    if ((ret = av_dict_set_int(&dict, "dash", 1, 0))   < 0 ||
        (ret = av_dict_set_int(&dict, "cluster_time_limit",
                               wc->chunk_duration, 0)) < 0 ||
        (ret = av_dict_set_int(&dict, "live", 1, 0))   < 0)
        goto fail;
119 120

    ret = avformat_init_output(oc, &dict);
121
fail:
122 123 124 125 126 127 128 129
    av_dict_free(&dict);
    if (ret < 0)
        return ret;

    // Copy the timing info back to the original stream
    // so that the timestamps of the packets are directly usable
    avpriv_set_pts_info(ost, st->pts_wrap_bits, st->time_base.num,
                                                st->time_base.den);
130

131 132 133 134 135 136
    // This ensures that the timestamps will already be properly shifted
    // when the packets arrive here, so we don't need to shift again.
    s->avoid_negative_ts  = oc->avoid_negative_ts;
    s->internal->avoid_negative_ts_use_pts =
        oc->internal->avoid_negative_ts_use_pts;
    oc->avoid_negative_ts = 0;
137 138 139 140

    return 0;
}

141
static int get_chunk_filename(AVFormatContext *s, char filename[MAX_FILENAME_SIZE])
142 143
{
    WebMChunkContext *wc = s->priv_data;
144 145 146
    if (!filename) {
        return AVERROR(EINVAL);
    }
147 148 149 150 151
    if (av_get_frame_filename(filename, MAX_FILENAME_SIZE,
                              s->url, wc->chunk_index - 1) < 0) {
        av_log(s, AV_LOG_ERROR, "Invalid chunk filename template '%s'\n", s->url);
        return AVERROR(EINVAL);
    }
152 153 154 155 156 157
    return 0;
}

static int webm_chunk_write_header(AVFormatContext *s)
{
    WebMChunkContext *wc = s->priv_data;
158
    AVFormatContext *oc = wc->avf;
159 160
    int ret;

161
    ret = avformat_write_header(oc, NULL);
162
    ff_format_io_close(s, &oc->pb);
163
    wc->header_written = 1;
164 165 166 167 168 169 170 171 172 173 174
    if (ret < 0)
        return ret;
    return 0;
}

static int chunk_start(AVFormatContext *s)
{
    WebMChunkContext *wc = s->priv_data;
    AVFormatContext *oc = wc->avf;
    int ret;

175
    ret = avio_open_dyn_buf(&oc->pb);
176 177 178 179 180 181
    if (ret < 0)
        return ret;
    wc->chunk_index++;
    return 0;
}

182
static int chunk_end(AVFormatContext *s, int flush)
183 184 185 186
{
    WebMChunkContext *wc = s->priv_data;
    AVFormatContext *oc = wc->avf;
    int ret;
187 188 189 190
    int buffer_size;
    uint8_t *buffer;
    AVIOContext *pb;
    char filename[MAX_FILENAME_SIZE];
191
    AVDictionary *options = NULL;
192

193
    if (!oc->pb)
194
        return 0;
195 196 197

    if (flush)
        // Flush the cluster in WebM muxer.
198
        av_write_frame(oc, NULL);
199
    buffer_size = avio_close_dyn_buf(oc->pb, &buffer);
200
    oc->pb = NULL;
201
    ret = get_chunk_filename(s, filename);
202
    if (ret < 0)
203
        goto fail;
204
    if (wc->http_method)
205 206
        if ((ret = av_dict_set(&options, "method", wc->http_method, 0)) < 0)
            goto fail;
207
    ret = s->io_open(s, &pb, filename, AVIO_FLAG_WRITE, &options);
208
    av_dict_free(&options);
209 210 211
    if (ret < 0)
        goto fail;
    avio_write(pb, buffer, buffer_size);
212
    ff_format_io_close(s, &pb);
213 214 215
fail:
    av_free(buffer);
    return (ret < 0) ? ret : 0;
216 217 218 219 220 221 222 223 224
}

static int webm_chunk_write_packet(AVFormatContext *s, AVPacket *pkt)
{
    WebMChunkContext *wc = s->priv_data;
    AVFormatContext *oc = wc->avf;
    AVStream *st = s->streams[pkt->stream_index];
    int ret;

225
    if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
226 227 228 229
        if (wc->prev_pts != AV_NOPTS_VALUE)
            wc->duration_written += av_rescale_q(pkt->pts - wc->prev_pts,
                                                 st->time_base,
                                                 (AVRational) {1, 1000});
230 231 232 233
        wc->prev_pts = pkt->pts;
    }

    // For video, a new chunk is started only on key frames. For audio, a new
234 235 236
    // chunk is started based on chunk_duration. Also, a new chunk is started
    // unconditionally if there is no currently open chunk.
    if (!oc->pb || (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
237
         (pkt->flags & AV_PKT_FLAG_KEY)) ||
238
        (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
239
         wc->duration_written >= wc->chunk_duration)) {
240
        wc->duration_written = 0;
241 242
        if ((ret = chunk_end(s, 1)) < 0 || (ret = chunk_start(s)) < 0) {
            return ret;
243 244 245
        }
    }

246 247
    // We only have one stream, so use the non-interleaving av_write_frame.
    return av_write_frame(oc, pkt);
248 249 250 251 252 253
}

static int webm_chunk_write_trailer(AVFormatContext *s)
{
    WebMChunkContext *wc = s->priv_data;
    AVFormatContext *oc = wc->avf;
254 255 256 257 258
    int ret;

    if (!oc->pb) {
        ret = chunk_start(s);
        if (ret < 0)
259
            return ret;
260
    }
261 262 263
    ret = av_write_trailer(oc);
    if (ret < 0)
        return ret;
264 265 266 267 268 269 270 271 272 273
    return chunk_end(s, 0);
}

static void webm_chunk_deinit(AVFormatContext *s)
{
    WebMChunkContext *wc = s->priv_data;

    if (!wc->avf)
        return;

274 275 276 277
    if (wc->header_written)
        ffio_free_dyn_buf(&wc->avf->pb);
    else
        ff_format_io_close(s, &wc->avf->pb);
278 279
    avformat_free_context(wc->avf);
    wc->avf = NULL;
280 281 282 283
}

#define OFFSET(x) offsetof(WebMChunkContext, x)
static const AVOption options[] = {
284
    { "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 },
285
    { "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 },
286
    { "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 },
287
    { "method", "set the HTTP method", OFFSET(http_method), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0, AV_OPT_FLAG_ENCODING_PARAM },
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    { NULL },
};

static const AVClass webm_chunk_class = {
    .class_name = "WebM Chunk Muxer",
    .item_name  = av_default_item_name,
    .option     = options,
    .version    = LIBAVUTIL_VERSION_INT,
};

AVOutputFormat ff_webm_chunk_muxer = {
    .name           = "webm_chunk",
    .long_name      = NULL_IF_CONFIG_SMALL("WebM Chunk Muxer"),
    .mime_type      = "video/webm",
    .extensions     = "chk",
    .flags          = AVFMT_NOFILE | AVFMT_GLOBALHEADER | AVFMT_NEEDNUMBER |
304
                      AVFMT_TS_NONSTRICT,
305
    .priv_data_size = sizeof(WebMChunkContext),
306
    .init           = webm_chunk_init,
307 308 309
    .write_header   = webm_chunk_write_header,
    .write_packet   = webm_chunk_write_packet,
    .write_trailer  = webm_chunk_write_trailer,
310
    .deinit         = webm_chunk_deinit,
311 312
    .priv_class     = &webm_chunk_class,
};