]> git.sesse.net Git - ffmpeg/blobdiff - libavformat/matroskaenc.c
Modify put_ebml_size() so that the bytes parameter is exact rather than minimum
[ffmpeg] / libavformat / matroskaenc.c
index c6e4fb2be8c56c81e0c783a9d378cfdcc884edab..6146ee1db4b61d6b5c039bc0bbafb737d60c9509 100644 (file)
@@ -20,6 +20,7 @@
  */
 
 #include "avformat.h"
+#include "md5.h"
 #include "riff.h"
 #include "xiph.h"
 #include "matroska.h"
@@ -53,6 +54,7 @@ typedef struct {
 typedef struct MatroskaMuxContext {
     offset_t        segment;
     offset_t        segment_offset;
+    offset_t        segment_uid;
     offset_t        cluster;
     offset_t        cluster_pos;        ///< file offset of the current cluster
     uint64_t        cluster_pts;
@@ -61,55 +63,96 @@ typedef struct MatroskaMuxContext {
     mkv_seekhead    *main_seekhead;
     mkv_seekhead    *cluster_seekhead;
     mkv_cues        *cues;
+
+    struct AVMD5    *md5_ctx;
 } MatroskaMuxContext;
 
+static int ebml_id_size(unsigned int id)
+{
+    return (av_log2(id+1)-1)/7+1;
+}
+
 static void put_ebml_id(ByteIOContext *pb, unsigned int id)
 {
-    if (id >= 0x3fffff)
-        put_byte(pb, id >> 24);
-    if (id >= 0x7fff)
-        put_byte(pb, id >> 16);
-    if (id >= 0xff)
-        put_byte(pb, id >> 8);
-    put_byte(pb, id);
+    int i = ebml_id_size(id);
+    while (i--)
+        put_byte(pb, id >> (i*8));
 }
 
-static int ebml_id_size(unsigned int id)
+/**
+ * Write an EBML size meaning "unknown size"
+ *
+ * @param bytes The number of bytes the size should occupy. Maximum of 8.
+ */
+static void put_ebml_size_unknown(ByteIOContext *pb, int bytes)
 {
-    return (av_log2(id+1)-1)/7+1;
+    uint64_t value = 0;
+    int i;
+
+    bytes = FFMIN(bytes, 8);
+    for (i = 0; i < bytes*7 + 1; i++)
+        value |= 1ULL << i;
+    for (i = bytes-1; i >= 0; i--)
+        put_byte(pb, value >> i*8);
+}
+
+/**
+ * Calculate how many bytes are needed to represent a given size in EBML
+ */
+static int ebml_size_bytes(uint64_t size)
+{
+    int bytes = 1;
+    while ((size+1) >> bytes*7) bytes++;
+    return bytes;
 }
 
-// XXX: test this thoroughly and get rid of minbytes hack (currently needed to
-// use up all of the space reserved in start_ebml_master)
-static void put_ebml_size(ByteIOContext *pb, uint64_t size, int minbytes)
+/**
+ * Write a size in EBML variable length format.
+ *
+ * @param bytes The number of bytes that need to be used to write the size.
+ *              If zero, any number of bytes can be used.
+ */
+static void put_ebml_size(ByteIOContext *pb, uint64_t size, int bytes)
 {
-    int bytes = minbytes;
+    int i, needed_bytes = ebml_size_bytes(size);
 
     // sizes larger than this are currently undefined in EBML
     // so write "unknown" size
-    size = FFMIN(size, (1ULL<<56)-1);
+    if (size >= (1ULL<<56)-1) {
+        put_ebml_size_unknown(pb, 1);
+        return;
+    }
 
-    while (size >> (bytes*7 + 7)) bytes++;
+    if (bytes == 0)
+        // don't care how many bytes are used, so use the min
+        bytes = needed_bytes;
+    else if (needed_bytes > bytes) {
+        // the bytes needed to write the given size would exceed the bytes
+        // that we need to use, so write unknown size. This shouldn't happen.
+        av_log(NULL, AV_LOG_WARNING, "Size of %llu needs %d bytes but only %d bytes reserved\n",
+               size, needed_bytes, bytes);
+        put_ebml_size_unknown(pb, bytes);
+        return;
+    }
 
-    put_byte(pb, (0x80 >> bytes) | (size >> bytes*8));
-    for (bytes -= 1; bytes >= 0; bytes--)
-        put_byte(pb, size >> bytes*8);
+    size |= 1ULL << bytes*7;
+    for (i = bytes - 1; i >= 0; i--)
+        put_byte(pb, size >> i*8);
 }
 
 static void put_ebml_uint(ByteIOContext *pb, unsigned int elementid, uint64_t val)
 {
-    int bytes = 1;
+    int i, bytes = 1;
     while (val >> bytes*8) bytes++;
 
     put_ebml_id(pb, elementid);
     put_ebml_size(pb, bytes, 0);
-    for (bytes -= 1; bytes >= 0; bytes--)
-        put_byte(pb, val >> bytes*8);
+    for (i = bytes - 1; i >= 0; i--)
+        put_byte(pb, val >> i*8);
 }
 
 static void put_ebml_float(ByteIOContext *pb, unsigned int elementid, double val)
 {
-    // XXX: single-precision floats?
     put_ebml_id(pb, elementid);
     put_ebml_size(pb, 8, 0);
     put_be64(pb, av_dbl2int(val));
@@ -128,7 +171,12 @@ static void put_ebml_string(ByteIOContext *pb, unsigned int elementid, const cha
     put_ebml_binary(pb, elementid, str, strlen(str));
 }
 
-// this reserves exactly the amount of space specified by size, which must be at least 2
+/**
+ * Writes a void element of a given size. Useful for reserving space in the file to be
+ * written to later.
+ *
+ * @param size The amount of space to reserve, which must be at least 2.
+ */
 static void put_ebml_void(ByteIOContext *pb, uint64_t size)
 {
     offset_t currentpos = url_ftell(pb);
@@ -142,7 +190,7 @@ static void put_ebml_void(ByteIOContext *pb, uint64_t size)
     if (size < 10)
         put_ebml_size(pb, size-1, 0);
     else
-        put_ebml_size(pb, size-9, 7);
+        put_ebml_size(pb, size-9, 8);
     url_fseek(pb, currentpos + size, SEEK_SET);
 }
 
@@ -151,7 +199,7 @@ static offset_t start_ebml_master(ByteIOContext *pb, unsigned int elementid)
     put_ebml_id(pb, elementid);
     // XXX: this always reserves the maximum needed space to store any size value
     // we should be smarter (additional parameter for expected size?)
-    put_ebml_size(pb, (1ULL<<56)-1, 0);     // largest unknown size
+    put_ebml_size_unknown(pb, 8);
     return url_ftell(pb);
 }
 
@@ -160,14 +208,27 @@ static void end_ebml_master(ByteIOContext *pb, offset_t start)
     offset_t pos = url_ftell(pb);
 
     url_fseek(pb, start - 8, SEEK_SET);
-    put_ebml_size(pb, pos - start, 7);
+    put_ebml_size(pb, pos - start, 8);
     url_fseek(pb, pos, SEEK_SET);
 }
 
-// initializes a mkv_seekhead element to be ready to index level 1 matroska elements
-// if numelements is greater than 0, it reserves enough space for that many elements
-// at the current file position and writes the seekhead there, otherwise the seekhead
-// will be appended to the file when end_mkv_seekhead() is called
+static void put_xiph_size(ByteIOContext *pb, int size)
+{
+    int i;
+    for (i = 0; i < size / 255; i++)
+        put_byte(pb, 255);
+    put_byte(pb, size % 255);
+}
+
+/**
+ * Initialize a mkv_seekhead element to be ready to index level 1 Matroska elements.
+ * If a maximum number of elements is specified, enough space will be reserved at
+ * the current file location to write a seek head of that size.
+ *
+ * @param segment_offset the absolute offset into the file that the segment begins
+ * @param numelements the maximum number of elements that will be indexed by this
+ *                    seek head, 0 if unlimited.
+ */
 static mkv_seekhead * mkv_start_seekhead(ByteIOContext *pb, offset_t segment_offset, int numelements)
 {
     mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
@@ -210,7 +271,13 @@ static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid
     return 0;
 }
 
-// returns the file offset where the seekhead was written and frees the seekhead
+/**
+ * Write the seek head to the file and free it. If a maximum number of elements was
+ * specified to mkv_start_seekhead(), the seek head will be written at the location
+ * reserved for it. Otherwise, it is written at the current location in the file.
+ *
+ * @return the file offset where the seekhead was written
+ */
 static offset_t mkv_write_seekhead(ByteIOContext *pb, mkv_seekhead *seekhead)
 {
     offset_t metaseek, seekentry, currentpos;
@@ -317,7 +384,7 @@ static int put_xiph_codecpriv(ByteIOContext *pb, AVCodecContext *codec)
     uint8_t *header_start[3];
     int header_len[3];
     int first_header_size;
-    int j, k;
+    int j;
 
     if (codec->codec_id == CODEC_ID_VORBIS)
         first_header_size = 30;
@@ -333,9 +400,7 @@ static int put_xiph_codecpriv(ByteIOContext *pb, AVCodecContext *codec)
     codecprivate = start_ebml_master(pb, MATROSKA_ID_CODECPRIVATE);
     put_byte(pb, 2);                    // number packets - 1
     for (j = 0; j < 2; j++) {
-        for (k = 0; k < header_len[j] / 255; k++)
-            put_byte(pb, 255);
-        put_byte(pb, header_len[j] % 255);
+        put_xiph_size(pb, header_len[j]);
     }
     for (j = 0; j < 3; j++)
         put_buffer(pb, header_start[j], header_len[j]);
@@ -344,6 +409,28 @@ static int put_xiph_codecpriv(ByteIOContext *pb, AVCodecContext *codec)
     return 0;
 }
 
+#define FLAC_STREAMINFO_SIZE 34
+
+static int put_flac_codecpriv(ByteIOContext *pb, AVCodecContext *codec)
+{
+    offset_t codecpriv = start_ebml_master(pb, MATROSKA_ID_CODECPRIVATE);
+
+    // if the extradata_size is greater than FLAC_STREAMINFO_SIZE,
+    // assume that it's in Matroska's format already
+    if (codec->extradata_size < FLAC_STREAMINFO_SIZE) {
+        av_log(codec, AV_LOG_ERROR, "Invalid FLAC extradata\n");
+        return -1;
+    } else if (codec->extradata_size == FLAC_STREAMINFO_SIZE) {
+        // only the streaminfo packet
+        put_byte(pb, 0);
+        put_xiph_size(pb, codec->extradata_size);
+        av_log(codec, AV_LOG_ERROR, "Only one packet\n");
+    }
+    put_buffer(pb, codec->extradata, codec->extradata_size);
+    end_ebml_master(pb, codecpriv);
+    return 0;
+}
+
 static void get_aac_sample_rates(AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
 {
     static const int aac_sample_rates[] = {
@@ -405,6 +492,8 @@ static int mkv_write_tracks(AVFormatContext *s)
 
         if (st->language[0])
             put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, st->language);
+        else
+            put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, "und");
 
         // look for a codec id string specific to mkv to use, if none are found, use AVI codes
         for (j = 0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++) {
@@ -415,11 +504,13 @@ static int mkv_write_tracks(AVFormatContext *s)
             }
         }
 
-        // XXX: CodecPrivate for vorbis, theora, aac, native mpeg4, ...
         if (native_id) {
             if (codec->codec_id == CODEC_ID_VORBIS || codec->codec_id == CODEC_ID_THEORA) {
                 if (put_xiph_codecpriv(pb, codec) < 0)
                     return -1;
+            } else if (codec->codec_id == CODEC_ID_FLAC) {
+                if (put_flac_codecpriv(pb, codec) < 0)
+                    return -1;
             } else if (codec->extradata_size) {
                 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codec->extradata, codec->extradata_size);
             }
@@ -444,7 +535,10 @@ static int mkv_write_tracks(AVFormatContext *s)
                 // XXX: interlace flag?
                 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
                 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
-                // XXX: display width/height
+                if (codec->sample_aspect_ratio.num) {
+                    put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , codec->sample_aspect_ratio.num);
+                    put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->sample_aspect_ratio.den);
+                }
                 end_ebml_master(pb, subinfo);
                 break;
 
@@ -497,6 +591,9 @@ static int mkv_write_header(AVFormatContext *s)
     ByteIOContext *pb = &s->pb;
     offset_t ebml_header, segment_info;
 
+    mkv->md5_ctx = av_mallocz(av_md5_size);
+    av_md5_init(mkv->md5_ctx);
+
     ebml_header = start_ebml_master(pb, EBML_ID_HEADER);
     put_ebml_uint   (pb, EBML_ID_EBMLVERSION        ,           1);
     put_ebml_uint   (pb, EBML_ID_EBMLREADVERSION    ,           1);
@@ -525,11 +622,14 @@ static int mkv_write_header(AVFormatContext *s)
     if (strlen(s->title))
         put_ebml_string(pb, MATROSKA_ID_TITLE, s->title);
     if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
-        put_ebml_string(pb, MATROSKA_ID_MUXINGAPP, LIBAVFORMAT_IDENT);
-        // XXX: both are required; something better for writing app?
+        put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , LIBAVFORMAT_IDENT);
         put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
+
+        // reserve space to write the segment UID later
+        mkv->segment_uid = url_ftell(pb);
+        put_ebml_void(pb, 19);
     }
-    // XXX: segment UID
+
     // reserve space for the duration
     mkv->duration = 0;
     mkv->duration_offset = url_ftell(pb);
@@ -559,6 +659,8 @@ static void mkv_write_block(AVFormatContext *s, unsigned int blockid, AVPacket *
     MatroskaMuxContext *mkv = s->priv_data;
     ByteIOContext *pb = &s->pb;
 
+    av_log(s, AV_LOG_DEBUG, "Writing block at offset %llu, size %d, pts %lld, dts %lld, duration %d, flags %d\n",
+           url_ftell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
     put_ebml_id(pb, blockid);
     put_ebml_size(pb, pkt->size + 4, 0);
     put_byte(pb, 0x80 | (pkt->stream_index + 1));     // this assumes stream_index is less than 126
@@ -571,10 +673,12 @@ static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     MatroskaMuxContext *mkv = s->priv_data;
     ByteIOContext *pb = &s->pb;
+    AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
     int keyframe = !!(pkt->flags & PKT_FLAG_KEY);
 
     // start a new cluster every 5 MB or 5 sec
     if (url_ftell(pb) > mkv->cluster + 5*1024*1024 || pkt->pts > mkv->cluster_pts + 5000) {
+        av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %llu bytes, pts %llu\n", url_ftell(pb), pkt->pts);
         end_ebml_master(pb, mkv->cluster);
 
         if (mkv_add_seekhead_entry(mkv->cluster_seekhead, MATROSKA_ID_CLUSTER, url_ftell(pb)) < 0)
@@ -584,10 +688,11 @@ static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
         mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER);
         put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, pkt->pts);
         mkv->cluster_pts = pkt->pts;
+        av_md5_update(mkv->md5_ctx, pkt->data, FFMIN(200, pkt->size));
     }
 
-    if (s->streams[pkt->stream_index]->codec->codec_type != CODEC_TYPE_SUBTITLE) {
-    mkv_write_block(s, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
+    if (codec->codec_type != CODEC_TYPE_SUBTITLE) {
+        mkv_write_block(s, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
     } else {
         offset_t blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP);
         mkv_write_block(s, MATROSKA_ID_BLOCK, pkt, 0);
@@ -595,7 +700,7 @@ static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
         end_ebml_master(pb, blockgroup);
     }
 
-    if (s->streams[pkt->stream_index]->codec->codec_type == CODEC_TYPE_VIDEO && keyframe) {
+    if (codec->codec_type == CODEC_TYPE_VIDEO && keyframe) {
         if (mkv_add_cuepoint(mkv->cues, pkt, mkv->cluster_pos) < 0)
             return -1;
     }
@@ -620,12 +725,22 @@ static int mkv_write_trailer(AVFormatContext *s)
     mkv_write_seekhead(pb, mkv->main_seekhead);
 
     // update the duration
+    av_log(s, AV_LOG_DEBUG, "end duration = %llu\n", mkv->duration);
     currentpos = url_ftell(pb);
     url_fseek(pb, mkv->duration_offset, SEEK_SET);
     put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
+
+    // write the md5sum of some frames as the segment UID
+    if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
+        uint8_t segment_uid[16];
+        av_md5_final(mkv->md5_ctx, segment_uid);
+        url_fseek(pb, mkv->segment_uid, SEEK_SET);
+        put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
+    }
     url_fseek(pb, currentpos, SEEK_SET);
 
     end_ebml_master(pb, mkv->segment);
+    av_free(mkv->md5_ctx);
     return 0;
 }
 
@@ -641,4 +756,19 @@ AVOutputFormat matroska_muxer = {
     mkv_write_packet,
     mkv_write_trailer,
     .codec_tag = (const AVCodecTag*[]){codec_bmp_tags, codec_wav_tags, 0},
+    .subtitle_codec = CODEC_ID_TEXT,
+};
+
+AVOutputFormat matroska_audio_muxer = {
+    "matroska",
+    "Matroska File Format",
+    "audio/x-matroska",
+    "mka",
+    sizeof(MatroskaMuxContext),
+    CODEC_ID_MP2,
+    CODEC_ID_NONE,
+    mkv_write_header,
+    mkv_write_packet,
+    mkv_write_trailer,
+    .codec_tag = (const AVCodecTag*[]){codec_wav_tags, 0},
 };