Add Dirac support through libschroedinger.
[ffmpeg.git] / libavcodec / libschroedingerenc.c
1 /*
2  * Dirac encoder support via Schroedinger libraries
3  * Copyright (c) 2008 BBC, Anuradha Suraparaju <asuraparaju at gmail dot com >
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23 * @file libschroedingerenc.c
24 * Dirac encoder support via libschroedinger-1.0 libraries. More details about
25 * the Schroedinger project can be found at http://www.diracvideo.org/.
26 * The library implements Dirac Specification Version 2.2
27 * (http://dirac.sourceforge.net/specification.html).
28 */
29
30 #undef NDEBUG
31 #include <assert.h>
32
33 #include <schroedinger/schro.h>
34 #include <schroedinger/schrodebug.h>
35 #include <schroedinger/schrovideoformat.h>
36
37 #include "avcodec.h"
38 #include "libdirac_libschro.h"
39 #include "libschroedinger.h"
40
41
42 /** libschroedinger encoder private data */
43 typedef struct FfmpegSchroEncoderParams
44 {
45     /** Schroedinger video format */
46     SchroVideoFormat *format;
47
48     /** Schroedinger frame format */
49     SchroFrameFormat frame_format;
50
51     /** frame being encoded */
52     AVFrame picture;
53
54     /** frame size */
55     int frame_size;
56
57     /** Schroedinger encoder handle*/
58     SchroEncoder* encoder;
59
60     /** queue storing encoded frames */
61     FfmpegDiracSchroQueue enc_frame_queue;
62
63     /** end of sequence signalled */
64     int eos_signalled;
65
66     /** end of sequence pulled */
67     int eos_pulled;
68 } FfmpegSchroEncoderParams;
69
70 /**
71 * Works out Schro-compatible chroma format.
72 */
73 static int SetSchroChromaFormat(AVCodecContext *avccontext)
74 {
75     int num_formats = sizeof(ffmpeg_schro_pixel_format_map) /
76                       sizeof(ffmpeg_schro_pixel_format_map[0]);
77     int idx;
78
79     FfmpegSchroEncoderParams* p_schro_params = avccontext->priv_data;
80
81     for (idx = 0; idx < num_formats; ++idx) {
82         if (ffmpeg_schro_pixel_format_map[idx].ff_pix_fmt ==
83                                                        avccontext->pix_fmt) {
84             p_schro_params->format->chroma_format =
85                             ffmpeg_schro_pixel_format_map[idx].schro_pix_fmt;
86             return 0;
87         }
88     }
89
90     av_log (avccontext, AV_LOG_ERROR,
91             "This codec currently only supports planar YUV 4:2:0, 4:2:2"
92             " and 4:4:4 formats.\n");
93
94     return -1;
95 }
96
97 static int libschroedinger_encode_init(AVCodecContext *avccontext)
98 {
99     FfmpegSchroEncoderParams* p_schro_params = avccontext->priv_data;
100     SchroVideoFormatEnum preset;
101
102     /* Initialize the libraries that libschroedinger depends on. */
103     schro_init();
104
105     /* Create an encoder object. */
106     p_schro_params->encoder = schro_encoder_new();
107
108     if (!p_schro_params->encoder) {
109         av_log(avccontext, AV_LOG_ERROR,
110                "Unrecoverable Error: schro_encoder_new failed. ");
111         return -1;
112     }
113
114     /* Initialize the format. */
115     preset = ff_get_schro_video_format_preset(avccontext);
116     p_schro_params->format =
117                     schro_encoder_get_video_format(p_schro_params->encoder);
118     schro_video_format_set_std_video_format (p_schro_params->format, preset);
119     p_schro_params->format->width = avccontext->width;
120     p_schro_params->format->height = avccontext->height;
121
122     if (SetSchroChromaFormat(avccontext) == -1)
123         return -1;
124
125     if (ff_get_schro_frame_format(p_schro_params->format->chroma_format,
126                                   &p_schro_params->frame_format) == -1) {
127         av_log (avccontext, AV_LOG_ERROR,
128                 "This codec currently supports only planar YUV 4:2:0, 4:2:2"
129                 " and 4:4:4 formats.\n");
130         return -1;
131     }
132
133     p_schro_params->format->frame_rate_numerator   = avccontext->time_base.den;
134     p_schro_params->format->frame_rate_denominator = avccontext->time_base.num;
135
136     p_schro_params->frame_size = avpicture_get_size(avccontext->pix_fmt,
137                                                     avccontext->width,
138                                                     avccontext->height);
139
140     avccontext->coded_frame = &p_schro_params->picture;
141
142     if (avccontext->gop_size == 0){
143         schro_encoder_setting_set_double (p_schro_params->encoder,
144                                           "gop_structure",
145                                           SCHRO_ENCODER_GOP_INTRA_ONLY);
146     }
147     else {
148         schro_encoder_setting_set_double (p_schro_params->encoder,
149                                           "gop_structure",
150                                           SCHRO_ENCODER_GOP_BIREF);
151         avccontext->has_b_frames = 1;
152     }
153
154     /* FIXME - Need to handle SCHRO_ENCODER_RATE_CONTROL_LOW_DELAY. */
155     if (avccontext->flags & CODEC_FLAG_QSCALE) {
156         if (avccontext->global_quality == 0) {
157             /* lossless coding */
158             schro_encoder_setting_set_double (p_schro_params->encoder,
159                                           "rate_control",
160                                           SCHRO_ENCODER_RATE_CONTROL_LOSSLESS);
161         } else {
162             int noise_threshold;
163             schro_encoder_setting_set_double (p_schro_params->encoder,
164                           "rate_control",
165                           SCHRO_ENCODER_RATE_CONTROL_CONSTANT_NOISE_THRESHOLD);
166
167             noise_threshold = avccontext->global_quality/FF_QP2LAMBDA;
168             if (noise_threshold > 100)
169                 noise_threshold = 100;
170             schro_encoder_setting_set_double (p_schro_params->encoder,
171                                               "noise_threshold",
172                                               noise_threshold);
173         }
174     }
175     else {
176         schro_encoder_setting_set_double ( p_schro_params->encoder,
177                                "rate_control",
178                                SCHRO_ENCODER_RATE_CONTROL_CONSTANT_BITRATE);
179
180         schro_encoder_setting_set_double (p_schro_params->encoder,
181                                           "bitrate",
182                                           avccontext->bit_rate);
183
184     }
185
186     if (avccontext->flags & CODEC_FLAG_INTERLACED_ME) {
187         /* All material can be coded as interlaced or progressive
188            irrespective of the type of source material. */
189         schro_encoder_setting_set_double (p_schro_params->encoder,
190                                             "interlaced_coding", 1);
191     }
192
193     /* FIXME: Signal range hardcoded to 8-bit data until both libschroedinger
194      * and libdirac support other bit-depth data. */
195     schro_video_format_set_std_signal_range(p_schro_params->format,
196                                             SCHRO_SIGNAL_RANGE_8BIT_VIDEO);
197
198
199     /* Hardcode motion vector precision to quarter pixel. */
200     schro_encoder_setting_set_double (p_schro_params->encoder,
201                                       "mv_precision", 2);
202
203     /* Set the encoder format. */
204     schro_encoder_set_video_format(p_schro_params->encoder,
205                                    p_schro_params->format);
206
207     /* Set the debug level. */
208     schro_debug_set_level (avccontext->debug);
209
210     schro_encoder_start (p_schro_params->encoder);
211
212     /* Initialize the encoded frame queue. */
213     ff_dirac_schro_queue_init (&p_schro_params->enc_frame_queue);
214     return 0 ;
215 }
216
217 static SchroFrame *libschroedinger_frame_from_data (AVCodecContext *avccontext,
218                                                     void *in_data)
219 {
220     FfmpegSchroEncoderParams* p_schro_params = avccontext->priv_data;
221     SchroFrame *in_frame;
222     /* Input line size may differ from what the codec supports. Especially
223      * when transcoding from one format to another. So use avpicture_layout
224      * to copy the frame. */
225     in_frame = schro_frame_new_and_alloc (NULL,
226                                           p_schro_params->frame_format,
227                                           p_schro_params->format->width,
228                                           p_schro_params->format->height);
229
230     avpicture_layout ((AVPicture *)in_data, avccontext->pix_fmt,
231                       avccontext->width, avccontext->height,
232                       in_frame->components[0].data,
233                       p_schro_params->frame_size);
234
235     return in_frame;
236 }
237
238 static void SchroedingerFreeFrame(void *data)
239 {
240     FfmpegDiracSchroEncodedFrame *enc_frame = data;
241
242     av_freep (&(enc_frame->p_encbuf));
243     av_free(enc_frame);
244 }
245
246 static int libschroedinger_encode_frame(AVCodecContext *avccontext,
247                                         unsigned char *frame,
248                                         int buf_size, void *data)
249 {
250     int enc_size = 0;
251     FfmpegSchroEncoderParams* p_schro_params = avccontext->priv_data;
252     SchroEncoder *encoder = p_schro_params->encoder;
253     struct FfmpegDiracSchroEncodedFrame* p_frame_output = NULL;
254     int go = 1;
255     SchroBuffer *enc_buf;
256     int presentation_frame;
257     int parse_code;
258
259     if(data == NULL) {
260         /* Push end of sequence if not already signalled. */
261         if (!p_schro_params->eos_signalled) {
262             schro_encoder_end_of_stream(encoder);
263             p_schro_params->eos_signalled = 1;
264         }
265     } else {
266         /* Allocate frame data to schro input buffer. */
267         SchroFrame *in_frame = libschroedinger_frame_from_data (avccontext,
268                                                                 data);
269         /* Load next frame. */
270         schro_encoder_push_frame(encoder, in_frame);
271     }
272
273     if (p_schro_params->eos_pulled)
274         go = 0;
275
276     /* Now check to see if we have any output from the encoder. */
277     while (go) {
278         SchroStateEnum  state;
279         state = schro_encoder_wait(encoder);
280         switch (state)
281         {
282         case SCHRO_STATE_HAVE_BUFFER:
283         case SCHRO_STATE_END_OF_STREAM:
284             enc_buf = schro_encoder_pull (encoder,
285                                           &presentation_frame);
286             assert (enc_buf->length > 0);
287             assert (enc_buf->length <= buf_size);
288
289             /* Create output frame. */
290             p_frame_output = av_mallocz(sizeof(FfmpegDiracSchroEncodedFrame));
291             /* Set output data. */
292             p_frame_output->size     = enc_buf->length;
293             p_frame_output->p_encbuf = av_malloc(enc_buf->length);
294             memcpy(p_frame_output->p_encbuf, enc_buf->data, enc_buf->length);
295
296             parse_code = enc_buf->data[4];
297             if (SCHRO_PARSE_CODE_IS_INTRA(parse_code) &&
298                 SCHRO_PARSE_CODE_IS_REFERENCE(parse_code)) {
299                 p_frame_output->key_frame = 1;
300             }
301
302             /* Parse the coded frame number from the bitstream. Bytes 14
303              * through 17 represesent the frame number. */
304             if (SCHRO_PARSE_CODE_IS_PICTURE(parse_code))
305             {
306                 assert (enc_buf->length >= 17);
307                 p_frame_output->frame_num = (enc_buf->data[13] << 24) +
308                                             (enc_buf->data[14] << 16) +
309                                             (enc_buf->data[15] <<  8) +
310                                              enc_buf->data[16];
311             }
312
313             ff_dirac_schro_queue_push_back (&p_schro_params->enc_frame_queue,
314                                             p_frame_output);
315             schro_buffer_unref (enc_buf);
316
317             if (state == SCHRO_STATE_END_OF_STREAM) {
318                 p_schro_params->eos_pulled = 1;
319                    go = 0;
320             }
321             break;
322
323         case SCHRO_STATE_NEED_FRAME:
324             go = 0;
325             break;
326
327         case SCHRO_STATE_AGAIN:
328             break;
329
330         default:
331             av_log(avccontext, AV_LOG_ERROR, "Unknown Schro Encoder state\n");
332             return -1;
333         }
334     }
335
336     /* Copy 'next' frame in queue. */
337     p_frame_output =
338                ff_dirac_schro_queue_pop (&p_schro_params->enc_frame_queue);
339
340     if (p_frame_output == NULL)
341         return 0;
342
343     memcpy(frame, p_frame_output->p_encbuf, p_frame_output->size);
344     avccontext->coded_frame->key_frame = p_frame_output->key_frame;
345     /* Use the frame number of the encoded frame as the pts. It is OK to
346      * do so since Dirac is a constant frame rate codec. It expects input
347      * to be of constant frame rate. */
348     avccontext->coded_frame->pts = p_frame_output->frame_num;
349     enc_size = p_frame_output->size;
350
351     /* free frame */
352     SchroedingerFreeFrame (p_frame_output);
353
354     return enc_size;
355 }
356
357
358 static int libschroedinger_encode_close(AVCodecContext *avccontext)
359 {
360
361     FfmpegSchroEncoderParams* p_schro_params = avccontext->priv_data;
362
363      /* Close the encoder. */
364     schro_encoder_free(p_schro_params->encoder);
365
366     /* Free data in the output frame queue. */
367     ff_dirac_schro_queue_free (&p_schro_params->enc_frame_queue,
368                                SchroedingerFreeFrame);
369
370     /* Free the video format structure. */
371     av_freep(&p_schro_params->format);
372
373     return 0 ;
374 }
375
376
377 AVCodec libschroedinger_encoder = {
378     "libschroedinger",
379     CODEC_TYPE_VIDEO,
380     CODEC_ID_DIRAC,
381     sizeof(FfmpegSchroEncoderParams),
382     libschroedinger_encode_init,
383     libschroedinger_encode_frame,
384     libschroedinger_encode_close,
385    .capabilities= CODEC_CAP_DELAY,
386    .pix_fmts= (enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV444P, -1},
387 };