94033cc2562f96e191947075cc9fa22ca3c7053a
[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 libavcodec/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     /** Schroedinger video format */
45     SchroVideoFormat *format;
46
47     /** Schroedinger frame format */
48     SchroFrameFormat frame_format;
49
50     /** frame being encoded */
51     AVFrame picture;
52
53     /** frame size */
54     int frame_size;
55
56     /** Schroedinger encoder handle*/
57     SchroEncoder* encoder;
58
59     /** buffer to store encoder output before writing it to the frame queue*/
60     unsigned char *enc_buf;
61
62     /** Size of encoder buffer*/
63     int enc_buf_size;
64
65     /** queue storing encoded frames */
66     FfmpegDiracSchroQueue enc_frame_queue;
67
68     /** end of sequence signalled */
69     int eos_signalled;
70
71     /** end of sequence pulled */
72     int eos_pulled;
73 } FfmpegSchroEncoderParams;
74
75 /**
76 * Works out Schro-compatible chroma format.
77 */
78 static int SetSchroChromaFormat(AVCodecContext *avccontext)
79 {
80     int num_formats = sizeof(ffmpeg_schro_pixel_format_map) /
81                       sizeof(ffmpeg_schro_pixel_format_map[0]);
82     int idx;
83
84     FfmpegSchroEncoderParams* p_schro_params = avccontext->priv_data;
85
86     for (idx = 0; idx < num_formats; ++idx) {
87         if (ffmpeg_schro_pixel_format_map[idx].ff_pix_fmt ==
88             avccontext->pix_fmt) {
89             p_schro_params->format->chroma_format =
90                             ffmpeg_schro_pixel_format_map[idx].schro_pix_fmt;
91             return 0;
92         }
93     }
94
95     av_log(avccontext, AV_LOG_ERROR,
96            "This codec currently only supports planar YUV 4:2:0, 4:2:2"
97            " and 4:4:4 formats.\n");
98
99     return -1;
100 }
101
102 static int libschroedinger_encode_init(AVCodecContext *avccontext)
103 {
104     FfmpegSchroEncoderParams* p_schro_params = avccontext->priv_data;
105     SchroVideoFormatEnum preset;
106
107     /* Initialize the libraries that libschroedinger depends on. */
108     schro_init();
109
110     /* Create an encoder object. */
111     p_schro_params->encoder = schro_encoder_new();
112
113     if (!p_schro_params->encoder) {
114         av_log(avccontext, AV_LOG_ERROR,
115                "Unrecoverable Error: schro_encoder_new failed. ");
116         return -1;
117     }
118
119     /* Initialize the format. */
120     preset = ff_get_schro_video_format_preset(avccontext);
121     p_schro_params->format =
122                     schro_encoder_get_video_format(p_schro_params->encoder);
123     schro_video_format_set_std_video_format(p_schro_params->format, preset);
124     p_schro_params->format->width  = avccontext->width;
125     p_schro_params->format->height = avccontext->height;
126
127     if (SetSchroChromaFormat(avccontext) == -1)
128         return -1;
129
130     if (ff_get_schro_frame_format(p_schro_params->format->chroma_format,
131                                   &p_schro_params->frame_format) == -1) {
132         av_log(avccontext, AV_LOG_ERROR,
133                "This codec currently supports only planar YUV 4:2:0, 4:2:2"
134                " and 4:4:4 formats.\n");
135         return -1;
136     }
137
138     p_schro_params->format->frame_rate_numerator   = avccontext->time_base.den;
139     p_schro_params->format->frame_rate_denominator = avccontext->time_base.num;
140
141     p_schro_params->frame_size = avpicture_get_size(avccontext->pix_fmt,
142                                                     avccontext->width,
143                                                     avccontext->height);
144
145     avccontext->coded_frame = &p_schro_params->picture;
146
147     if (!avccontext->gop_size) {
148         schro_encoder_setting_set_double(p_schro_params->encoder,
149                                          "gop_structure",
150                                          SCHRO_ENCODER_GOP_INTRA_ONLY);
151
152         if (avccontext->coder_type == FF_CODER_TYPE_VLC)
153             schro_encoder_setting_set_double(p_schro_params->encoder,
154                                              "enable_noarith", 1);
155     } else {
156         schro_encoder_setting_set_double(p_schro_params->encoder,
157                                          "gop_structure",
158                                          SCHRO_ENCODER_GOP_BIREF);
159         avccontext->has_b_frames = 1;
160     }
161
162     /* FIXME - Need to handle SCHRO_ENCODER_RATE_CONTROL_LOW_DELAY. */
163     if (avccontext->flags & CODEC_FLAG_QSCALE) {
164         if (!avccontext->global_quality) {
165             /* lossless coding */
166             schro_encoder_setting_set_double(p_schro_params->encoder,
167                                              "rate_control",
168                                              SCHRO_ENCODER_RATE_CONTROL_LOSSLESS);
169         } else {
170             int noise_threshold;
171             schro_encoder_setting_set_double(p_schro_params->encoder,
172                                              "rate_control",
173                                              SCHRO_ENCODER_RATE_CONTROL_CONSTANT_NOISE_THRESHOLD);
174
175             noise_threshold = avccontext->global_quality / FF_QP2LAMBDA;
176             if (noise_threshold > 100)
177                 noise_threshold = 100;
178             schro_encoder_setting_set_double(p_schro_params->encoder,
179                                              "noise_threshold",
180                                              noise_threshold);
181         }
182     } else {
183         schro_encoder_setting_set_double(p_schro_params->encoder,
184                                          "rate_control",
185                                          SCHRO_ENCODER_RATE_CONTROL_CONSTANT_BITRATE);
186
187         schro_encoder_setting_set_double(p_schro_params->encoder,
188                                          "bitrate",
189                                          avccontext->bit_rate);
190
191     }
192
193     if (avccontext->flags & CODEC_FLAG_INTERLACED_ME)
194         /* All material can be coded as interlaced or progressive
195            irrespective of the type of source material. */
196         schro_encoder_setting_set_double(p_schro_params->encoder,
197                                          "interlaced_coding", 1);
198
199     /* FIXME: Signal range hardcoded to 8-bit data until both libschroedinger
200      * and libdirac support other bit-depth data. */
201     schro_video_format_set_std_signal_range(p_schro_params->format,
202                                             SCHRO_SIGNAL_RANGE_8BIT_VIDEO);
203
204     /* Set the encoder format. */
205     schro_encoder_set_video_format(p_schro_params->encoder,
206                                    p_schro_params->format);
207
208     /* Set the debug level. */
209     schro_debug_set_level(avccontext->debug);
210
211     schro_encoder_start(p_schro_params->encoder);
212
213     /* Initialize the encoded frame queue. */
214     ff_dirac_schro_queue_init(&p_schro_params->enc_frame_queue);
215     return 0;
216 }
217
218 static SchroFrame *libschroedinger_frame_from_data(AVCodecContext *avccontext,
219                                                    void *in_data)
220 {
221     FfmpegSchroEncoderParams* p_schro_params = avccontext->priv_data;
222     SchroFrame *in_frame;
223     /* Input line size may differ from what the codec supports. Especially
224      * when transcoding from one format to another. So use avpicture_layout
225      * to copy the frame. */
226     in_frame = schro_frame_new_and_alloc(NULL,
227                                          p_schro_params->frame_format,
228                                          p_schro_params->format->width,
229                                          p_schro_params->format->height);
230
231     avpicture_layout((AVPicture *)in_data, avccontext->pix_fmt,
232                      avccontext->width, avccontext->height,
233                      in_frame->components[0].data,
234                      p_schro_params->frame_size);
235
236     return in_frame;
237 }
238
239 static void SchroedingerFreeFrame(void *data)
240 {
241     FfmpegDiracSchroEncodedFrame *enc_frame = data;
242
243     av_freep(&(enc_frame->p_encbuf));
244     av_free(enc_frame);
245 }
246
247 static int libschroedinger_encode_frame(AVCodecContext *avccontext,
248                                         unsigned char *frame,
249                                         int buf_size, void *data)
250 {
251     int enc_size = 0;
252     FfmpegSchroEncoderParams* p_schro_params = avccontext->priv_data;
253     SchroEncoder *encoder = p_schro_params->encoder;
254     struct FfmpegDiracSchroEncodedFrame* p_frame_output = NULL;
255     int go = 1;
256     SchroBuffer *enc_buf;
257     int presentation_frame;
258     int parse_code;
259     int last_frame_in_sequence = 0;
260
261     if (!data) {
262         /* Push end of sequence if not already signalled. */
263         if (!p_schro_params->eos_signalled) {
264             schro_encoder_end_of_stream(encoder);
265             p_schro_params->eos_signalled = 1;
266         }
267     } else {
268         /* Allocate frame data to schro input buffer. */
269         SchroFrame *in_frame = libschroedinger_frame_from_data(avccontext,
270                                                                data);
271         /* Load next frame. */
272         schro_encoder_push_frame(encoder, in_frame);
273     }
274
275     if (p_schro_params->eos_pulled)
276         go = 0;
277
278     /* Now check to see if we have any output from the encoder. */
279     while (go) {
280         SchroStateEnum state;
281         state = schro_encoder_wait(encoder);
282         switch (state) {
283         case SCHRO_STATE_HAVE_BUFFER:
284         case SCHRO_STATE_END_OF_STREAM:
285             enc_buf = schro_encoder_pull(encoder, &presentation_frame);
286             assert(enc_buf->length > 0);
287             assert(enc_buf->length <= buf_size);
288             parse_code = enc_buf->data[4];
289
290             /* All non-frame data is prepended to actual frame data to
291              * be able to set the pts correctly. So we don't write data
292              * to the frame output queue until we actually have a frame
293              */
294             p_schro_params->enc_buf = av_realloc(p_schro_params->enc_buf,
295                                                  p_schro_params->enc_buf_size + enc_buf->length);
296
297             memcpy(p_schro_params->enc_buf + p_schro_params->enc_buf_size,
298                    enc_buf->data, enc_buf->length);
299             p_schro_params->enc_buf_size += enc_buf->length;
300
301
302             if (state == SCHRO_STATE_END_OF_STREAM) {
303                 p_schro_params->eos_pulled = 1;
304                 go = 0;
305             }
306
307             if (!SCHRO_PARSE_CODE_IS_PICTURE(parse_code)) {
308                 schro_buffer_unref(enc_buf);
309                 break;
310             }
311
312             /* Create output frame. */
313             p_frame_output = av_mallocz(sizeof(FfmpegDiracSchroEncodedFrame));
314             /* Set output data. */
315             p_frame_output->size     = p_schro_params->enc_buf_size;
316             p_frame_output->p_encbuf = p_schro_params->enc_buf;
317             if (SCHRO_PARSE_CODE_IS_INTRA(parse_code) &&
318                 SCHRO_PARSE_CODE_IS_REFERENCE(parse_code))
319                 p_frame_output->key_frame = 1;
320
321             /* Parse the coded frame number from the bitstream. Bytes 14
322              * through 17 represesent the frame number. */
323                 p_frame_output->frame_num = (enc_buf->data[13] << 24) +
324                                             (enc_buf->data[14] << 16) +
325                                             (enc_buf->data[15] <<  8) +
326                                              enc_buf->data[16];
327
328             ff_dirac_schro_queue_push_back(&p_schro_params->enc_frame_queue,
329                                            p_frame_output);
330             p_schro_params->enc_buf_size = 0;
331             p_schro_params->enc_buf      = NULL;
332
333             schro_buffer_unref(enc_buf);
334
335             break;
336
337         case SCHRO_STATE_NEED_FRAME:
338             go = 0;
339             break;
340
341         case SCHRO_STATE_AGAIN:
342             break;
343
344         default:
345             av_log(avccontext, AV_LOG_ERROR, "Unknown Schro Encoder state\n");
346             return -1;
347         }
348     }
349
350     /* Copy 'next' frame in queue. */
351
352     if (p_schro_params->enc_frame_queue.size == 1 &&
353         p_schro_params->eos_pulled)
354         last_frame_in_sequence = 1;
355
356     p_frame_output = ff_dirac_schro_queue_pop(&p_schro_params->enc_frame_queue);
357
358     if (!p_frame_output)
359         return 0;
360
361     memcpy(frame, p_frame_output->p_encbuf, p_frame_output->size);
362     avccontext->coded_frame->key_frame = p_frame_output->key_frame;
363     /* Use the frame number of the encoded frame as the pts. It is OK to
364      * do so since Dirac is a constant frame rate codec. It expects input
365      * to be of constant frame rate. */
366     avccontext->coded_frame->pts = p_frame_output->frame_num;
367     enc_size = p_frame_output->size;
368
369     /* Append the end of sequence information to the last frame in the
370      * sequence. */
371     if (last_frame_in_sequence && p_schro_params->enc_buf_size > 0) {
372         memcpy(frame + enc_size, p_schro_params->enc_buf,
373                p_schro_params->enc_buf_size);
374         enc_size += p_schro_params->enc_buf_size;
375         av_freep(&p_schro_params->enc_buf);
376         p_schro_params->enc_buf_size = 0;
377     }
378
379     /* free frame */
380     SchroedingerFreeFrame(p_frame_output);
381
382     return enc_size;
383 }
384
385
386 static int libschroedinger_encode_close(AVCodecContext *avccontext)
387 {
388
389     FfmpegSchroEncoderParams* p_schro_params = avccontext->priv_data;
390
391     /* Close the encoder. */
392     schro_encoder_free(p_schro_params->encoder);
393
394     /* Free data in the output frame queue. */
395     ff_dirac_schro_queue_free(&p_schro_params->enc_frame_queue,
396                               SchroedingerFreeFrame);
397
398
399     /* Free the encoder buffer. */
400     if (p_schro_params->enc_buf_size)
401         av_freep(&p_schro_params->enc_buf);
402
403     /* Free the video format structure. */
404     av_freep(&p_schro_params->format);
405
406     return 0;
407 }
408
409
410 AVCodec libschroedinger_encoder = {
411     "libschroedinger",
412     CODEC_TYPE_VIDEO,
413     CODEC_ID_DIRAC,
414     sizeof(FfmpegSchroEncoderParams),
415     libschroedinger_encode_init,
416     libschroedinger_encode_frame,
417     libschroedinger_encode_close,
418    .capabilities = CODEC_CAP_DELAY,
419    .pix_fmts     = (enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_NONE},
420    .long_name    = NULL_IF_CONFIG_SMALL("libschroedinger Dirac 2.2"),
421 };