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