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