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