libavcodec/libxavs.c
Go to the documentation of this file.
00001 /*
00002  * AVS encoding using the xavs library
00003  * Copyright (C) 2010 Amanda, Y.N. Wu <amanda11192003@gmail.com>
00004  *
00005  * This file is part of Libav.
00006  *
00007  * Libav is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * Libav is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with Libav; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00022 #include <stdio.h>
00023 #include <stdlib.h>
00024 #include <string.h>
00025 #include <math.h>
00026 #include <stdint.h>
00027 #include <float.h>
00028 #include <xavs.h>
00029 #include "avcodec.h"
00030 #include "internal.h"
00031 #include "libavutil/opt.h"
00032 
00033 #define END_OF_STREAM 0x001
00034 
00035 #define XAVS_PART_I8X8 0x002 /* Analyze i8x8 (requires 8x8 transform) */
00036 #define XAVS_PART_P8X8 0x010 /* Analyze p16x8, p8x16 and p8x8 */
00037 #define XAVS_PART_B8X8 0x100 /* Analyze b16x8, b*/
00038 
00039 typedef struct XavsContext {
00040     xavs_param_t    params;
00041     xavs_t         *enc;
00042     xavs_picture_t  pic;
00043     uint8_t        *sei;
00044     int             sei_size;
00045     AVFrame         out_pic;
00046     int             end_of_stream;
00047     float crf;
00048     int cqp;
00049     int b_bias;
00050     float cplxblur;
00051     int direct_pred;
00052     int aud;
00053     int fast_pskip;
00054     int mbtree;
00055     int mixed_refs;
00056 } XavsContext;
00057 
00058 static void XAVS_log(void *p, int level, const char *fmt, va_list args)
00059 {
00060     static const int level_map[] = {
00061         [XAVS_LOG_ERROR]   = AV_LOG_ERROR,
00062         [XAVS_LOG_WARNING] = AV_LOG_WARNING,
00063         [XAVS_LOG_INFO]    = AV_LOG_INFO,
00064         [XAVS_LOG_DEBUG]   = AV_LOG_DEBUG
00065     };
00066 
00067     if (level < 0 || level > XAVS_LOG_DEBUG)
00068         return;
00069 
00070     av_vlog(p, level_map[level], fmt, args);
00071 }
00072 
00073 static int encode_nals(AVCodecContext *ctx, uint8_t *buf,
00074                        int size, xavs_nal_t *nals,
00075                        int nnal, int skip_sei)
00076 {
00077     XavsContext *x4 = ctx->priv_data;
00078     uint8_t *p = buf;
00079     int i, s;
00080 
00081     /* Write the SEI as part of the first frame. */
00082     if (x4->sei_size > 0 && nnal > 0) {
00083         memcpy(p, x4->sei, x4->sei_size);
00084         p += x4->sei_size;
00085         x4->sei_size = 0;
00086     }
00087 
00088     for (i = 0; i < nnal; i++) {
00089         /* Don't put the SEI in extradata. */
00090         if (skip_sei && nals[i].i_type == NAL_SEI) {
00091             x4->sei = av_malloc( 5 + nals[i].i_payload * 4 / 3 );
00092             if (xavs_nal_encode(x4->sei, &x4->sei_size, 1, nals + i) < 0)
00093                 return -1;
00094 
00095             continue;
00096         }
00097         s = xavs_nal_encode(p, &size, 1, nals + i);
00098         if (s < 0)
00099             return -1;
00100         p += s;
00101     }
00102 
00103     return p - buf;
00104 }
00105 
00106 static int XAVS_frame(AVCodecContext *ctx, uint8_t *buf,
00107                       int bufsize, void *data)
00108 {
00109     XavsContext *x4 = ctx->priv_data;
00110     AVFrame *frame = data;
00111     xavs_nal_t *nal;
00112     int nnal, i;
00113     xavs_picture_t pic_out;
00114 
00115     x4->pic.img.i_csp   = XAVS_CSP_I420;
00116     x4->pic.img.i_plane = 3;
00117 
00118     if (frame) {
00119        for (i = 0; i < 3; i++) {
00120             x4->pic.img.plane[i] = frame->data[i];
00121             x4->pic.img.i_stride[i] = frame->linesize[i];
00122        }
00123 
00124         x4->pic.i_pts  = frame->pts;
00125         x4->pic.i_type = XAVS_TYPE_AUTO;
00126     }
00127 
00128     if (xavs_encoder_encode(x4->enc, &nal, &nnal,
00129                             frame? &x4->pic: NULL, &pic_out) < 0)
00130     return -1;
00131 
00132     bufsize = encode_nals(ctx, buf, bufsize, nal, nnal, 0);
00133 
00134     if (bufsize < 0)
00135         return -1;
00136 
00137     if (!bufsize && !frame && !(x4->end_of_stream)){
00138         buf[bufsize]   = 0x0;
00139         buf[bufsize+1] = 0x0;
00140         buf[bufsize+2] = 0x01;
00141         buf[bufsize+3] = 0xb1;
00142         bufsize += 4;
00143         x4->end_of_stream = END_OF_STREAM;
00144         return bufsize;
00145     }
00146     /* FIXME: libxavs now provides DTS */
00147     /* but AVFrame doesn't have a field for it. */
00148     x4->out_pic.pts = pic_out.i_pts;
00149 
00150     switch (pic_out.i_type) {
00151     case XAVS_TYPE_IDR:
00152     case XAVS_TYPE_I:
00153         x4->out_pic.pict_type = AV_PICTURE_TYPE_I;
00154         break;
00155     case XAVS_TYPE_P:
00156         x4->out_pic.pict_type = AV_PICTURE_TYPE_P;
00157         break;
00158     case XAVS_TYPE_B:
00159     case XAVS_TYPE_BREF:
00160         x4->out_pic.pict_type = AV_PICTURE_TYPE_B;
00161         break;
00162     }
00163 
00164     /* There is no IDR frame in AVS JiZhun */
00165     /* Sequence header is used as a flag */
00166     x4->out_pic.key_frame = pic_out.i_type == XAVS_TYPE_I;
00167 
00168     x4->out_pic.quality   = (pic_out.i_qpplus1 - 1) * FF_QP2LAMBDA;
00169 
00170     return bufsize;
00171 }
00172 
00173 static av_cold int XAVS_close(AVCodecContext *avctx)
00174 {
00175     XavsContext *x4 = avctx->priv_data;
00176 
00177     av_freep(&avctx->extradata);
00178     av_free(x4->sei);
00179 
00180     if (x4->enc)
00181         xavs_encoder_close(x4->enc);
00182 
00183     return 0;
00184 }
00185 
00186 static av_cold int XAVS_init(AVCodecContext *avctx)
00187 {
00188     XavsContext *x4 = avctx->priv_data;
00189 
00190     x4->sei_size = 0;
00191     xavs_param_default(&x4->params);
00192 
00193     x4->params.pf_log               = XAVS_log;
00194     x4->params.p_log_private        = avctx;
00195     x4->params.i_keyint_max         = avctx->gop_size;
00196     if (avctx->bit_rate) {
00197         x4->params.rc.i_bitrate   = avctx->bit_rate / 1000;
00198         x4->params.rc.i_rc_method = XAVS_RC_ABR;
00199     }
00200     x4->params.rc.i_vbv_buffer_size = avctx->rc_buffer_size / 1000;
00201     x4->params.rc.i_vbv_max_bitrate = avctx->rc_max_rate    / 1000;
00202     x4->params.rc.b_stat_write      = avctx->flags & CODEC_FLAG_PASS1;
00203     if (avctx->flags & CODEC_FLAG_PASS2) {
00204         x4->params.rc.b_stat_read = 1;
00205     } else {
00206 #if FF_API_X264_GLOBAL_OPTS
00207         if (avctx->crf) {
00208             x4->params.rc.i_rc_method   = XAVS_RC_CRF;
00209             x4->params.rc.f_rf_constant = avctx->crf;
00210         } else if (avctx->cqp > -1) {
00211             x4->params.rc.i_rc_method   = XAVS_RC_CQP;
00212             x4->params.rc.i_qp_constant = avctx->cqp;
00213         }
00214 #endif
00215 
00216         if (x4->crf >= 0) {
00217             x4->params.rc.i_rc_method   = XAVS_RC_CRF;
00218             x4->params.rc.f_rf_constant = x4->crf;
00219         } else if (x4->cqp >= 0) {
00220             x4->params.rc.i_rc_method   = XAVS_RC_CQP;
00221             x4->params.rc.i_qp_constant = x4->cqp;
00222         }
00223     }
00224 
00225 #if FF_API_X264_GLOBAL_OPTS
00226     if (avctx->bframebias)
00227         x4->params.i_bframe_bias              = avctx->bframebias;
00228     if (avctx->deblockalpha)
00229         x4->params.i_deblocking_filter_alphac0 = avctx->deblockalpha;
00230     if (avctx->deblockbeta)
00231         x4->params.i_deblocking_filter_beta    = avctx->deblockbeta;
00232     if (avctx->complexityblur >= 0)
00233         x4->params.rc.f_complexity_blur        = avctx->complexityblur;
00234     if (avctx->directpred >= 0)
00235         x4->params.analyse.i_direct_mv_pred    = avctx->directpred;
00236     if (avctx->partitions) {
00237         if (avctx->partitions & XAVS_PART_I8X8)
00238             x4->params.analyse.inter |= XAVS_ANALYSE_I8x8;
00239         if (avctx->partitions & XAVS_PART_P8X8)
00240             x4->params.analyse.inter |= XAVS_ANALYSE_PSUB16x16;
00241         if (avctx->partitions & XAVS_PART_B8X8)
00242             x4->params.analyse.inter |= XAVS_ANALYSE_BSUB16x16;
00243     }
00244     x4->params.rc.b_mb_tree               = !!(avctx->flags2 & CODEC_FLAG2_MBTREE);
00245     x4->params.b_aud          = avctx->flags2 & CODEC_FLAG2_AUD;
00246     x4->params.analyse.b_mixed_references = avctx->flags2 & CODEC_FLAG2_MIXED_REFS;
00247     x4->params.analyse.b_fast_pskip       = avctx->flags2 & CODEC_FLAG2_FASTPSKIP;
00248     x4->params.analyse.b_weighted_bipred = avctx->flags2 & CODEC_FLAG2_WPRED;
00249 #endif
00250 
00251     if (x4->aud >= 0)
00252         x4->params.b_aud                      = x4->aud;
00253     if (x4->mbtree >= 0)
00254         x4->params.rc.b_mb_tree               = x4->mbtree;
00255     if (x4->direct_pred >= 0)
00256         x4->params.analyse.i_direct_mv_pred   = x4->direct_pred;
00257     if (x4->fast_pskip >= 0)
00258         x4->params.analyse.b_fast_pskip       = x4->fast_pskip;
00259     if (x4->mixed_refs >= 0)
00260         x4->params.analyse.b_mixed_references = x4->mixed_refs;
00261     if (x4->b_bias != INT_MIN)
00262         x4->params.i_bframe_bias              = x4->b_bias;
00263     if (x4->cplxblur >= 0)
00264         x4->params.rc.f_complexity_blur = x4->cplxblur;
00265 
00266     x4->params.i_bframe          = avctx->max_b_frames;
00267     /* cabac is not included in AVS JiZhun Profile */
00268     x4->params.b_cabac           = 0;
00269 
00270     x4->params.i_bframe_adaptive = avctx->b_frame_strategy;
00271 
00272     avctx->has_b_frames          = !!avctx->max_b_frames;
00273 
00274     /* AVS doesn't allow B picture as reference */
00275     /* The max allowed reference frame number of B is 2 */
00276     x4->params.i_keyint_min      = avctx->keyint_min;
00277     if (x4->params.i_keyint_min > x4->params.i_keyint_max)
00278         x4->params.i_keyint_min = x4->params.i_keyint_max;
00279 
00280     x4->params.i_scenecut_threshold        = avctx->scenechange_threshold;
00281 
00282    // x4->params.b_deblocking_filter       = avctx->flags & CODEC_FLAG_LOOP_FILTER;
00283 
00284     x4->params.rc.i_qp_min                 = avctx->qmin;
00285     x4->params.rc.i_qp_max                 = avctx->qmax;
00286     x4->params.rc.i_qp_step                = avctx->max_qdiff;
00287 
00288     x4->params.rc.f_qcompress       = avctx->qcompress; /* 0.0 => cbr, 1.0 => constant qp */
00289     x4->params.rc.f_qblur           = avctx->qblur;     /* temporally blur quants */
00290 
00291     x4->params.i_frame_reference    = avctx->refs;
00292 
00293     x4->params.i_width              = avctx->width;
00294     x4->params.i_height             = avctx->height;
00295     x4->params.vui.i_sar_width      = avctx->sample_aspect_ratio.num;
00296     x4->params.vui.i_sar_height     = avctx->sample_aspect_ratio.den;
00297     /* This is only used for counting the fps */
00298     x4->params.i_fps_num            = avctx->time_base.den;
00299     x4->params.i_fps_den            = avctx->time_base.num;
00300     x4->params.analyse.inter        = XAVS_ANALYSE_I8x8 |XAVS_ANALYSE_PSUB16x16| XAVS_ANALYSE_BSUB16x16;
00301 
00302     switch (avctx->me_method) {
00303          case  ME_EPZS:
00304                x4->params.analyse.i_me_method = XAVS_ME_DIA;
00305                break;
00306          case  ME_HEX:
00307                x4->params.analyse.i_me_method = XAVS_ME_HEX;
00308                break;
00309          case  ME_UMH:
00310                x4->params.analyse.i_me_method = XAVS_ME_UMH;
00311                break;
00312          case  ME_FULL:
00313                x4->params.analyse.i_me_method = XAVS_ME_ESA;
00314                break;
00315          case  ME_TESA:
00316                x4->params.analyse.i_me_method = XAVS_ME_TESA;
00317                break;
00318          default:
00319                x4->params.analyse.i_me_method = XAVS_ME_HEX;
00320     }
00321 
00322     x4->params.analyse.i_me_range = avctx->me_range;
00323     x4->params.analyse.i_subpel_refine    = avctx->me_subpel_quality;
00324 
00325     x4->params.analyse.b_chroma_me        = avctx->me_cmp & FF_CMP_CHROMA;
00326     /* AVS P2 only enables 8x8 transform */
00327     x4->params.analyse.b_transform_8x8    = 1; //avctx->flags2 & CODEC_FLAG2_8X8DCT;
00328 
00329     x4->params.analyse.i_trellis          = avctx->trellis;
00330     x4->params.analyse.i_noise_reduction  = avctx->noise_reduction;
00331 
00332     if (avctx->level > 0)
00333         x4->params.i_level_idc = avctx->level;
00334 
00335     x4->params.rc.f_rate_tolerance =
00336         (float)avctx->bit_rate_tolerance/avctx->bit_rate;
00337 
00338     if ((avctx->rc_buffer_size) &&
00339         (avctx->rc_initial_buffer_occupancy <= avctx->rc_buffer_size)) {
00340         x4->params.rc.f_vbv_buffer_init =
00341             (float)avctx->rc_initial_buffer_occupancy / avctx->rc_buffer_size;
00342     } else
00343         x4->params.rc.f_vbv_buffer_init = 0.9;
00344 
00345     /* TAG:do we have MB tree RC method */
00346     /* what is the RC method we are now using? Default NO */
00347     x4->params.rc.f_ip_factor             = 1 / fabs(avctx->i_quant_factor);
00348     x4->params.rc.f_pb_factor             = avctx->b_quant_factor;
00349     x4->params.analyse.i_chroma_qp_offset = avctx->chromaoffset;
00350 
00351     x4->params.analyse.b_psnr = avctx->flags & CODEC_FLAG_PSNR;
00352     x4->params.i_log_level    = XAVS_LOG_DEBUG;
00353     x4->params.i_threads      = avctx->thread_count;
00354     x4->params.b_interlaced   = avctx->flags & CODEC_FLAG_INTERLACED_DCT;
00355 
00356     if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER)
00357         x4->params.b_repeat_headers = 0;
00358 
00359     x4->enc = xavs_encoder_open(&x4->params);
00360     if (!x4->enc)
00361         return -1;
00362 
00363     avctx->coded_frame = &x4->out_pic;
00364     /* TAG: Do we have GLOBAL HEADER in AVS */
00365     /* We Have PPS and SPS in AVS */
00366     if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) {
00367         xavs_nal_t *nal;
00368         int nnal, s;
00369 
00370         s = xavs_encoder_headers(x4->enc, &nal, &nnal);
00371 
00372         avctx->extradata      = av_malloc(s);
00373         avctx->extradata_size = encode_nals(avctx, avctx->extradata, s, nal, nnal, 1);
00374     }
00375     return 0;
00376 }
00377 
00378 #define OFFSET(x) offsetof(XavsContext, x)
00379 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
00380 static const AVOption options[] = {
00381     { "crf",           "Select the quality for constant quality mode",    OFFSET(crf),           AV_OPT_TYPE_FLOAT,  {-1 }, -1, FLT_MAX, VE },
00382     { "qp",            "Constant quantization parameter rate control method",OFFSET(cqp),        AV_OPT_TYPE_INT,    {-1 }, -1, INT_MAX, VE },
00383     { "b-bias",        "Influences how often B-frames are used",          OFFSET(b_bias),        AV_OPT_TYPE_INT,    {INT_MIN}, INT_MIN, INT_MAX, VE },
00384     { "cplxblur",      "Reduce fluctuations in QP (before curve compression)", OFFSET(cplxblur), AV_OPT_TYPE_FLOAT,  {-1 }, -1, FLT_MAX, VE},
00385     { "direct-pred",   "Direct MV prediction mode",                       OFFSET(direct_pred),   AV_OPT_TYPE_INT,    {-1 }, -1, INT_MAX, VE, "direct-pred" },
00386     { "none",          NULL,      0,    AV_OPT_TYPE_CONST, { XAVS_DIRECT_PRED_NONE },     0, 0, VE, "direct-pred" },
00387     { "spatial",       NULL,      0,    AV_OPT_TYPE_CONST, { XAVS_DIRECT_PRED_SPATIAL },  0, 0, VE, "direct-pred" },
00388     { "temporal",      NULL,      0,    AV_OPT_TYPE_CONST, { XAVS_DIRECT_PRED_TEMPORAL }, 0, 0, VE, "direct-pred" },
00389     { "auto",          NULL,      0,    AV_OPT_TYPE_CONST, { XAVS_DIRECT_PRED_AUTO },     0, 0, VE, "direct-pred" },
00390     { "aud",           "Use access unit delimiters.",                     OFFSET(aud),           AV_OPT_TYPE_INT,    {-1 }, -1, 1, VE},
00391     { "mbtree",        "Use macroblock tree ratecontrol.",                OFFSET(mbtree),        AV_OPT_TYPE_INT,    {-1 }, -1, 1, VE},
00392     { "mixed-refs",    "One reference per partition, as opposed to one reference per macroblock", OFFSET(mixed_refs), AV_OPT_TYPE_INT, {-1}, -1, 1, VE },
00393     { "fast-pskip",    NULL,                                              OFFSET(fast_pskip),    AV_OPT_TYPE_INT,    {-1 }, -1, 1, VE},
00394     { NULL },
00395 };
00396 
00397 static const AVClass class = {
00398     .class_name = "libxavs",
00399     .item_name  = av_default_item_name,
00400     .option     = options,
00401     .version    = LIBAVUTIL_VERSION_INT,
00402 };
00403 
00404 static const AVCodecDefault xavs_defaults[] = {
00405     { "b",                "0" },
00406     { NULL },
00407 };
00408 
00409 AVCodec ff_libxavs_encoder = {
00410     .name           = "libxavs",
00411     .type           = AVMEDIA_TYPE_VIDEO,
00412     .id             = CODEC_ID_CAVS,
00413     .priv_data_size = sizeof(XavsContext),
00414     .init           = XAVS_init,
00415     .encode         = XAVS_frame,
00416     .close          = XAVS_close,
00417     .capabilities   = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
00418     .pix_fmts       = (const enum PixelFormat[]) { PIX_FMT_YUV420P, PIX_FMT_NONE },
00419     .long_name      = NULL_IF_CONFIG_SMALL("libxavs - the Chinese Audio Video Standard Encoder"),
00420     .priv_class     = &class,
00421     .defaults       = xavs_defaults,
00422 };
00423