libavcodec/libdiracenc.c
690bfceb
 /*
  * Dirac encoding support via libdirac library
  * Copyright (c) 2005 BBC, Andrew Kennedy <dirac at rd dot bbc dot co dot uk>
  * Copyright (c) 2006-2008 BBC, Anuradha Suraparaju <asuraparaju 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
  */
 
 /**
ba87f080
 * @file
690bfceb
 * Dirac encoding support via libdirac library; more details about the
 * Dirac project can be found at http://dirac.sourceforge.net/.
 * The libdirac_encoder library implements Dirac specification version 2.2
 * (http://dirac.sourceforge.net/specification.html).
 */
 
 #include "libdirac_libschro.h"
 #include "libdirac.h"
 
 #undef NDEBUG
 #include <assert.h>
 
 
 #include <libdirac_encoder/dirac_encoder.h>
 
 /** Dirac encoder private data */
45235d69
 typedef struct DiracEncoderParams {
690bfceb
     /** Dirac encoder context */
     dirac_encoder_context_t enc_ctx;
 
     /** frame being encoded */
     AVFrame picture;
 
     /** frame size */
     int frame_size;
 
     /** Dirac encoder handle */
     dirac_encoder_t* p_encoder;
 
     /** input frame buffer */
     unsigned char *p_in_frame_buf;
 
f73b2040
     /** buffer to store encoder output before writing it to the frame queue */
     unsigned char *enc_buf;
 
     /** size of encoder buffer */
     int enc_buf_size;
 
690bfceb
     /** queue storing encoded frames */
45235d69
     DiracSchroQueue enc_frame_queue;
690bfceb
 
     /** end of sequence signalled by user, 0 - false, 1 - true */
     int eos_signalled;
 
     /** end of sequence returned by encoder, 0 - false, 1 - true */
     int eos_pulled;
45235d69
 } DiracEncoderParams;
690bfceb
 
 /**
 * Works out Dirac-compatible chroma format.
 */
 static dirac_chroma_t GetDiracChromaFormat(enum PixelFormat ff_pix_fmt)
 {
45235d69
     int num_formats = sizeof(dirac_pixel_format_map) /
                       sizeof(dirac_pixel_format_map[0]);
690bfceb
     int idx;
 
c6438000
     for (idx = 0; idx < num_formats; ++idx)
45235d69
         if (dirac_pixel_format_map[idx].ff_pix_fmt == ff_pix_fmt)
             return dirac_pixel_format_map[idx].dirac_pix_fmt;
690bfceb
     return formatNK;
 }
 
 /**
 * Dirac video preset table. Ensure that this tables matches up correctly
 * with the ff_dirac_schro_video_format_info table in libdirac_libschro.c.
 */
 static const VideoFormat ff_dirac_video_formats[]={
     VIDEO_FORMAT_CUSTOM           ,
     VIDEO_FORMAT_QSIF525          ,
     VIDEO_FORMAT_QCIF             ,
     VIDEO_FORMAT_SIF525           ,
     VIDEO_FORMAT_CIF              ,
     VIDEO_FORMAT_4SIF525          ,
     VIDEO_FORMAT_4CIF             ,
     VIDEO_FORMAT_SD_480I60        ,
     VIDEO_FORMAT_SD_576I50        ,
     VIDEO_FORMAT_HD_720P60        ,
     VIDEO_FORMAT_HD_720P50        ,
     VIDEO_FORMAT_HD_1080I60       ,
     VIDEO_FORMAT_HD_1080I50       ,
     VIDEO_FORMAT_HD_1080P60       ,
     VIDEO_FORMAT_HD_1080P50       ,
     VIDEO_FORMAT_DIGI_CINEMA_2K24 ,
     VIDEO_FORMAT_DIGI_CINEMA_4K24 ,
 };
 
 /**
 * Returns the video format preset matching the input video dimensions and
 * time base.
 */
0ebe3b8e
 static VideoFormat GetDiracVideoFormatPreset(AVCodecContext *avccontext)
690bfceb
 {
     unsigned int num_formats = sizeof(ff_dirac_video_formats) /
                                sizeof(ff_dirac_video_formats[0]);
 
0ebe3b8e
     unsigned int idx = ff_dirac_schro_get_video_format_idx(avccontext);
690bfceb
 
     return (idx < num_formats) ?
                  ff_dirac_video_formats[idx] : VIDEO_FORMAT_CUSTOM;
 }
 
5ef251e5
 static av_cold int libdirac_encode_init(AVCodecContext *avccontext)
690bfceb
 {
 
45235d69
     DiracEncoderParams* p_dirac_params = avccontext->priv_data;
690bfceb
     int no_local = 1;
0ebe3b8e
     int verbose  = avccontext->debug;
690bfceb
     VideoFormat preset;
 
     /* get Dirac preset */
     preset = GetDiracVideoFormatPreset(avccontext);
 
     /* initialize the encoder context */
0ebe3b8e
     dirac_encoder_context_init(&(p_dirac_params->enc_ctx), preset);
690bfceb
 
0ebe3b8e
     p_dirac_params->enc_ctx.src_params.chroma = GetDiracChromaFormat(avccontext->pix_fmt);
690bfceb
 
     if (p_dirac_params->enc_ctx.src_params.chroma == formatNK) {
0ebe3b8e
         av_log(avccontext, AV_LOG_ERROR,
                "Unsupported pixel format %d. This codec supports only "
                "Planar YUV formats (yuv420p, yuv422p, yuv444p\n",
                avccontext->pix_fmt);
690bfceb
         return -1;
     }
 
0ebe3b8e
     p_dirac_params->enc_ctx.src_params.frame_rate.numerator   = avccontext->time_base.den;
     p_dirac_params->enc_ctx.src_params.frame_rate.denominator = avccontext->time_base.num;
690bfceb
 
     p_dirac_params->enc_ctx.src_params.width  = avccontext->width;
     p_dirac_params->enc_ctx.src_params.height = avccontext->height;
 
     p_dirac_params->frame_size = avpicture_get_size(avccontext->pix_fmt,
                                                     avccontext->width,
                                                     avccontext->height);
 
     avccontext->coded_frame = &p_dirac_params->picture;
 
     if (no_local) {
         p_dirac_params->enc_ctx.decode_flag = 0;
         p_dirac_params->enc_ctx.instr_flag  = 0;
     } else {
         p_dirac_params->enc_ctx.decode_flag = 1;
         p_dirac_params->enc_ctx.instr_flag  = 1;
     }
 
     /* Intra-only sequence */
7c809dc3
     if (!avccontext->gop_size) {
690bfceb
         p_dirac_params->enc_ctx.enc_params.num_L1 = 0;
d7c96d66
         if (avccontext->coder_type == FF_CODER_TYPE_VLC)
             p_dirac_params->enc_ctx.enc_params.using_ac = 0;
     } else
690bfceb
         avccontext->has_b_frames = 1;
 
     if (avccontext->flags & CODEC_FLAG_QSCALE) {
7c809dc3
         if (avccontext->global_quality) {
0ebe3b8e
             p_dirac_params->enc_ctx.enc_params.qf = avccontext->global_quality
                                                     / (FF_QP2LAMBDA * 10.0);
690bfceb
             /* if it is not default bitrate then send target rate. */
             if (avccontext->bit_rate >= 1000 &&
735a3804
                 avccontext->bit_rate != 200000)
0ebe3b8e
                 p_dirac_params->enc_ctx.enc_params.trate = avccontext->bit_rate
                                                            / 1000;
690bfceb
         } else
             p_dirac_params->enc_ctx.enc_params.lossless = 1;
     } else if (avccontext->bit_rate >= 1000)
         p_dirac_params->enc_ctx.enc_params.trate = avccontext->bit_rate / 1000;
 
     if ((preset > VIDEO_FORMAT_QCIF || preset < VIDEO_FORMAT_QSIF525) &&
0ebe3b8e
          avccontext->bit_rate == 200000)
690bfceb
         p_dirac_params->enc_ctx.enc_params.trate = 0;
 
735a3804
     if (avccontext->flags & CODEC_FLAG_INTERLACED_ME)
690bfceb
         /* all material can be coded as interlaced or progressive
          * irrespective of the type of source material */
         p_dirac_params->enc_ctx.enc_params.picture_coding_mode = 1;
 
0ebe3b8e
     p_dirac_params->p_encoder = dirac_encoder_init(&(p_dirac_params->enc_ctx),
                                                    verbose);
690bfceb
 
     if (!p_dirac_params->p_encoder) {
         av_log(avccontext, AV_LOG_ERROR,
                "Unrecoverable Error: dirac_encoder_init failed. ");
         return EXIT_FAILURE;
     }
 
     /* allocate enough memory for the incoming data */
     p_dirac_params->p_in_frame_buf = av_malloc(p_dirac_params->frame_size);
 
     /* initialize the encoded frame queue */
     ff_dirac_schro_queue_init(&p_dirac_params->enc_frame_queue);
 
0ebe3b8e
     return 0;
690bfceb
 }
 
0ebe3b8e
 static void DiracFreeFrame(void *data)
690bfceb
 {
45235d69
     DiracSchroEncodedFrame *enc_frame = data;
690bfceb
 
0ebe3b8e
     av_freep(&(enc_frame->p_encbuf));
690bfceb
     av_free(enc_frame);
 }
 
 static int libdirac_encode_frame(AVCodecContext *avccontext,
                                  unsigned char *frame,
                                  int buf_size, void *data)
 {
     int enc_size = 0;
     dirac_encoder_state_t state;
45235d69
     DiracEncoderParams     *p_dirac_params      = avccontext->priv_data;
     DiracSchroEncodedFrame *p_frame_output      = NULL;
     DiracSchroEncodedFrame *p_next_output_frame = NULL;
690bfceb
     int go = 1;
f73b2040
     int last_frame_in_sequence = 0;
690bfceb
 
7c809dc3
     if (!data) {
690bfceb
         /* push end of sequence if not already signalled */
         if (!p_dirac_params->eos_signalled) {
0ebe3b8e
             dirac_encoder_end_sequence(p_dirac_params->p_encoder);
690bfceb
             p_dirac_params->eos_signalled = 1;
         }
     } else {
 
         /* Allocate frame data to Dirac input buffer.
          * Input line size may differ from what the codec supports,
          * especially when transcoding from one format to another.
          * So use avpicture_layout to copy the frame. */
0ebe3b8e
         avpicture_layout((AVPicture *)data, avccontext->pix_fmt,
                          avccontext->width, avccontext->height,
                          p_dirac_params->p_in_frame_buf,
                          p_dirac_params->frame_size);
690bfceb
 
         /* load next frame */
0ebe3b8e
         if (dirac_encoder_load(p_dirac_params->p_encoder,
                                p_dirac_params->p_in_frame_buf,
                                p_dirac_params->frame_size) < 0) {
690bfceb
             av_log(avccontext, AV_LOG_ERROR, "Unrecoverable Encoder Error."
                    " dirac_encoder_load failed...\n");
             return -1;
         }
     }
 
     if (p_dirac_params->eos_pulled)
         go = 0;
 
0ebe3b8e
     while (go) {
690bfceb
         p_dirac_params->p_encoder->enc_buf.buffer = frame;
         p_dirac_params->p_encoder->enc_buf.size   = buf_size;
         /* process frame */
0ebe3b8e
         state = dirac_encoder_output(p_dirac_params->p_encoder);
690bfceb
 
0ebe3b8e
         switch (state) {
690bfceb
         case ENC_STATE_AVAIL:
         case ENC_STATE_EOS:
0ebe3b8e
             assert(p_dirac_params->p_encoder->enc_buf.size > 0);
690bfceb
 
f73b2040
             /* All non-frame data is prepended to actual frame data to
              * be able to set the pts correctly. So we don't write data
              * to the frame output queue until we actually have a frame
              */
 
0ebe3b8e
             p_dirac_params->enc_buf = av_realloc(p_dirac_params->enc_buf,
                                                  p_dirac_params->enc_buf_size +
                                                  p_dirac_params->p_encoder->enc_buf.size);
f73b2040
             memcpy(p_dirac_params->enc_buf + p_dirac_params->enc_buf_size,
690bfceb
                    p_dirac_params->p_encoder->enc_buf.buffer,
                    p_dirac_params->p_encoder->enc_buf.size);
 
0ebe3b8e
             p_dirac_params->enc_buf_size += p_dirac_params->p_encoder->enc_buf.size;
f73b2040
 
             if (state == ENC_STATE_EOS) {
                 p_dirac_params->eos_pulled = 1;
                 go = 0;
             }
 
             /* If non-frame data, don't output it until it we get an
              * encoded frame back from the encoder. */
             if (p_dirac_params->p_encoder->enc_pparams.pnum == -1)
                 break;
690bfceb
 
f73b2040
             /* create output frame */
45235d69
             p_frame_output = av_mallocz(sizeof(DiracSchroEncodedFrame));
f73b2040
             /* set output data */
0ebe3b8e
             p_frame_output->size      = p_dirac_params->enc_buf_size;
             p_frame_output->p_encbuf  = p_dirac_params->enc_buf;
             p_frame_output->frame_num = p_dirac_params->p_encoder->enc_pparams.pnum;
690bfceb
 
             if (p_dirac_params->p_encoder->enc_pparams.ptype == INTRA_PICTURE &&
                 p_dirac_params->p_encoder->enc_pparams.rtype == REFERENCE_PICTURE)
                 p_frame_output->key_frame = 1;
 
0ebe3b8e
             ff_dirac_schro_queue_push_back(&p_dirac_params->enc_frame_queue,
                                            p_frame_output);
690bfceb
 
f73b2040
             p_dirac_params->enc_buf_size = 0;
             p_dirac_params->enc_buf      = NULL;
690bfceb
             break;
 
         case ENC_STATE_BUFFER:
             go = 0;
             break;
 
         case ENC_STATE_INVALID:
             av_log(avccontext, AV_LOG_ERROR,
                    "Unrecoverable Dirac Encoder Error. Quitting...\n");
             return -1;
 
         default:
             av_log(avccontext, AV_LOG_ERROR, "Unknown Dirac Encoder state\n");
             return -1;
         }
     }
 
     /* copy 'next' frame in queue */
f73b2040
 
0ebe3b8e
     if (p_dirac_params->enc_frame_queue.size == 1 && p_dirac_params->eos_pulled)
f73b2040
         last_frame_in_sequence = 1;
 
0ebe3b8e
     p_next_output_frame = ff_dirac_schro_queue_pop(&p_dirac_params->enc_frame_queue);
690bfceb
 
7c809dc3
     if (!p_next_output_frame)
690bfceb
         return 0;
 
     memcpy(frame, p_next_output_frame->p_encbuf, p_next_output_frame->size);
     avccontext->coded_frame->key_frame = p_next_output_frame->key_frame;
     /* Use the frame number of the encoded frame as the pts. It is OK to do
      * so since Dirac is a constant framerate codec. It expects input to be
      * of constant framerate. */
     avccontext->coded_frame->pts = p_next_output_frame->frame_num;
     enc_size = p_next_output_frame->size;
 
f73b2040
     /* Append the end of sequence information to the last frame in the
      * sequence. */
0ebe3b8e
     if (last_frame_in_sequence && p_dirac_params->enc_buf_size > 0) {
         memcpy(frame + enc_size, p_dirac_params->enc_buf,
                p_dirac_params->enc_buf_size);
f73b2040
         enc_size += p_dirac_params->enc_buf_size;
0ebe3b8e
         av_freep(&p_dirac_params->enc_buf);
f73b2040
         p_dirac_params->enc_buf_size = 0;
     }
 
690bfceb
     /* free frame */
     DiracFreeFrame(p_next_output_frame);
 
     return enc_size;
 }
 
5ef251e5
 static av_cold int libdirac_encode_close(AVCodecContext *avccontext)
690bfceb
 {
45235d69
     DiracEncoderParams *p_dirac_params = avccontext->priv_data;
690bfceb
 
     /* close the encoder */
0ebe3b8e
     dirac_encoder_close(p_dirac_params->p_encoder);
690bfceb
 
     /* free data in the output frame queue */
     ff_dirac_schro_queue_free(&p_dirac_params->enc_frame_queue,
                               DiracFreeFrame);
 
f73b2040
     /* free the encoder buffer */
     if (p_dirac_params->enc_buf_size)
         av_freep(&p_dirac_params->enc_buf);
 
690bfceb
     /* free the input frame buffer */
     av_freep(&p_dirac_params->p_in_frame_buf);
 
0ebe3b8e
     return 0;
690bfceb
 }
 
 
e7e2df27
 AVCodec ff_libdirac_encoder = {
ec6402b7
     .name           = "libdirac",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = CODEC_ID_DIRAC,
45235d69
     .priv_data_size = sizeof(DiracEncoderParams),
ec6402b7
     .init           = libdirac_encode_init,
     .encode         = libdirac_encode_frame,
     .close          = libdirac_encode_close,
0ebe3b8e
    .capabilities = CODEC_CAP_DELAY,
2ba83017
    .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_NONE},
0ebe3b8e
    .long_name = NULL_IF_CONFIG_SMALL("libdirac Dirac 2.2"),
 };