]> git.sesse.net Git - ffmpeg/blob - libavcodec/libschroedingerenc.c
lavf/qsvvpp: bypass vpp if not needed.
[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 #include <schroedinger/schro.h>
31 #include <schroedinger/schrodebug.h>
32 #include <schroedinger/schrovideoformat.h>
33
34 #include "libavutil/attributes.h"
35 #include "libavutil/imgutils.h"
36 #include "libavutil/opt.h"
37
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 size */
53     int frame_size;
54
55     /** Schroedinger encoder handle*/
56     SchroEncoder* encoder;
57
58     /** buffer to store encoder output before writing it to the frame queue*/
59     unsigned char *enc_buf;
60
61     /** Size of encoder buffer*/
62     int enc_buf_size;
63
64     /** queue storing encoded frames */
65     FFSchroQueue enc_frame_queue;
66
67     /** end of sequence signalled */
68     int eos_signalled;
69
70     /** end of sequence pulled */
71     int eos_pulled;
72
73     /* counter for frames submitted to encoder, used as dts */
74     int64_t dts;
75
76     /** enable noarith */
77     int noarith;
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 = av_image_get_buffer_size(avctx->pix_fmt,
164                                                           avctx->width,
165                                                           avctx->height, 1);
166
167     if (!avctx->gop_size) {
168         schro_encoder_setting_set_double(p_schro_params->encoder,
169                                          "gop_structure",
170                                          SCHRO_ENCODER_GOP_INTRA_ONLY);
171
172 #if FF_API_CODER_TYPE
173 FF_DISABLE_DEPRECATION_WARNINGS
174         if (avctx->coder_type != FF_CODER_TYPE_VLC)
175             p_schro_params->noarith = 0;
176 FF_ENABLE_DEPRECATION_WARNINGS
177 #endif
178         schro_encoder_setting_set_double(p_schro_params->encoder,
179                                          "enable_noarith",
180                                          p_schro_params->noarith);
181     } else {
182         schro_encoder_setting_set_double(p_schro_params->encoder,
183                                          "au_distance", avctx->gop_size);
184         avctx->has_b_frames = 1;
185         p_schro_params->dts = -1;
186     }
187
188     /* FIXME - Need to handle SCHRO_ENCODER_RATE_CONTROL_LOW_DELAY. */
189     if (avctx->flags & AV_CODEC_FLAG_QSCALE) {
190         if (!avctx->global_quality) {
191             /* lossless coding */
192             schro_encoder_setting_set_double(p_schro_params->encoder,
193                                              "rate_control",
194                                              SCHRO_ENCODER_RATE_CONTROL_LOSSLESS);
195         } else {
196             int quality;
197             schro_encoder_setting_set_double(p_schro_params->encoder,
198                                              "rate_control",
199                                              SCHRO_ENCODER_RATE_CONTROL_CONSTANT_QUALITY);
200
201             quality = avctx->global_quality / FF_QP2LAMBDA;
202             if (quality > 10)
203                 quality = 10;
204             schro_encoder_setting_set_double(p_schro_params->encoder,
205                                              "quality", quality);
206         }
207     } else {
208         schro_encoder_setting_set_double(p_schro_params->encoder,
209                                          "rate_control",
210                                          SCHRO_ENCODER_RATE_CONTROL_CONSTANT_BITRATE);
211
212         schro_encoder_setting_set_double(p_schro_params->encoder,
213                                          "bitrate", avctx->bit_rate);
214     }
215
216     if (avctx->flags & AV_CODEC_FLAG_INTERLACED_ME)
217         /* All material can be coded as interlaced or progressive
218            irrespective of the type of source material. */
219         schro_encoder_setting_set_double(p_schro_params->encoder,
220                                          "interlaced_coding", 1);
221
222     schro_encoder_setting_set_double(p_schro_params->encoder, "open_gop",
223                                      !(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP));
224
225     /* FIXME: Signal range hardcoded to 8-bit data until both libschroedinger
226      * and libdirac support other bit-depth data. */
227     schro_video_format_set_std_signal_range(p_schro_params->format,
228                                             SCHRO_SIGNAL_RANGE_8BIT_VIDEO);
229
230     /* Set the encoder format. */
231     schro_encoder_set_video_format(p_schro_params->encoder,
232                                    p_schro_params->format);
233
234     /* Set the debug level. */
235     schro_debug_set_level(avctx->debug);
236
237     schro_encoder_start(p_schro_params->encoder);
238
239     /* Initialize the encoded frame queue. */
240     ff_schro_queue_init(&p_schro_params->enc_frame_queue);
241     return 0;
242 }
243
244 static SchroFrame *libschroedinger_frame_from_data(AVCodecContext *avctx,
245                                                    const AVFrame *frame)
246 {
247     SchroEncoderParams *p_schro_params = avctx->priv_data;
248     SchroFrame *in_frame = ff_create_schro_frame(avctx,
249                                                  p_schro_params->frame_format);
250
251     if (in_frame) {
252         /* Copy input data to SchroFrame buffers (they match the ones
253          * referenced by the AVFrame stored in priv) */
254         if (av_frame_copy(in_frame->priv, frame) < 0) {
255             av_log(avctx, AV_LOG_ERROR, "Failed to copy input data\n");
256             return NULL;
257         }
258     }
259
260     return in_frame;
261 }
262
263 static void libschroedinger_free_frame(void *data)
264 {
265     FFSchroEncodedFrame *enc_frame = data;
266
267     av_freep(&enc_frame->p_encbuf);
268     av_free(enc_frame);
269 }
270
271 static int libschroedinger_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
272                                         const AVFrame *frame, int *got_packet)
273 {
274     int enc_size = 0;
275     SchroEncoderParams *p_schro_params = avctx->priv_data;
276     SchroEncoder *encoder = p_schro_params->encoder;
277     struct FFSchroEncodedFrame *p_frame_output = NULL;
278     int go = 1;
279     SchroBuffer *enc_buf;
280     int presentation_frame;
281     int parse_code;
282     int last_frame_in_sequence = 0;
283     int pkt_size, ret;
284
285     if (!frame) {
286         /* Push end of sequence if not already signalled. */
287         if (!p_schro_params->eos_signalled) {
288             schro_encoder_end_of_stream(encoder);
289             p_schro_params->eos_signalled = 1;
290         }
291     } else {
292         /* Allocate frame data to schro input buffer. */
293         SchroFrame *in_frame = libschroedinger_frame_from_data(avctx, frame);
294         if (!in_frame)
295             return AVERROR(ENOMEM);
296         /* Load next frame. */
297         schro_encoder_push_frame(encoder, in_frame);
298     }
299
300     if (p_schro_params->eos_pulled)
301         go = 0;
302
303     /* Now check to see if we have any output from the encoder. */
304     while (go) {
305         int err;
306         SchroStateEnum state;
307         state = schro_encoder_wait(encoder);
308         switch (state) {
309         case SCHRO_STATE_HAVE_BUFFER:
310         case SCHRO_STATE_END_OF_STREAM:
311             enc_buf = schro_encoder_pull(encoder, &presentation_frame);
312             if (enc_buf->length <= 0)
313                 return AVERROR_BUG;
314             parse_code = enc_buf->data[4];
315
316             /* All non-frame data is prepended to actual frame data to
317              * be able to set the pts correctly. So we don't write data
318              * to the frame output queue until we actually have a frame
319              */
320             if ((err = av_reallocp(&p_schro_params->enc_buf,
321                                    p_schro_params->enc_buf_size +
322                                    enc_buf->length)) < 0) {
323                 p_schro_params->enc_buf_size = 0;
324                 return err;
325             }
326
327             memcpy(p_schro_params->enc_buf + p_schro_params->enc_buf_size,
328                    enc_buf->data, enc_buf->length);
329             p_schro_params->enc_buf_size += enc_buf->length;
330
331
332             if (state == SCHRO_STATE_END_OF_STREAM) {
333                 p_schro_params->eos_pulled = 1;
334                 go = 0;
335             }
336
337             if (!SCHRO_PARSE_CODE_IS_PICTURE(parse_code)) {
338                 schro_buffer_unref(enc_buf);
339                 break;
340             }
341
342             /* Create output frame. */
343             p_frame_output = av_mallocz(sizeof(FFSchroEncodedFrame));
344             if (!p_frame_output)
345                 return AVERROR(ENOMEM);
346             /* Set output data. */
347             p_frame_output->size     = p_schro_params->enc_buf_size;
348             p_frame_output->p_encbuf = p_schro_params->enc_buf;
349             if (SCHRO_PARSE_CODE_IS_INTRA(parse_code) &&
350                 SCHRO_PARSE_CODE_IS_REFERENCE(parse_code))
351                 p_frame_output->key_frame = 1;
352
353             /* Parse the coded frame number from the bitstream. Bytes 14
354              * through 17 represent the frame number. */
355             p_frame_output->frame_num = AV_RB32(enc_buf->data + 13);
356
357             ff_schro_queue_push_back(&p_schro_params->enc_frame_queue,
358                                      p_frame_output);
359             p_schro_params->enc_buf_size = 0;
360             p_schro_params->enc_buf      = NULL;
361
362             schro_buffer_unref(enc_buf);
363
364             break;
365
366         case SCHRO_STATE_NEED_FRAME:
367             go = 0;
368             break;
369
370         case SCHRO_STATE_AGAIN:
371             break;
372
373         default:
374             av_log(avctx, AV_LOG_ERROR, "Unknown Schro Encoder state\n");
375             return -1;
376         }
377     }
378
379     /* Copy 'next' frame in queue. */
380
381     if (p_schro_params->enc_frame_queue.size == 1 &&
382         p_schro_params->eos_pulled)
383         last_frame_in_sequence = 1;
384
385     p_frame_output = ff_schro_queue_pop(&p_schro_params->enc_frame_queue);
386
387     if (!p_frame_output)
388         return 0;
389
390     pkt_size = p_frame_output->size;
391     if (last_frame_in_sequence && p_schro_params->enc_buf_size > 0)
392         pkt_size += p_schro_params->enc_buf_size;
393     if ((ret = ff_alloc_packet(pkt, pkt_size)) < 0) {
394         av_log(avctx, AV_LOG_ERROR, "Error getting output packet of size %d.\n", pkt_size);
395         goto error;
396     }
397
398     memcpy(pkt->data, p_frame_output->p_encbuf, p_frame_output->size);
399 #if FF_API_CODED_FRAME
400 FF_DISABLE_DEPRECATION_WARNINGS
401     avctx->coded_frame->key_frame = p_frame_output->key_frame;
402     avctx->coded_frame->pts = p_frame_output->frame_num;
403 FF_ENABLE_DEPRECATION_WARNINGS
404 #endif
405     /* Use the frame number of the encoded frame as the pts. It is OK to
406      * do so since Dirac is a constant frame rate codec. It expects input
407      * to be of constant frame rate. */
408     pkt->pts = p_frame_output->frame_num;
409     pkt->dts = p_schro_params->dts++;
410     enc_size = p_frame_output->size;
411
412     /* Append the end of sequence information to the last frame in the
413      * sequence. */
414     if (last_frame_in_sequence && p_schro_params->enc_buf_size > 0) {
415         memcpy(pkt->data + enc_size, p_schro_params->enc_buf,
416                p_schro_params->enc_buf_size);
417         enc_size += p_schro_params->enc_buf_size;
418         av_freep(&p_schro_params->enc_buf);
419         p_schro_params->enc_buf_size = 0;
420     }
421
422     if (p_frame_output->key_frame)
423         pkt->flags |= AV_PKT_FLAG_KEY;
424     *got_packet = 1;
425
426 error:
427     /* free frame */
428     libschroedinger_free_frame(p_frame_output);
429     return ret;
430 }
431
432
433 static int libschroedinger_encode_close(AVCodecContext *avctx)
434 {
435     SchroEncoderParams *p_schro_params = avctx->priv_data;
436
437     /* Close the encoder. */
438     schro_encoder_free(p_schro_params->encoder);
439
440     /* Free data in the output frame queue. */
441     ff_schro_queue_free(&p_schro_params->enc_frame_queue,
442                         libschroedinger_free_frame);
443
444
445     /* Free the encoder buffer. */
446     if (p_schro_params->enc_buf_size)
447         av_freep(&p_schro_params->enc_buf);
448
449     /* Free the video format structure. */
450     av_freep(&p_schro_params->format);
451
452     return 0;
453 }
454
455 #define OFFSET(x) offsetof(SchroEncoderParams, x)
456 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
457 static const AVOption options[] = {
458     { "noarith", "Enable noarith", OFFSET(noarith), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, VE },
459
460     { NULL },
461 };
462
463 static const AVClass libschroedinger_class = {
464     .class_name = "libschroedinger",
465     .item_name  = av_default_item_name,
466     .option     = options,
467     .version    = LIBAVUTIL_VERSION_INT,
468 };
469
470 AVCodec ff_libschroedinger_encoder = {
471     .name           = "libschroedinger",
472     .long_name      = NULL_IF_CONFIG_SMALL("libschroedinger Dirac 2.2"),
473     .type           = AVMEDIA_TYPE_VIDEO,
474     .id             = AV_CODEC_ID_DIRAC,
475     .priv_data_size = sizeof(SchroEncoderParams),
476     .priv_class     = &libschroedinger_class,
477     .init           = libschroedinger_encode_init,
478     .encode2        = libschroedinger_encode_frame,
479     .close          = libschroedinger_encode_close,
480     .capabilities   = AV_CODEC_CAP_DELAY,
481     .pix_fmts       = (const enum AVPixelFormat[]){
482         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_NONE
483     },
484     .wrapper_name   = "libschroedinger",
485 };