[FFmpeg-cvslog] movenc: support cenc (common encryption)

erankor git at videolan.org
Tue Dec 15 15:36:32 CET 2015


ffmpeg | branch: master | erankor <eran.kornblau at kaltura.com> | Mon Dec  7 12:01:09 2015 +0200| [4469e8ebb2f370794c88aa51d528d1d899d29ddc] | committer: Michael Niedermayer

movenc: support cenc (common encryption)

support writing encrypted mp4 using aes-ctr, conforming to ISO/IEC
23001-7.

3 new parameters were added:
- encryption_scheme - allowed values are none (default) and cenc-aes-ctr
- encryption_key - 128 bit encryption key (hex)
- encryption_kid - 128 bit encryption key identifier (hex)

Signed-off-by: Michael Niedermayer <michael at niedermayer.cc>

> http://git.videolan.org/gitweb.cgi/ffmpeg.git/?a=commit;h=4469e8ebb2f370794c88aa51d528d1d899d29ddc
---

 Changelog                |    1 +
 libavformat/Makefile     |    2 +-
 libavformat/movenc.c     |   92 +++++++++-
 libavformat/movenc.h     |   16 ++
 libavformat/movenccenc.c |  415 ++++++++++++++++++++++++++++++++++++++++++++++
 libavformat/movenccenc.h |   86 ++++++++++
 6 files changed, 604 insertions(+), 8 deletions(-)

diff --git a/Changelog b/Changelog
index 1770068..a3d44b4 100644
--- a/Changelog
+++ b/Changelog
@@ -2,6 +2,7 @@ Entries are sorted chronologically from oldest to youngest within each release,
 releases are sorted from youngest to oldest.
 
 version <next>:
+- Common Encryption (CENC) MP4 encoding support
 - DXV decoding
 - extrastereo filter
 - ocr filter
diff --git a/libavformat/Makefile b/libavformat/Makefile
index ddc4c3d..110e9e3 100644
--- a/libavformat/Makefile
+++ b/libavformat/Makefile
@@ -264,7 +264,7 @@ OBJS-$(CONFIG_MMF_DEMUXER)               += mmf.o
 OBJS-$(CONFIG_MMF_MUXER)                 += mmf.o rawenc.o
 OBJS-$(CONFIG_MOV_DEMUXER)               += mov.o isom.o mov_chan.o replaygain.o
 OBJS-$(CONFIG_MOV_MUXER)                 += movenc.o isom.o avc.o hevc.o \
-                                            movenchint.o mov_chan.o rtp.o
+                                            movenchint.o mov_chan.o rtp.o movenccenc.o
 OBJS-$(CONFIG_MP2_MUXER)                 += mp3enc.o rawenc.o id3v2enc.o
 OBJS-$(CONFIG_MP3_DEMUXER)               += mp3dec.o replaygain.o
 OBJS-$(CONFIG_MP3_MUXER)                 += mp3enc.o rawenc.o id3v2enc.o
diff --git a/libavformat/movenc.c b/libavformat/movenc.c
index e3bab96..3cb3263 100644
--- a/libavformat/movenc.c
+++ b/libavformat/movenc.c
@@ -83,6 +83,9 @@ static const AVOption options[] = {
     { "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
     { "mov_gamma", "gamma value for gama atom", offsetof(MOVMuxContext, gamma), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, 0.0, 10, AV_OPT_FLAG_ENCODING_PARAM},
     { "frag_interleave", "Interleave samples within fragments (max number of consecutive samples, lower is tighter interleaving, but with more overhead)", offsetof(MOVMuxContext, frag_interleave), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
+    { "encryption_scheme",    "Configures the encryption scheme, allowed values are none, cenc-aes-ctr", offsetof(MOVMuxContext, encryption_scheme_str),   AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM, .unit = "movflags" },
+    { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM, .unit = "movflags" },
+    { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM, .unit = "movflags" },
     { NULL },
 };
 
@@ -891,7 +894,7 @@ static int get_samples_per_packet(MOVTrack *track)
     return first_duration;
 }
 
-static int mov_write_audio_tag(AVIOContext *pb, MOVTrack *track)
+static int mov_write_audio_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
 {
     int64_t pos = avio_tell(pb);
     int version = 0;
@@ -912,7 +915,11 @@ static int mov_write_audio_tag(AVIOContext *pb, MOVTrack *track)
     }
 
     avio_wb32(pb, 0); /* size */
-    avio_wl32(pb, tag); // store it byteswapped
+    if (mov->encryption_scheme != MOV_ENC_NONE) {
+        ffio_wfourcc(pb, "enca");
+    } else {
+        avio_wl32(pb, tag); // store it byteswapped
+    }
     avio_wb32(pb, 0); /* Reserved */
     avio_wb16(pb, 0); /* Reserved */
     avio_wb16(pb, 1); /* Data-reference index, XXX  == 1 */
@@ -1000,6 +1007,10 @@ static int mov_write_audio_tag(AVIOContext *pb, MOVTrack *track)
     if (track->mode == MODE_MOV && track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
         mov_write_chan_tag(pb, track);
 
+    if (mov->encryption_scheme != MOV_ENC_NONE) {
+        ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
+    }
+
     return update_size(pb, pos);
 }
 
@@ -1659,7 +1670,11 @@ static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *tr
     int avid = 0;
 
     avio_wb32(pb, 0); /* size */
-    avio_wl32(pb, track->tag); // store it byteswapped
+    if (mov->encryption_scheme != MOV_ENC_NONE) {
+        ffio_wfourcc(pb, "encv");
+    } else {
+        avio_wl32(pb, track->tag); // store it byteswapped
+    }
     avio_wb32(pb, 0); /* Reserved */
     avio_wb16(pb, 0); /* Reserved */
     avio_wb16(pb, 1); /* Data-reference index */
@@ -1750,6 +1765,10 @@ static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *tr
         mov_write_pasp_tag(pb, track);
     }
 
+    if (mov->encryption_scheme != MOV_ENC_NONE) {
+        ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
+    }
+
     /* extra padding for avid stsd */
     /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
     if (avid)
@@ -1848,9 +1867,9 @@ static int mov_write_stsd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *tra
     avio_wb32(pb, 0); /* version & flags */
     avio_wb32(pb, 1); /* entry count */
     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
-        mov_write_video_tag(pb, mov,  track);
+        mov_write_video_tag(pb, mov, track);
     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
-        mov_write_audio_tag(pb, track);
+        mov_write_audio_tag(pb, mov, track);
     else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
         mov_write_subtitle_tag(pb, track);
     else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
@@ -1980,6 +1999,9 @@ static int mov_write_stbl_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *tra
     mov_write_stsc_tag(pb, track);
     mov_write_stsz_tag(pb, track);
     mov_write_stco_tag(pb, track);
+    if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
+        ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
+    }
     return update_size(pb, pos);
 }
 
@@ -4419,7 +4441,15 @@ int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
                                        &size);
             avio_write(pb, reformatted_data, size);
         } else {
-            size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
+            if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
+                size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
+                if (size < 0) {
+                    ret = size;
+                    goto err;
+                }
+            } else {
+                size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
+            }
         }
     } else if (enc->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
                (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
@@ -4440,7 +4470,20 @@ int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
         avio_write(pb, pkt->data, size);
 #endif
     } else {
-        avio_write(pb, pkt->data, size);
+        if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
+            if (enc->codec_id == AV_CODEC_ID_H264 && enc->extradata_size > 4) {
+                int nal_size_length = (enc->extradata[4] & 0x3) + 1;
+                ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
+            } else {
+                ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
+            }
+
+            if (ret) {
+                goto err;
+            }
+        } else {
+            avio_write(pb, pkt->data, size);
+        }
     }
 
     if ((enc->codec_id == AV_CODEC_ID_DNXHD ||
@@ -4913,6 +4956,8 @@ static void mov_free(AVFormatContext *s)
 
         if (mov->tracks[i].vos_len)
             av_freep(&mov->tracks[i].vos_data);
+
+        ff_mov_cenc_free(&mov->tracks[i].cenc);
     }
 
     av_freep(&mov->tracks);
@@ -5123,6 +5168,31 @@ static int mov_write_header(AVFormatContext *s)
     if (!mov->tracks)
         return AVERROR(ENOMEM);
 
+    if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
+        if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
+            mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
+
+            if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
+                av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
+                    mov->encryption_key_len, AES_CTR_KEY_SIZE);
+                ret = AVERROR(EINVAL);
+                goto error;
+            }
+
+            if (mov->encryption_kid_len != CENC_KID_SIZE) {
+                av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
+                    mov->encryption_kid_len, CENC_KID_SIZE);
+                ret = AVERROR(EINVAL);
+                goto error;
+            }
+        } else {
+            av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
+                mov->encryption_scheme_str);
+            ret = AVERROR(EINVAL);
+            goto error;
+        }
+    }
+
     for (i = 0; i < s->nb_streams; i++) {
         AVStream *st= s->streams[i];
         MOVTrack *track= &mov->tracks[i];
@@ -5241,6 +5311,14 @@ static int mov_write_header(AVFormatContext *s)
                 memcpy(track->vos_data, st->codec->extradata, track->vos_len);
             }
         }
+
+        if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
+            ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
+                track->enc->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
+            if (ret) {
+                goto error;
+            }
+        }
     }
 
     for (i = 0; i < s->nb_streams; i++) {
diff --git a/libavformat/movenc.h b/libavformat/movenc.h
index 06adf2b..deb90fe 100644
--- a/libavformat/movenc.h
+++ b/libavformat/movenc.h
@@ -25,6 +25,7 @@
 #define AVFORMAT_MOVENC_H
 
 #include "avformat.h"
+#include "movenccenc.h"
 
 #define MOV_FRAG_INFO_ALLOC_INCREMENT 64
 #define MOV_INDEX_CLUSTER_SIZE 1024
@@ -149,8 +150,15 @@ typedef struct MOVTrack {
     } vc1_info;
 
     void       *eac3_priv;
+
+    MOVMuxCencContext cenc;
 } MOVTrack;
 
+typedef enum {
+    MOV_ENC_NONE = 0,
+    MOV_ENC_CENC_AES_CTR,
+} MOVEncryptionScheme;
+
 typedef struct MOVMuxContext {
     const AVClass *av_class;
     int     mode;
@@ -193,6 +201,14 @@ typedef struct MOVMuxContext {
 
     int frag_interleave;
     int missing_duration_warned;
+
+    char *encryption_scheme_str;
+    MOVEncryptionScheme encryption_scheme;
+    uint8_t *encryption_key;
+    int encryption_key_len;
+    uint8_t *encryption_kid;
+    int encryption_kid_len;
+
 } MOVMuxContext;
 
 #define FF_MOV_FLAG_RTP_HINT              (1 <<  0)
diff --git a/libavformat/movenccenc.c b/libavformat/movenccenc.c
new file mode 100644
index 0000000..b91294f
--- /dev/null
+++ b/libavformat/movenccenc.c
@@ -0,0 +1,415 @@
+/*
+ * MOV CENC (Common Encryption) writer
+ * Copyright (c) 2015 Eran Kornblau <erankor at gmail dot com>
+ *
+ * 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
+ */
+#include "movenccenc.h"
+#include "libavutil/intreadwrite.h"
+#include "avio_internal.h"
+#include "movenc.h"
+#include "avc.h"
+
+static int auxiliary_info_alloc_size(MOVMuxCencContext* ctx, int size)
+{
+    size_t new_alloc_size;
+
+    if (ctx->auxiliary_info_size + size > ctx->auxiliary_info_alloc_size) {
+        new_alloc_size = FFMAX(ctx->auxiliary_info_size + size, ctx->auxiliary_info_alloc_size * 2);
+        if (av_reallocp(&ctx->auxiliary_info, new_alloc_size)) {
+            return AVERROR(ENOMEM);
+        }
+
+        ctx->auxiliary_info_alloc_size = new_alloc_size;
+    }
+
+    return 0;
+}
+
+static int auxiliary_info_write(MOVMuxCencContext* ctx,
+                                         const uint8_t *buf_in, int size)
+{
+    int ret;
+
+    ret = auxiliary_info_alloc_size(ctx, size);
+    if (ret) {
+        return ret;
+    }
+    memcpy(ctx->auxiliary_info + ctx->auxiliary_info_size, buf_in, size);
+    ctx->auxiliary_info_size += size;
+
+    return 0;
+}
+
+static int auxiliary_info_add_subsample(MOVMuxCencContext* ctx,
+    uint16_t clear_bytes, uint32_t encrypted_bytes)
+{
+    uint8_t* p;
+    int ret;
+
+    if (!ctx->use_subsamples) {
+        return 0;
+    }
+
+    ret = auxiliary_info_alloc_size(ctx, 6);
+    if (ret) {
+        return ret;
+    }
+
+    p = ctx->auxiliary_info + ctx->auxiliary_info_size;
+
+    AV_WB16(p, clear_bytes);
+    p += sizeof(uint16_t);
+
+    AV_WB32(p, encrypted_bytes);
+
+    ctx->auxiliary_info_size += 6;
+    ctx->subsample_count++;
+
+    return 0;
+}
+
+/**
+ * Encrypt the input buffer and write using avio_write
+ */
+static void mov_cenc_write_encrypted(MOVMuxCencContext* ctx, AVIOContext *pb,
+                                     const uint8_t *buf_in, int size)
+{
+    uint8_t chunk[4096];
+    const uint8_t* cur_pos = buf_in;
+    int size_left = size;
+    int cur_size;
+
+    while (size_left > 0) {
+        cur_size = FFMIN(size_left, sizeof(chunk));
+        av_aes_ctr_crypt(ctx->aes_ctr, chunk, cur_pos, cur_size);
+        avio_write(pb, chunk, cur_size);
+        cur_pos += cur_size;
+        size_left -= cur_size;
+    }
+}
+
+/**
+ * Start writing a packet
+ */
+static int mov_cenc_start_packet(MOVMuxCencContext* ctx)
+{
+    int ret;
+
+    /* write the iv */
+    ret = auxiliary_info_write(ctx, av_aes_ctr_get_iv(ctx->aes_ctr), AES_CTR_IV_SIZE);
+    if (ret) {
+        return ret;
+    }
+
+    if (!ctx->use_subsamples) {
+        return 0;
+    }
+
+    /* write a zero subsample count */
+    ctx->auxiliary_info_subsample_start = ctx->auxiliary_info_size;
+    ctx->subsample_count = 0;
+    ret = auxiliary_info_write(ctx, (uint8_t*)&ctx->subsample_count, sizeof(ctx->subsample_count));
+    if (ret) {
+        return ret;
+    }
+
+    return 0;
+}
+
+/**
+ * Finalize a packet
+ */
+static int mov_cenc_end_packet(MOVMuxCencContext* ctx)
+{
+    size_t new_alloc_size;
+
+    av_aes_ctr_increment_iv(ctx->aes_ctr);
+
+    if (!ctx->use_subsamples) {
+        ctx->auxiliary_info_entries++;
+        return 0;
+    }
+
+    /* add the auxiliary info entry size*/
+    if (ctx->auxiliary_info_entries >= ctx->auxiliary_info_sizes_alloc_size) {
+        new_alloc_size = ctx->auxiliary_info_entries * 2 + 1;
+        if (av_reallocp(&ctx->auxiliary_info_sizes, new_alloc_size)) {
+            return AVERROR(ENOMEM);
+        }
+
+        ctx->auxiliary_info_sizes_alloc_size = new_alloc_size;
+    }
+    ctx->auxiliary_info_sizes[ctx->auxiliary_info_entries] =
+        AES_CTR_IV_SIZE + ctx->auxiliary_info_size - ctx->auxiliary_info_subsample_start;
+    ctx->auxiliary_info_entries++;
+
+    /* update the subsample count*/
+    AV_WB16(ctx->auxiliary_info + ctx->auxiliary_info_subsample_start, ctx->subsample_count);
+
+    return 0;
+}
+
+int ff_mov_cenc_write_packet(MOVMuxCencContext* ctx, AVIOContext *pb,
+                          const uint8_t *buf_in, int size)
+{
+    int ret;
+
+    ret = mov_cenc_start_packet(ctx);
+    if (ret) {
+        return ret;
+    }
+
+    ret = auxiliary_info_add_subsample(ctx, 0, size);
+    if (ret) {
+        return ret;
+    }
+
+    mov_cenc_write_encrypted(ctx, pb, buf_in, size);
+
+    ret = mov_cenc_end_packet(ctx);
+    if (ret) {
+        return ret;
+    }
+
+    return 0;
+}
+
+int ff_mov_cenc_avc_parse_nal_units(MOVMuxCencContext* ctx, AVIOContext *pb,
+                                 const uint8_t *buf_in, int size)
+{
+    const uint8_t *p = buf_in;
+    const uint8_t *end = p + size;
+    const uint8_t *nal_start, *nal_end;
+    int ret;
+
+    ret = mov_cenc_start_packet(ctx);
+    if (ret) {
+        return ret;
+    }
+
+    size = 0;
+    nal_start = ff_avc_find_startcode(p, end);
+    for (;;) {
+        while (nal_start < end && !*(nal_start++));
+        if (nal_start == end)
+            break;
+
+        nal_end = ff_avc_find_startcode(nal_start, end);
+
+        avio_wb32(pb, nal_end - nal_start);
+        avio_w8(pb, *nal_start);
+        mov_cenc_write_encrypted(ctx, pb, nal_start + 1, nal_end - nal_start - 1);
+
+        auxiliary_info_add_subsample(ctx, 5, nal_end - nal_start - 1);
+
+        size += 4 + nal_end - nal_start;
+        nal_start = nal_end;
+    }
+
+    ret = mov_cenc_end_packet(ctx);
+    if (ret) {
+        return ret;
+    }
+
+    return size;
+}
+
+int ff_mov_cenc_avc_write_nal_units(AVFormatContext *s, MOVMuxCencContext* ctx,
+    int nal_length_size, AVIOContext *pb, const uint8_t *buf_in, int size)
+{
+    int nalsize;
+    int ret;
+    int j;
+
+    ret = mov_cenc_start_packet(ctx);
+    if (ret) {
+        return ret;
+    }
+
+    while (size > 0) {
+        /* parse the nal size */
+        if (size < nal_length_size + 1) {
+            av_log(s, AV_LOG_ERROR, "CENC-AVC: remaining size %d smaller than nal length+type %d\n",
+                size, nal_length_size + 1);
+            return -1;
+        }
+
+        avio_write(pb, buf_in, nal_length_size + 1);
+
+        nalsize = 0;
+        for (j = 0; j < nal_length_size; j++) {
+            nalsize = (nalsize << 8) | *buf_in++;
+        }
+        size -= nal_length_size;
+
+        /* encrypt the nal body */
+        if (nalsize <= 0 || nalsize > size) {
+            av_log(s, AV_LOG_ERROR, "CENC-AVC: nal size %d remaining %d\n", nalsize, size);
+            return -1;
+        }
+
+        mov_cenc_write_encrypted(ctx, pb, buf_in + 1, nalsize - 1);
+        buf_in += nalsize;
+        size -= nalsize;
+
+        auxiliary_info_add_subsample(ctx, nal_length_size + 1, nalsize - 1);
+    }
+
+    ret = mov_cenc_end_packet(ctx);
+    if (ret) {
+        return ret;
+    }
+
+    return 0;
+}
+
+/* TODO: reuse this function from movenc.c */
+static int64_t update_size(AVIOContext *pb, int64_t pos)
+{
+    int64_t curpos = avio_tell(pb);
+    avio_seek(pb, pos, SEEK_SET);
+    avio_wb32(pb, curpos - pos); /* rewrite size */
+    avio_seek(pb, curpos, SEEK_SET);
+
+    return curpos - pos;
+}
+
+static int mov_cenc_write_senc_tag(MOVMuxCencContext* ctx, AVIOContext *pb,
+                                   int64_t* auxiliary_info_offset)
+{
+    int64_t pos = avio_tell(pb);
+
+    avio_wb32(pb, 0); /* size */
+    ffio_wfourcc(pb, "senc");
+    avio_wb32(pb, ctx->use_subsamples ? 0x02 : 0); /* version & flags */
+    avio_wb32(pb, ctx->auxiliary_info_entries); /* entry count */
+    *auxiliary_info_offset = avio_tell(pb);
+    avio_write(pb, ctx->auxiliary_info, ctx->auxiliary_info_size);
+    return update_size(pb, pos);
+}
+
+static int mov_cenc_write_saio_tag(AVIOContext *pb, int64_t auxiliary_info_offset)
+{
+    int64_t pos = avio_tell(pb);
+    uint8_t version;
+
+    avio_wb32(pb, 0); /* size */
+    ffio_wfourcc(pb, "saio");
+    version = auxiliary_info_offset > 0xffffffff ? 1 : 0;
+    avio_w8(pb, version);
+    avio_wb24(pb, 0); /* flags */
+    avio_wb32(pb, 1); /* entry count */
+    if (version) {
+        avio_wb64(pb, auxiliary_info_offset);
+    } else {
+        avio_wb32(pb, auxiliary_info_offset);
+    }
+    return update_size(pb, pos);
+}
+
+static int mov_cenc_write_saiz_tag(MOVMuxCencContext* ctx, AVIOContext *pb)
+{
+    int64_t pos = avio_tell(pb);
+    avio_wb32(pb, 0); /* size */
+    ffio_wfourcc(pb, "saiz");
+    avio_wb32(pb, 0); /* version & flags */
+    avio_w8(pb, ctx->use_subsamples ? 0 : AES_CTR_IV_SIZE);    /* default size*/
+    avio_wb32(pb, ctx->auxiliary_info_entries); /* entry count */
+    if (ctx->use_subsamples) {
+        avio_write(pb, ctx->auxiliary_info_sizes, ctx->auxiliary_info_entries);
+    }
+    return update_size(pb, pos);
+}
+
+void ff_mov_cenc_write_stbl_atoms(MOVMuxCencContext* ctx, AVIOContext *pb)
+{
+    int64_t auxiliary_info_offset;
+
+    mov_cenc_write_senc_tag(ctx, pb, &auxiliary_info_offset);
+    mov_cenc_write_saio_tag(pb, auxiliary_info_offset);
+    mov_cenc_write_saiz_tag(ctx, pb);
+}
+
+static int mov_cenc_write_schi_tag(AVIOContext *pb, uint8_t* kid)
+{
+    int64_t pos = avio_tell(pb);
+    avio_wb32(pb, 0);     /* size */
+    ffio_wfourcc(pb, "schi");
+
+    avio_wb32(pb, 32);    /* size */
+    ffio_wfourcc(pb, "tenc");
+    avio_wb32(pb, 0);     /* version & flags */
+    avio_wb24(pb, 1);     /* is encrypted */
+    avio_w8(pb, AES_CTR_IV_SIZE); /* iv size */
+    avio_write(pb, kid, CENC_KID_SIZE);
+
+    return update_size(pb, pos);
+}
+
+int ff_mov_cenc_write_sinf_tag(MOVTrack* track, AVIOContext *pb, uint8_t* kid)
+{
+    int64_t pos = avio_tell(pb);
+    avio_wb32(pb, 0); /* size */
+    ffio_wfourcc(pb, "sinf");
+
+    /* frma */
+    avio_wb32(pb, 12);    /* size */
+    ffio_wfourcc(pb, "frma");
+    avio_wl32(pb, track->tag);
+
+    /* schm */
+    avio_wb32(pb, 20);    /* size */
+    ffio_wfourcc(pb, "schm");
+    avio_wb32(pb, 0); /* version & flags */
+    ffio_wfourcc(pb, "cenc");    /* scheme type*/
+    avio_wb32(pb, 0x10000); /* scheme version */
+
+    /* schi */
+    mov_cenc_write_schi_tag(pb, kid);
+
+    return update_size(pb, pos);
+}
+
+int ff_mov_cenc_init(MOVMuxCencContext* ctx, uint8_t* encryption_key,
+                     int use_subsamples, int bitexact)
+{
+    int ret;
+
+    ctx->aes_ctr = av_aes_ctr_alloc();
+    if (!ctx->aes_ctr) {
+        return AVERROR(ENOMEM);
+    }
+
+    ret = av_aes_ctr_init(ctx->aes_ctr, encryption_key);
+    if (ret != 0) {
+        return ret;
+    }
+
+    if (!bitexact) {
+        av_aes_ctr_set_random_iv(ctx->aes_ctr);
+    }
+
+    ctx->use_subsamples = use_subsamples;
+
+    return 0;
+}
+
+void ff_mov_cenc_free(MOVMuxCencContext* ctx)
+{
+    av_aes_ctr_free(ctx->aes_ctr);
+}
diff --git a/libavformat/movenccenc.h b/libavformat/movenccenc.h
new file mode 100644
index 0000000..6f9e70e
--- /dev/null
+++ b/libavformat/movenccenc.h
@@ -0,0 +1,86 @@
+/*
+ * MOV CENC (Common Encryption) writer
+ * Copyright (c) 2015 Eran Kornblau <erankor at gmail dot com>
+ *
+ * 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
+ */
+
+#ifndef AVFORMAT_MOVENCCENC_H
+#define AVFORMAT_MOVENCCENC_H
+
+#include "libavutil/aes_ctr.h"
+#include "avformat.h"
+#include "avio.h"
+
+#define CENC_KID_SIZE (16)
+
+struct MOVTrack;
+
+typedef struct {
+    struct AVAESCTR* aes_ctr;
+    uint8_t* auxiliary_info;
+    size_t auxiliary_info_size;
+    size_t auxiliary_info_alloc_size;
+    uint32_t auxiliary_info_entries;
+
+    /* subsample support */
+    int use_subsamples;
+    uint16_t subsample_count;
+    size_t auxiliary_info_subsample_start;
+    uint8_t* auxiliary_info_sizes;
+    size_t  auxiliary_info_sizes_alloc_size;
+} MOVMuxCencContext;
+
+/**
+ * Initialize a CENC context
+ * @param key encryption key, must have a length of AES_CTR_KEY_SIZE
+ * @param use_subsamples when enabled parts of a packet can be encrypted, otherwise the whole packet is encrypted
+ */
+int ff_mov_cenc_init(MOVMuxCencContext* ctx, uint8_t* encryption_key, int use_subsamples, int bitexact);
+
+/**
+ * Free a CENC context
+ */
+void ff_mov_cenc_free(MOVMuxCencContext* ctx);
+
+/**
+ * Write a fully encrypted packet
+ */
+int ff_mov_cenc_write_packet(MOVMuxCencContext* ctx, AVIOContext *pb, const uint8_t *buf_in, int size);
+
+/**
+ * Parse AVC NAL units from annex B format, the nal size and type are written in the clear while the body is encrypted
+ */
+int ff_mov_cenc_avc_parse_nal_units(MOVMuxCencContext* ctx, AVIOContext *pb, const uint8_t *buf_in, int size);
+
+/**
+ * Write AVC NAL units that are in MP4 format, the nal size and type are written in the clear while the body is encrypted
+ */
+int ff_mov_cenc_avc_write_nal_units(AVFormatContext *s, MOVMuxCencContext* ctx, int nal_length_size,
+    AVIOContext *pb, const uint8_t *buf_in, int size);
+
+/**
+ * Write the cenc atoms that should reside inside stbl
+ */
+void ff_mov_cenc_write_stbl_atoms(MOVMuxCencContext* ctx, AVIOContext *pb);
+
+/**
+ * Write the sinf atom, contained inside stsd
+ */
+int ff_mov_cenc_write_sinf_tag(struct MOVTrack* track, AVIOContext *pb, uint8_t* kid);
+
+#endif /* AVFORMAT_MOVENCCENC_H */



More information about the ffmpeg-cvslog mailing list