libavcodec/libtheoraenc.c
150d2772
 /*
  * Copyright (c) 2006 Paul Richards <paul.richards@gmail.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
e5a389a1
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
150d2772
  */
 
4311ff77
 /**
ba87f080
  * @file
4311ff77
  * @brief Theora encoder using libtheora.
  * @author Paul Richards <paul.richards@gmail.com>
150d2772
  *
  * A lot of this is copy / paste from other output codecs in
  * libavcodec or pure guesswork (or both).
  *
  * I have used t_ prefixes on variables which are libtheora types
  * and o_ prefixes on variables which are libogg types.
  */
 
2d2b5a14
 /* FFmpeg includes */
1d9c2dc8
 #include "libavutil/common.h"
d9513de6
 #include "libavutil/intreadwrite.h"
83f9ed42
 #include "libavutil/pixdesc.h"
245976da
 #include "libavutil/log.h"
b0a6d9ca
 #include "libavutil/base64.h"
150d2772
 #include "avcodec.h"
f7fa73ac
 #include "internal.h"
150d2772
 
 /* libtheora includes */
bdc8c488
 #include <theora/theoraenc.h>
150d2772
 
8767fb4c
 typedef struct TheoraContext {
bdc8c488
     th_enc_ctx *t_state;
b0a6d9ca
     uint8_t    *stats;
     int         stats_size;
     int         stats_offset;
af89b178
     int         uv_hshift;
     int         uv_vshift;
c39b94be
     int         keyframe_mask;
150d2772
 } TheoraContext;
 
49bd8e4b
 /** Concatenate an ogg_packet into the extradata. */
8767fb4c
 static int concatenate_packet(unsigned int* offset,
                               AVCodecContext* avc_context,
                               const ogg_packet* packet)
150d2772
 {
3e962f31
     const char* message = NULL;
150d2772
     int newsize = avc_context->extradata_size + 2 + packet->bytes;
9b8d11a7
     int err = AVERROR_INVALIDDATA;
150d2772
 
     if (packet->bytes < 0) {
         message = "ogg_packet has negative size";
     } else if (packet->bytes > 0xffff) {
         message = "ogg_packet is larger than 65535 bytes";
     } else if (newsize < avc_context->extradata_size) {
         message = "extradata_size would overflow";
     } else {
9b8d11a7
         if ((err = av_reallocp(&avc_context->extradata, newsize)) < 0) {
             avc_context->extradata_size = 0;
150d2772
             message = "av_realloc failed";
9b8d11a7
         }
150d2772
     }
96ff02f1
     if (message) {
150d2772
         av_log(avc_context, AV_LOG_ERROR, "concatenate_packet failed: %s\n", message);
9b8d11a7
         return err;
150d2772
     }
 
     avc_context->extradata_size = newsize;
2c124cb6
     AV_WB16(avc_context->extradata + (*offset), packet->bytes);
     *offset += 2;
8767fb4c
     memcpy(avc_context->extradata + (*offset), packet->packet, packet->bytes);
150d2772
     (*offset) += packet->bytes;
     return 0;
 }
 
b0a6d9ca
 static int get_stats(AVCodecContext *avctx, int eos)
 {
800841fd
 #ifdef TH_ENCCTL_2PASS_OUT
b0a6d9ca
     TheoraContext *h = avctx->priv_data;
     uint8_t *buf;
     int bytes;
 
     bytes = th_encode_ctl(h->t_state, TH_ENCCTL_2PASS_OUT, &buf, sizeof(buf));
     if (bytes < 0) {
         av_log(avctx, AV_LOG_ERROR, "Error getting first pass stats\n");
8cb76ef2
         return AVERROR_EXTERNAL;
b0a6d9ca
     }
     if (!eos) {
         h->stats = av_fast_realloc(h->stats, &h->stats_size,
                                    h->stats_offset + bytes);
         memcpy(h->stats + h->stats_offset, buf, bytes);
         h->stats_offset += bytes;
     } else {
784824a6
         int b64_size = AV_BASE64_SIZE(h->stats_offset);
b0a6d9ca
         // libtheora generates a summary header at the end
         memcpy(h->stats, buf, bytes);
         avctx->stats_out = av_malloc(b64_size);
eac07625
         if (!avctx->stats_out)
             return AVERROR(ENOMEM);
b0a6d9ca
         av_base64_encode(avctx->stats_out, b64_size, h->stats, h->stats_offset);
     }
     return 0;
800841fd
 #else
     av_log(avctx, AV_LOG_ERROR, "libtheora too old to support 2pass\n");
8cb76ef2
     return AVERROR(ENOSUP);
800841fd
 #endif
b0a6d9ca
 }
 
 // libtheora won't read the entire buffer we give it at once, so we have to
 // repeatedly submit it...
 static int submit_stats(AVCodecContext *avctx)
 {
800841fd
 #ifdef TH_ENCCTL_2PASS_IN
b0a6d9ca
     TheoraContext *h = avctx->priv_data;
     int bytes;
     if (!h->stats) {
         if (!avctx->stats_in) {
             av_log(avctx, AV_LOG_ERROR, "No statsfile for second pass\n");
8cb76ef2
             return AVERROR(EINVAL);
b0a6d9ca
         }
         h->stats_size = strlen(avctx->stats_in) * 3/4;
         h->stats      = av_malloc(h->stats_size);
         h->stats_size = av_base64_decode(h->stats, avctx->stats_in, h->stats_size);
     }
     while (h->stats_size - h->stats_offset > 0) {
         bytes = th_encode_ctl(h->t_state, TH_ENCCTL_2PASS_IN,
                               h->stats + h->stats_offset,
                               h->stats_size - h->stats_offset);
         if (bytes < 0) {
             av_log(avctx, AV_LOG_ERROR, "Error submitting stats\n");
8cb76ef2
             return AVERROR_EXTERNAL;
b0a6d9ca
         }
         if (!bytes)
             return 0;
         h->stats_offset += bytes;
     }
     return 0;
800841fd
 #else
     av_log(avctx, AV_LOG_ERROR, "libtheora too old to support 2pass\n");
8cb76ef2
     return AVERROR(ENOSUP);
800841fd
 #endif
b0a6d9ca
 }
 
5ef251e5
 static av_cold int encode_init(AVCodecContext* avc_context)
150d2772
 {
bdc8c488
     th_info t_info;
     th_comment t_comment;
150d2772
     ogg_packet o_packet;
     unsigned int offset;
     TheoraContext *h = avc_context->priv_data;
bdc8c488
     uint32_t gop_size = avc_context->gop_size;
8cb76ef2
     int ret;
150d2772
 
     /* Set up the theora_info struct */
bdc8c488
     th_info_init(&t_info);
     t_info.frame_width  = FFALIGN(avc_context->width,  16);
     t_info.frame_height = FFALIGN(avc_context->height, 16);
     t_info.pic_width    = avc_context->width;
     t_info.pic_height   = avc_context->height;
     t_info.pic_x        = 0;
     t_info.pic_y        = 0;
013591c5
     /* Swap numerator and denominator as time_base in AVCodecContext gives the
      * time period between frames, but theora_info needs the framerate.  */
8767fb4c
     t_info.fps_numerator   = avc_context->time_base.den;
150d2772
     t_info.fps_denominator = avc_context->time_base.num;
96ff02f1
     if (avc_context->sample_aspect_ratio.num) {
8767fb4c
         t_info.aspect_numerator   = avc_context->sample_aspect_ratio.num;
150d2772
         t_info.aspect_denominator = avc_context->sample_aspect_ratio.den;
     } else {
8767fb4c
         t_info.aspect_numerator   = 1;
150d2772
         t_info.aspect_denominator = 1;
     }
6c2289b5
 
     if (avc_context->color_primaries == AVCOL_PRI_BT470M)
         t_info.colorspace = TH_CS_ITU_REC_470M;
     else if (avc_context->color_primaries == AVCOL_PRI_BT470BG)
         t_info.colorspace = TH_CS_ITU_REC_470BG;
     else
         t_info.colorspace = TH_CS_UNSPECIFIED;
af89b178
 
716d413c
     if (avc_context->pix_fmt == AV_PIX_FMT_YUV420P)
af89b178
         t_info.pixel_fmt = TH_PF_420;
716d413c
     else if (avc_context->pix_fmt == AV_PIX_FMT_YUV422P)
af89b178
         t_info.pixel_fmt = TH_PF_422;
716d413c
     else if (avc_context->pix_fmt == AV_PIX_FMT_YUV444P)
af89b178
         t_info.pixel_fmt = TH_PF_444;
     else {
         av_log(avc_context, AV_LOG_ERROR, "Unsupported pix_fmt\n");
8cb76ef2
         return AVERROR(EINVAL);
af89b178
     }
     avcodec_get_chroma_sub_sample(avc_context->pix_fmt, &h->uv_hshift, &h->uv_vshift);
150d2772
 
6945c2bc
     if (avc_context->flags & CODEC_FLAG_QSCALE) {
37fce84e
         /* Clip global_quality in QP units to the [0 - 10] range
            to be consistent with the libvorbis implementation.
            Theora accepts a quality parameter which is an int value in
            the [0 - 63] range.
         */
467c0338
         t_info.quality        = av_clipf(avc_context->global_quality / (float)FF_QP2LAMBDA, 0, 10) * 6.3;
6945c2bc
         t_info.target_bitrate = 0;
     } else {
         t_info.target_bitrate = avc_context->bit_rate;
8767fb4c
         t_info.quality        = 0;
6945c2bc
     }
 
150d2772
     /* Now initialise libtheora */
bdc8c488
     h->t_state = th_encode_alloc(&t_info);
     if (!h->t_state) {
150d2772
         av_log(avc_context, AV_LOG_ERROR, "theora_encode_init failed\n");
8cb76ef2
         return AVERROR_EXTERNAL;
150d2772
     }
 
c39b94be
     h->keyframe_mask = (1 << t_info.keyframe_granule_shift) - 1;
150d2772
     /* Clear up theora_info struct */
bdc8c488
     th_info_clear(&t_info);
 
     if (th_encode_ctl(h->t_state, TH_ENCCTL_SET_KEYFRAME_FREQUENCY_FORCE,
                       &gop_size, sizeof(gop_size))) {
         av_log(avc_context, AV_LOG_ERROR, "Error setting GOP size\n");
8cb76ef2
         return AVERROR_EXTERNAL;
bdc8c488
     }
150d2772
 
b0a6d9ca
     // need to enable 2 pass (via TH_ENCCTL_2PASS_) before encoding headers
     if (avc_context->flags & CODEC_FLAG_PASS1) {
8cb76ef2
         if ((ret = get_stats(avc_context, 0)) < 0)
             return ret;
b0a6d9ca
     } else if (avc_context->flags & CODEC_FLAG_PASS2) {
8cb76ef2
         if ((ret = submit_stats(avc_context)) < 0)
             return ret;
b0a6d9ca
     }
 
150d2772
     /*
         Output first header packet consisting of theora
         header, comment, and tables.
 
         Each one is prefixed with a 16bit size, then they
2f5df0b1
         are concatenated together into libavcodec's extradata.
150d2772
     */
     offset = 0;
 
bdc8c488
     /* Headers */
     th_comment_init(&t_comment);
150d2772
 
bdc8c488
     while (th_encode_flushheader(h->t_state, &t_comment, &o_packet))
8cb76ef2
         if ((ret = concatenate_packet(&offset, avc_context, &o_packet)) < 0)
             return ret;
bdc8c488
 
     th_comment_clear(&t_comment);
150d2772
 
     /* Set up the output AVFrame */
5b9c3b45
     avc_context->coded_frame = av_frame_alloc();
150d2772
 
     return 0;
 }
 
f7fa73ac
 static int encode_frame(AVCodecContext* avc_context, AVPacket *pkt,
                         const AVFrame *frame, int *got_packet)
150d2772
 {
bdc8c488
     th_ycbcr_buffer t_yuv_buffer;
150d2772
     TheoraContext *h = avc_context->priv_data;
     ogg_packet o_packet;
f7fa73ac
     int result, i, ret;
150d2772
 
b0a6d9ca
     // EOS, finish and get 1st pass stats if applicable
     if (!frame) {
         th_encode_packetout(h->t_state, 1, &o_packet);
         if (avc_context->flags & CODEC_FLAG_PASS1)
8cb76ef2
             if ((ret = get_stats(avc_context, 1)) < 0)
                 return ret;
b0a6d9ca
         return 0;
     }
 
150d2772
     /* Copy planes to the theora yuv_buffer */
bdc8c488
     for (i = 0; i < 3; i++) {
af89b178
         t_yuv_buffer[i].width  = FFALIGN(avc_context->width,  16) >> (i && h->uv_hshift);
         t_yuv_buffer[i].height = FFALIGN(avc_context->height, 16) >> (i && h->uv_vshift);
bdc8c488
         t_yuv_buffer[i].stride = frame->linesize[i];
         t_yuv_buffer[i].data   = frame->data[i];
150d2772
     }
 
b0a6d9ca
     if (avc_context->flags & CODEC_FLAG_PASS2)
8cb76ef2
         if ((ret = submit_stats(avc_context)) < 0)
             return ret;
b0a6d9ca
 
150d2772
     /* Now call into theora_encode_YUVin */
bdc8c488
     result = th_encode_ycbcr_in(h->t_state, t_yuv_buffer);
96ff02f1
     if (result) {
150d2772
         const char* message;
         switch (result) {
8767fb4c
         case -1:
             message = "differing frame sizes";
             break;
bdc8c488
         case TH_EINVAL:
8767fb4c
             message = "encoder is not ready or is finished";
             break;
         default:
             message = "unknown reason";
             break;
150d2772
         }
         av_log(avc_context, AV_LOG_ERROR, "theora_encode_YUVin failed (%s) [%d]\n", message, result);
8cb76ef2
         return AVERROR_EXTERNAL;
150d2772
     }
 
b0a6d9ca
     if (avc_context->flags & CODEC_FLAG_PASS1)
8cb76ef2
         if ((ret = get_stats(avc_context, 0)) < 0)
             return ret;
b0a6d9ca
 
150d2772
     /* Pick up returned ogg_packet */
bdc8c488
     result = th_encode_packetout(h->t_state, 0, &o_packet);
150d2772
     switch (result) {
8767fb4c
     case 0:
         /* No packet is ready */
         return 0;
     case 1:
         /* Success, we have a packet */
         break;
     default:
         av_log(avc_context, AV_LOG_ERROR, "theora_encode_packetout failed [%d]\n", result);
8cb76ef2
         return AVERROR_EXTERNAL;
150d2772
     }
 
     /* Copy ogg_packet content out to buffer */
ae2c33b0
     if ((ret = ff_alloc_packet2(avc_context, pkt, o_packet.bytes)) < 0)
f7fa73ac
         return ret;
     memcpy(pkt->data, o_packet.packet, o_packet.bytes);
150d2772
 
a4914ac7
     // HACK: assumes no encoder delay, this is true until libtheora becomes
511cf612
     // multithreaded (which will be disabled unless explicitly requested)
f7fa73ac
     pkt->pts = pkt->dts = frame->pts;
c39b94be
     avc_context->coded_frame->key_frame = !(o_packet.granulepos & h->keyframe_mask);
f7fa73ac
     if (avc_context->coded_frame->key_frame)
         pkt->flags |= AV_PKT_FLAG_KEY;
     *got_packet = 1;
3bb98498
 
f7fa73ac
     return 0;
150d2772
 }
 
5ef251e5
 static av_cold int encode_close(AVCodecContext* avc_context)
150d2772
 {
     TheoraContext *h = avc_context->priv_data;
 
bdc8c488
     th_encode_free(h->t_state);
b0a6d9ca
     av_freep(&h->stats);
870ee6f7
     av_freep(&avc_context->coded_frame);
b0a6d9ca
     av_freep(&avc_context->stats_out);
870ee6f7
     av_freep(&avc_context->extradata);
     avc_context->extradata_size = 0;
 
b0a6d9ca
     return 0;
150d2772
 }
 
4311ff77
 /** AVCodec struct exposed to libavcodec */
e7e2df27
 AVCodec ff_libtheora_encoder = {
00c3b67b
     .name           = "libtheora",
b2bed932
     .long_name      = NULL_IF_CONFIG_SMALL("libtheora Theora"),
00c3b67b
     .type           = AVMEDIA_TYPE_VIDEO,
36ef5369
     .id             = AV_CODEC_ID_THEORA,
150d2772
     .priv_data_size = sizeof(TheoraContext),
00c3b67b
     .init           = encode_init,
     .close          = encode_close,
     .encode2        = encode_frame,
     .capabilities   = CODEC_CAP_DELAY, // needed to get the statsfile summary
716d413c
     .pix_fmts       = (const enum AVPixelFormat[]){
         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_NONE
00c3b67b
     },
150d2772
 };