libavcodec/libvpxenc.c
Go to the documentation of this file.
00001 /*
00002  * Copyright (c) 2010, Google, Inc.
00003  *
00004  * This file is part of FFmpeg.
00005  *
00006  * FFmpeg is free software; you can redistribute it and/or
00007  * modify it under the terms of the GNU Lesser General Public
00008  * License as published by the Free Software Foundation; either
00009  * version 2.1 of the License, or (at your option) any later version.
00010  *
00011  * FFmpeg is distributed in the hope that it will be useful,
00012  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00013  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014  * Lesser General Public License for more details.
00015  *
00016  * You should have received a copy of the GNU Lesser General Public
00017  * License along with FFmpeg; if not, write to the Free Software
00018  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00019  */
00020 
00026 #define VPX_DISABLE_CTRL_TYPECHECKS 1
00027 #define VPX_CODEC_DISABLE_COMPAT    1
00028 #include <vpx/vpx_encoder.h>
00029 #include <vpx/vp8cx.h>
00030 
00031 #include "avcodec.h"
00032 #include "internal.h"
00033 #include "libavutil/base64.h"
00034 #include "libavutil/mathematics.h"
00035 #include "libavutil/opt.h"
00036 
00041 struct FrameListData {
00042     void *buf;                       
00043     size_t sz;                       
00044     int64_t pts;                     
00046     unsigned long duration;          
00048     uint32_t flags;                  
00049     struct FrameListData *next;
00050 };
00051 
00052 typedef struct VP8EncoderContext {
00053     AVClass *class;
00054     struct vpx_codec_ctx encoder;
00055     struct vpx_image rawimg;
00056     struct vpx_fixed_buf twopass_stats;
00057     int deadline; //i.e., RT/GOOD/BEST
00058     struct FrameListData *coded_frame_list;
00059 
00060     int cpu_used;
00064     int flags;
00065 #define VP8F_ERROR_RESILIENT 0x00000001 ///< Enable measures appropriate for streaming over lossy links
00066 #define VP8F_AUTO_ALT_REF    0x00000002 ///< Enable automatic alternate reference frame generation
00067 
00068     int auto_alt_ref;
00069 
00070     int arnr_max_frames;
00071     int arnr_strength;
00072     int arnr_type;
00073 
00074     int lag_in_frames;
00075     int error_resilient;
00076     int crf;
00077 } VP8Context;
00078 
00080 static const char *ctlidstr[] = {
00081     [VP8E_UPD_ENTROPY]           = "VP8E_UPD_ENTROPY",
00082     [VP8E_UPD_REFERENCE]         = "VP8E_UPD_REFERENCE",
00083     [VP8E_USE_REFERENCE]         = "VP8E_USE_REFERENCE",
00084     [VP8E_SET_ROI_MAP]           = "VP8E_SET_ROI_MAP",
00085     [VP8E_SET_ACTIVEMAP]         = "VP8E_SET_ACTIVEMAP",
00086     [VP8E_SET_SCALEMODE]         = "VP8E_SET_SCALEMODE",
00087     [VP8E_SET_CPUUSED]           = "VP8E_SET_CPUUSED",
00088     [VP8E_SET_ENABLEAUTOALTREF]  = "VP8E_SET_ENABLEAUTOALTREF",
00089     [VP8E_SET_NOISE_SENSITIVITY] = "VP8E_SET_NOISE_SENSITIVITY",
00090     [VP8E_SET_SHARPNESS]         = "VP8E_SET_SHARPNESS",
00091     [VP8E_SET_STATIC_THRESHOLD]  = "VP8E_SET_STATIC_THRESHOLD",
00092     [VP8E_SET_TOKEN_PARTITIONS]  = "VP8E_SET_TOKEN_PARTITIONS",
00093     [VP8E_GET_LAST_QUANTIZER]    = "VP8E_GET_LAST_QUANTIZER",
00094     [VP8E_SET_ARNR_MAXFRAMES]    = "VP8E_SET_ARNR_MAXFRAMES",
00095     [VP8E_SET_ARNR_STRENGTH]     = "VP8E_SET_ARNR_STRENGTH",
00096     [VP8E_SET_ARNR_TYPE]         = "VP8E_SET_ARNR_TYPE",
00097     [VP8E_SET_CQ_LEVEL]          = "VP8E_SET_CQ_LEVEL",
00098 };
00099 
00100 static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
00101 {
00102     VP8Context *ctx = avctx->priv_data;
00103     const char *error  = vpx_codec_error(&ctx->encoder);
00104     const char *detail = vpx_codec_error_detail(&ctx->encoder);
00105 
00106     av_log(avctx, AV_LOG_ERROR, "%s: %s\n", desc, error);
00107     if (detail)
00108         av_log(avctx, AV_LOG_ERROR, "  Additional information: %s\n", detail);
00109 }
00110 
00111 static av_cold void dump_enc_cfg(AVCodecContext *avctx,
00112                                  const struct vpx_codec_enc_cfg *cfg)
00113 {
00114     int width = -30;
00115     int level = AV_LOG_DEBUG;
00116 
00117     av_log(avctx, level, "vpx_codec_enc_cfg\n");
00118     av_log(avctx, level, "generic settings\n"
00119            "  %*s%u\n  %*s%u\n  %*s%u\n  %*s%u\n  %*s%u\n"
00120            "  %*s{%u/%u}\n  %*s%u\n  %*s%d\n  %*s%u\n",
00121            width, "g_usage:",           cfg->g_usage,
00122            width, "g_threads:",         cfg->g_threads,
00123            width, "g_profile:",         cfg->g_profile,
00124            width, "g_w:",               cfg->g_w,
00125            width, "g_h:",               cfg->g_h,
00126            width, "g_timebase:",        cfg->g_timebase.num, cfg->g_timebase.den,
00127            width, "g_error_resilient:", cfg->g_error_resilient,
00128            width, "g_pass:",            cfg->g_pass,
00129            width, "g_lag_in_frames:",   cfg->g_lag_in_frames);
00130     av_log(avctx, level, "rate control settings\n"
00131            "  %*s%u\n  %*s%u\n  %*s%u\n  %*s%u\n"
00132            "  %*s%d\n  %*s%p(%zu)\n  %*s%u\n",
00133            width, "rc_dropframe_thresh:",   cfg->rc_dropframe_thresh,
00134            width, "rc_resize_allowed:",     cfg->rc_resize_allowed,
00135            width, "rc_resize_up_thresh:",   cfg->rc_resize_up_thresh,
00136            width, "rc_resize_down_thresh:", cfg->rc_resize_down_thresh,
00137            width, "rc_end_usage:",          cfg->rc_end_usage,
00138            width, "rc_twopass_stats_in:",   cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,
00139            width, "rc_target_bitrate:",     cfg->rc_target_bitrate);
00140     av_log(avctx, level, "quantizer settings\n"
00141            "  %*s%u\n  %*s%u\n",
00142            width, "rc_min_quantizer:", cfg->rc_min_quantizer,
00143            width, "rc_max_quantizer:", cfg->rc_max_quantizer);
00144     av_log(avctx, level, "bitrate tolerance\n"
00145            "  %*s%u\n  %*s%u\n",
00146            width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,
00147            width, "rc_overshoot_pct:",  cfg->rc_overshoot_pct);
00148     av_log(avctx, level, "decoder buffer model\n"
00149             "  %*s%u\n  %*s%u\n  %*s%u\n",
00150             width, "rc_buf_sz:",         cfg->rc_buf_sz,
00151             width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,
00152             width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);
00153     av_log(avctx, level, "2 pass rate control settings\n"
00154            "  %*s%u\n  %*s%u\n  %*s%u\n",
00155            width, "rc_2pass_vbr_bias_pct:",       cfg->rc_2pass_vbr_bias_pct,
00156            width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,
00157            width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);
00158     av_log(avctx, level, "keyframing settings\n"
00159            "  %*s%d\n  %*s%u\n  %*s%u\n",
00160            width, "kf_mode:",     cfg->kf_mode,
00161            width, "kf_min_dist:", cfg->kf_min_dist,
00162            width, "kf_max_dist:", cfg->kf_max_dist);
00163     av_log(avctx, level, "\n");
00164 }
00165 
00166 static void coded_frame_add(void *list, struct FrameListData *cx_frame)
00167 {
00168     struct FrameListData **p = list;
00169 
00170     while (*p != NULL)
00171         p = &(*p)->next;
00172     *p = cx_frame;
00173     cx_frame->next = NULL;
00174 }
00175 
00176 static av_cold void free_coded_frame(struct FrameListData *cx_frame)
00177 {
00178     av_freep(&cx_frame->buf);
00179     av_freep(&cx_frame);
00180 }
00181 
00182 static av_cold void free_frame_list(struct FrameListData *list)
00183 {
00184     struct FrameListData *p = list;
00185 
00186     while (p) {
00187         list = list->next;
00188         free_coded_frame(p);
00189         p = list;
00190     }
00191 }
00192 
00193 static av_cold int codecctl_int(AVCodecContext *avctx,
00194                                 enum vp8e_enc_control_id id, int val)
00195 {
00196     VP8Context *ctx = avctx->priv_data;
00197     char buf[80];
00198     int width = -30;
00199     int res;
00200 
00201     snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
00202     av_log(avctx, AV_LOG_DEBUG, "  %*s%d\n", width, buf, val);
00203 
00204     res = vpx_codec_control(&ctx->encoder, id, val);
00205     if (res != VPX_CODEC_OK) {
00206         snprintf(buf, sizeof(buf), "Failed to set %s codec control",
00207                  ctlidstr[id]);
00208         log_encoder_error(avctx, buf);
00209     }
00210 
00211     return res == VPX_CODEC_OK ? 0 : AVERROR(EINVAL);
00212 }
00213 
00214 static av_cold int vp8_free(AVCodecContext *avctx)
00215 {
00216     VP8Context *ctx = avctx->priv_data;
00217 
00218     vpx_codec_destroy(&ctx->encoder);
00219     av_freep(&ctx->twopass_stats.buf);
00220     av_freep(&avctx->coded_frame);
00221     av_freep(&avctx->stats_out);
00222     free_frame_list(ctx->coded_frame_list);
00223     return 0;
00224 }
00225 
00226 static av_cold int vp8_init(AVCodecContext *avctx)
00227 {
00228     VP8Context *ctx = avctx->priv_data;
00229     const struct vpx_codec_iface *iface = &vpx_codec_vp8_cx_algo;
00230     struct vpx_codec_enc_cfg enccfg;
00231     int res;
00232 
00233     av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str());
00234     av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config());
00235 
00236     if ((res = vpx_codec_enc_config_default(iface, &enccfg, 0)) != VPX_CODEC_OK) {
00237         av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
00238                vpx_codec_err_to_string(res));
00239         return AVERROR(EINVAL);
00240     }
00241     dump_enc_cfg(avctx, &enccfg);
00242 
00243     enccfg.g_w            = avctx->width;
00244     enccfg.g_h            = avctx->height;
00245     enccfg.g_timebase.num = avctx->time_base.num;
00246     enccfg.g_timebase.den = avctx->time_base.den;
00247     enccfg.g_threads      = avctx->thread_count;
00248 #if FF_API_X264_GLOBAL_OPTS
00249     if(avctx->rc_lookahead >= 0)
00250         enccfg.g_lag_in_frames= FFMIN(avctx->rc_lookahead, 25);  //0-25, avoids init failure
00251     if (ctx->lag_in_frames >= 0)
00252         enccfg.g_lag_in_frames = ctx->lag_in_frames;
00253 #else
00254     enccfg.g_lag_in_frames= ctx->lag_in_frames;
00255 #endif
00256 
00257     if (avctx->flags & CODEC_FLAG_PASS1)
00258         enccfg.g_pass = VPX_RC_FIRST_PASS;
00259     else if (avctx->flags & CODEC_FLAG_PASS2)
00260         enccfg.g_pass = VPX_RC_LAST_PASS;
00261     else
00262         enccfg.g_pass = VPX_RC_ONE_PASS;
00263 
00264     if (avctx->rc_min_rate == avctx->rc_max_rate &&
00265         avctx->rc_min_rate == avctx->bit_rate)
00266         enccfg.rc_end_usage = VPX_CBR;
00267 #if FF_API_X264_GLOBAL_OPTS
00268     else if (avctx->crf || ctx->crf > 0)
00269 #else
00270     else if (ctx->crf)
00271 #endif
00272         enccfg.rc_end_usage = VPX_CQ;
00273     enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
00274                                               AV_ROUND_NEAR_INF);
00275     if (avctx->qmin > 0)
00276         enccfg.rc_min_quantizer = avctx->qmin;
00277     if (avctx->qmax > 0)
00278         enccfg.rc_max_quantizer = avctx->qmax;
00279     enccfg.rc_dropframe_thresh = avctx->frame_skip_threshold;
00280 
00281     //0-100 (0 => CBR, 100 => VBR)
00282     enccfg.rc_2pass_vbr_bias_pct           = round(avctx->qcompress * 100);
00283     enccfg.rc_2pass_vbr_minsection_pct     =
00284         avctx->rc_min_rate * 100LL / avctx->bit_rate;
00285     if (avctx->rc_max_rate)
00286         enccfg.rc_2pass_vbr_maxsection_pct =
00287             avctx->rc_max_rate * 100LL / avctx->bit_rate;
00288 
00289     if (avctx->rc_buffer_size)
00290         enccfg.rc_buf_sz         =
00291             avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
00292     if (avctx->rc_initial_buffer_occupancy)
00293         enccfg.rc_buf_initial_sz =
00294             avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
00295     enccfg.rc_buf_optimal_sz     = enccfg.rc_buf_sz * 5 / 6;
00296     enccfg.rc_undershoot_pct     = round(avctx->rc_buffer_aggressivity * 100);
00297 
00298     //_enc_init() will balk if kf_min_dist differs from max w/VPX_KF_AUTO
00299     if (avctx->keyint_min >= 0 && avctx->keyint_min == avctx->gop_size)
00300         enccfg.kf_min_dist = avctx->keyint_min;
00301     if (avctx->gop_size >= 0)
00302         enccfg.kf_max_dist = avctx->gop_size;
00303 
00304     if (enccfg.g_pass == VPX_RC_FIRST_PASS)
00305         enccfg.g_lag_in_frames = 0;
00306     else if (enccfg.g_pass == VPX_RC_LAST_PASS) {
00307         int decode_size;
00308 
00309         if (!avctx->stats_in) {
00310             av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
00311             return AVERROR_INVALIDDATA;
00312         }
00313 
00314         ctx->twopass_stats.sz  = strlen(avctx->stats_in) * 3 / 4;
00315         ctx->twopass_stats.buf = av_malloc(ctx->twopass_stats.sz);
00316         if (!ctx->twopass_stats.buf) {
00317             av_log(avctx, AV_LOG_ERROR,
00318                    "Stat buffer alloc (%zu bytes) failed\n",
00319                    ctx->twopass_stats.sz);
00320             return AVERROR(ENOMEM);
00321         }
00322         decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
00323                                        ctx->twopass_stats.sz);
00324         if (decode_size < 0) {
00325             av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
00326             return AVERROR_INVALIDDATA;
00327         }
00328 
00329         ctx->twopass_stats.sz      = decode_size;
00330         enccfg.rc_twopass_stats_in = ctx->twopass_stats;
00331     }
00332 
00333     /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
00334        complexity playback on low powered devices at the expense of encode
00335        quality. */
00336    if (avctx->profile != FF_PROFILE_UNKNOWN)
00337        enccfg.g_profile = avctx->profile;
00338 
00339     enccfg.g_error_resilient = ctx->error_resilient || ctx->flags & VP8F_ERROR_RESILIENT;
00340 
00341     dump_enc_cfg(avctx, &enccfg);
00342     /* Construct Encoder Context */
00343     res = vpx_codec_enc_init(&ctx->encoder, iface, &enccfg, 0);
00344     if (res != VPX_CODEC_OK) {
00345         log_encoder_error(avctx, "Failed to initialize encoder");
00346         return AVERROR(EINVAL);
00347     }
00348 
00349     //codec control failures are currently treated only as warnings
00350     av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");
00351     if (ctx->cpu_used != INT_MIN)
00352         codecctl_int(avctx, VP8E_SET_CPUUSED,          ctx->cpu_used);
00353     if (ctx->flags & VP8F_AUTO_ALT_REF)
00354         ctx->auto_alt_ref = 1;
00355     if (ctx->auto_alt_ref >= 0)
00356         codecctl_int(avctx, VP8E_SET_ENABLEAUTOALTREF, ctx->auto_alt_ref);
00357     if (ctx->arnr_max_frames >= 0)
00358         codecctl_int(avctx, VP8E_SET_ARNR_MAXFRAMES,   ctx->arnr_max_frames);
00359     if (ctx->arnr_strength >= 0)
00360         codecctl_int(avctx, VP8E_SET_ARNR_STRENGTH,    ctx->arnr_strength);
00361     if (ctx->arnr_type >= 0)
00362         codecctl_int(avctx, VP8E_SET_ARNR_TYPE,        ctx->arnr_type);
00363     codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, avctx->noise_reduction);
00364     codecctl_int(avctx, VP8E_SET_TOKEN_PARTITIONS,  av_log2(avctx->slices));
00365     codecctl_int(avctx, VP8E_SET_STATIC_THRESHOLD,  avctx->mb_threshold);
00366 #if FF_API_X264_GLOBAL_OPTS
00367     codecctl_int(avctx, VP8E_SET_CQ_LEVEL,          (int)avctx->crf);
00368     if (ctx->crf >= 0)
00369         codecctl_int(avctx, VP8E_SET_CQ_LEVEL,      ctx->crf);
00370 #else
00371     codecctl_int(avctx, VP8E_SET_CQ_LEVEL,          ctx->crf);
00372 #endif
00373 
00374     av_log(avctx, AV_LOG_DEBUG, "Using deadline: %d\n", ctx->deadline);
00375 
00376     //provide dummy value to initialize wrapper, values will be updated each _encode()
00377     vpx_img_wrap(&ctx->rawimg, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,
00378                  (unsigned char*)1);
00379 
00380     avctx->coded_frame = avcodec_alloc_frame();
00381     if (!avctx->coded_frame) {
00382         av_log(avctx, AV_LOG_ERROR, "Error allocating coded frame\n");
00383         vp8_free(avctx);
00384         return AVERROR(ENOMEM);
00385     }
00386     return 0;
00387 }
00388 
00389 static inline void cx_pktcpy(struct FrameListData *dst,
00390                              const struct vpx_codec_cx_pkt *src)
00391 {
00392     dst->pts      = src->data.frame.pts;
00393     dst->duration = src->data.frame.duration;
00394     dst->flags    = src->data.frame.flags;
00395     dst->sz       = src->data.frame.sz;
00396     dst->buf      = src->data.frame.buf;
00397 }
00398 
00407 static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
00408                       uint8_t *buf, int buf_size, AVFrame *coded_frame)
00409 {
00410     if ((int) cx_frame->sz <= buf_size) {
00411         buf_size = cx_frame->sz;
00412         memcpy(buf, cx_frame->buf, buf_size);
00413         coded_frame->pts       = cx_frame->pts;
00414         coded_frame->key_frame = !!(cx_frame->flags & VPX_FRAME_IS_KEY);
00415 
00416         if (coded_frame->key_frame)
00417             coded_frame->pict_type = AV_PICTURE_TYPE_I;
00418         else
00419             coded_frame->pict_type = AV_PICTURE_TYPE_P;
00420     } else {
00421         av_log(avctx, AV_LOG_ERROR,
00422                "Compressed frame larger than storage provided! (%zu/%d)\n",
00423                cx_frame->sz, buf_size);
00424         return AVERROR(EINVAL);
00425     }
00426     return buf_size;
00427 }
00428 
00437 static int queue_frames(AVCodecContext *avctx, uint8_t *buf, int buf_size,
00438                         AVFrame *coded_frame)
00439 {
00440     VP8Context *ctx = avctx->priv_data;
00441     const struct vpx_codec_cx_pkt *pkt;
00442     const void *iter = NULL;
00443     int size = 0;
00444 
00445     if (ctx->coded_frame_list) {
00446         struct FrameListData *cx_frame = ctx->coded_frame_list;
00447         /* return the leading frame if we've already begun queueing */
00448         size = storeframe(avctx, cx_frame, buf, buf_size, coded_frame);
00449         if (size < 0)
00450             return AVERROR(EINVAL);
00451         ctx->coded_frame_list = cx_frame->next;
00452         free_coded_frame(cx_frame);
00453     }
00454 
00455     /* consume all available output from the encoder before returning. buffers
00456        are only good through the next vpx_codec call */
00457     while ((pkt = vpx_codec_get_cx_data(&ctx->encoder, &iter))) {
00458         switch (pkt->kind) {
00459         case VPX_CODEC_CX_FRAME_PKT:
00460             if (!size) {
00461                 struct FrameListData cx_frame;
00462 
00463                 /* avoid storing the frame when the list is empty and we haven't yet
00464                    provided a frame for output */
00465                 assert(!ctx->coded_frame_list);
00466                 cx_pktcpy(&cx_frame, pkt);
00467                 size = storeframe(avctx, &cx_frame, buf, buf_size, coded_frame);
00468                 if (size < 0)
00469                     return AVERROR(EINVAL);
00470             } else {
00471                 struct FrameListData *cx_frame =
00472                     av_malloc(sizeof(struct FrameListData));
00473 
00474                 if (!cx_frame) {
00475                     av_log(avctx, AV_LOG_ERROR,
00476                            "Frame queue element alloc failed\n");
00477                     return AVERROR(ENOMEM);
00478                 }
00479                 cx_pktcpy(cx_frame, pkt);
00480                 cx_frame->buf = av_malloc(cx_frame->sz);
00481 
00482                 if (!cx_frame->buf) {
00483                     av_log(avctx, AV_LOG_ERROR,
00484                            "Data buffer alloc (%zu bytes) failed\n",
00485                            cx_frame->sz);
00486                     av_free(cx_frame);
00487                     return AVERROR(ENOMEM);
00488                 }
00489                 memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
00490                 coded_frame_add(&ctx->coded_frame_list, cx_frame);
00491             }
00492             break;
00493         case VPX_CODEC_STATS_PKT: {
00494             struct vpx_fixed_buf *stats = &ctx->twopass_stats;
00495             stats->buf = av_realloc_f(stats->buf, 1,
00496                                       stats->sz + pkt->data.twopass_stats.sz);
00497             if (!stats->buf) {
00498                 av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
00499                 return AVERROR(ENOMEM);
00500             }
00501             memcpy((uint8_t*)stats->buf + stats->sz,
00502                    pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
00503             stats->sz += pkt->data.twopass_stats.sz;
00504             break;
00505         }
00506         case VPX_CODEC_PSNR_PKT: //FIXME add support for CODEC_FLAG_PSNR
00507         case VPX_CODEC_CUSTOM_PKT:
00508             //ignore unsupported/unrecognized packet types
00509             break;
00510         }
00511     }
00512 
00513     return size;
00514 }
00515 
00516 static int vp8_encode(AVCodecContext *avctx, uint8_t *buf, int buf_size,
00517                       void *data)
00518 {
00519     VP8Context *ctx = avctx->priv_data;
00520     AVFrame *frame = data;
00521     struct vpx_image *rawimg = NULL;
00522     int64_t timestamp = 0;
00523     int res, coded_size;
00524 
00525     if (frame) {
00526         rawimg                      = &ctx->rawimg;
00527         rawimg->planes[VPX_PLANE_Y] = frame->data[0];
00528         rawimg->planes[VPX_PLANE_U] = frame->data[1];
00529         rawimg->planes[VPX_PLANE_V] = frame->data[2];
00530         rawimg->stride[VPX_PLANE_Y] = frame->linesize[0];
00531         rawimg->stride[VPX_PLANE_U] = frame->linesize[1];
00532         rawimg->stride[VPX_PLANE_V] = frame->linesize[2];
00533         timestamp                   = frame->pts;
00534     }
00535 
00536     res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp,
00537                            avctx->ticks_per_frame, 0, ctx->deadline);
00538     if (res != VPX_CODEC_OK) {
00539         log_encoder_error(avctx, "Error encoding frame");
00540         return AVERROR_INVALIDDATA;
00541     }
00542     coded_size = queue_frames(avctx, buf, buf_size, avctx->coded_frame);
00543 
00544     if (!frame && avctx->flags & CODEC_FLAG_PASS1) {
00545         unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
00546 
00547         avctx->stats_out = av_malloc(b64_size);
00548         if (!avctx->stats_out) {
00549             av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%d bytes) failed\n",
00550                    b64_size);
00551             return AVERROR(ENOMEM);
00552         }
00553         av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
00554                          ctx->twopass_stats.sz);
00555     }
00556     return coded_size;
00557 }
00558 
00559 #define OFFSET(x) offsetof(VP8Context, x)
00560 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
00561 static const AVOption options[] = {
00562     { "cpu-used",        "Quality/Speed ratio modifier",           OFFSET(cpu_used),        AV_OPT_TYPE_INT, {INT_MIN}, INT_MIN, INT_MAX, VE},
00563     { "auto-alt-ref",    "Enable use of alternate reference "
00564                          "frames (2-pass only)",                   OFFSET(auto_alt_ref),    AV_OPT_TYPE_INT, {-1},      -1,      1,       VE},
00565     { "lag-in-frames",   "Number of frames to look ahead for "
00566                          "alternate reference frame selection",    OFFSET(lag_in_frames),   AV_OPT_TYPE_INT, {-1},      -1,      INT_MAX, VE},
00567     { "arnr-maxframes",  "altref noise reduction max frame count", OFFSET(arnr_max_frames), AV_OPT_TYPE_INT, {-1},      -1,      INT_MAX, VE},
00568     { "arnr-strength",   "altref noise reduction filter strength", OFFSET(arnr_strength),   AV_OPT_TYPE_INT, {-1},      -1,      INT_MAX, VE},
00569     { "arnr-type",       "altref noise reduction filter type",     OFFSET(arnr_type),       AV_OPT_TYPE_INT, {-1},      -1,      INT_MAX, VE, "arnr_type"},
00570     { "backward",        NULL, 0, AV_OPT_TYPE_CONST, {1}, 0, 0, VE, "arnr_type" },
00571     { "forward",         NULL, 0, AV_OPT_TYPE_CONST, {2}, 0, 0, VE, "arnr_type" },
00572     { "centered",        NULL, 0, AV_OPT_TYPE_CONST, {3}, 0, 0, VE, "arnr_type" },
00573     { "deadline",        "Time to spend encoding, in microseconds.", OFFSET(deadline),      AV_OPT_TYPE_INT, {VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"},
00574     { "best",            NULL, 0, AV_OPT_TYPE_CONST, {VPX_DL_BEST_QUALITY}, 0, 0, VE, "quality"},
00575     { "good",            NULL, 0, AV_OPT_TYPE_CONST, {VPX_DL_GOOD_QUALITY}, 0, 0, VE, "quality"},
00576     { "realtime",        NULL, 0, AV_OPT_TYPE_CONST, {VPX_DL_REALTIME},     0, 0, VE, "quality"},
00577     { "error-resilient", "Error resilience configuration", OFFSET(error_resilient), AV_OPT_TYPE_FLAGS, {0}, INT_MIN, INT_MAX, VE, "er"},
00578 #ifdef VPX_ERROR_RESILIENT_DEFAULT
00579     { "default",         "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {VPX_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"},
00580     { "partitions",      "The frame partitions are independently decodable "
00581                          "by the bool decoder, meaning that partitions can be decoded even "
00582                          "though earlier partitions have been lost. Note that intra predicition"
00583                          " is still done over the partition boundary.",       0, AV_OPT_TYPE_CONST, {VPX_ERROR_RESILIENT_PARTITIONS}, 0, 0, VE, "er"},
00584 #endif
00585 {"speed", "", offsetof(VP8Context, cpu_used), AV_OPT_TYPE_INT, {.dbl = 3}, -16, 16, VE},
00586 {"quality", "", offsetof(VP8Context, deadline), AV_OPT_TYPE_INT, {.dbl = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"},
00587 {"vp8flags", "", offsetof(VP8Context, flags), FF_OPT_TYPE_FLAGS, {.dbl = 0}, 0, UINT_MAX, VE, "flags"},
00588 {"error_resilient", "enable error resilience", 0, FF_OPT_TYPE_CONST, {.dbl = VP8F_ERROR_RESILIENT}, INT_MIN, INT_MAX, VE, "flags"},
00589 {"altref", "enable use of alternate reference frames (VP8/2-pass only)", 0, FF_OPT_TYPE_CONST, {.dbl = VP8F_AUTO_ALT_REF}, INT_MIN, INT_MAX, VE, "flags"},
00590 {"arnr_max_frames", "altref noise reduction max frame count", offsetof(VP8Context, arnr_max_frames), AV_OPT_TYPE_INT, {.dbl = 0}, 0, 15, VE},
00591 {"arnr_strength", "altref noise reduction filter strength", offsetof(VP8Context, arnr_strength), AV_OPT_TYPE_INT, {.dbl = 3}, 0, 6, VE},
00592 {"arnr_type", "altref noise reduction filter type", offsetof(VP8Context, arnr_type), AV_OPT_TYPE_INT, {.dbl = 3}, 1, 3, VE},
00593 #if FF_API_X264_GLOBAL_OPTS
00594 {"rc_lookahead", "Number of frames to look ahead for alternate reference frame selection", offsetof(VP8Context, lag_in_frames), AV_OPT_TYPE_INT, {.dbl = -1}, -1, 25, VE},
00595 {"crf", "Select the quality for constant quality mode", offsetof(VP8Context, crf), AV_OPT_TYPE_INT, {.dbl = -1}, -1, 63, VE},
00596 #else
00597 {"rc_lookahead", "Number of frames to look ahead for alternate reference frame selection", offsetof(VP8Context, lag_in_frames), AV_OPT_TYPE_INT, {.dbl = 25}, 0, 25, VE},
00598 {"crf", "Select the quality for constant quality mode", offsetof(VP8Context, crf), AV_OPT_TYPE_INT, {.dbl = 0}, 0, 63, VE},
00599 #endif
00600 {NULL}
00601 };
00602 
00603 static const AVClass class = {
00604     .class_name = "libvpx encoder",
00605     .item_name  = av_default_item_name,
00606     .option     = options,
00607     .version    = LIBAVUTIL_VERSION_INT,
00608 };
00609 
00610 static const AVCodecDefault defaults[] = {
00611     { "qmin",             "-1" },
00612     { "qmax",             "-1" },
00613     { "g",                "-1" },
00614     { "keyint_min",       "-1" },
00615     { NULL },
00616 };
00617 
00618 AVCodec ff_libvpx_encoder = {
00619     .name           = "libvpx",
00620     .type           = AVMEDIA_TYPE_VIDEO,
00621     .id             = CODEC_ID_VP8,
00622     .priv_data_size = sizeof(VP8Context),
00623     .init           = vp8_init,
00624     .encode         = vp8_encode,
00625     .close          = vp8_free,
00626     .capabilities   = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
00627     .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
00628     .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"),
00629     .priv_class = &class,
00630     .defaults       = defaults,
00631 };