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