]> git.sesse.net Git - ffmpeg/blob - libavcodec/libschroedingerenc.c
Merge commit '65e73bc60f98dc7b26c687e145dfb755d3f2ccfa'
[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 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
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/avassert.h"
36 #include "libavutil/imgutils.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 } SchroEncoderParams;
76
77 /**
78 * Works out Schro-compatible chroma format.
79 */
80 static int set_chroma_format(AVCodecContext *avctx)
81 {
82     int num_formats = sizeof(schro_pixel_format_map) /
83                       sizeof(schro_pixel_format_map[0]);
84     int idx;
85
86     SchroEncoderParams *p_schro_params = avctx->priv_data;
87
88     for (idx = 0; idx < num_formats; ++idx) {
89         if (schro_pixel_format_map[idx].ff_pix_fmt == avctx->pix_fmt) {
90             p_schro_params->format->chroma_format =
91                             schro_pixel_format_map[idx].schro_pix_fmt;
92             return 0;
93         }
94     }
95
96     av_log(avctx, 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 av_cold int libschroedinger_encode_init(AVCodecContext *avctx)
104 {
105     SchroEncoderParams *p_schro_params = avctx->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(avctx, 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(avctx);
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  = avctx->width;
126     p_schro_params->format->height = avctx->height;
127
128     if (set_chroma_format(avctx) == -1)
129         return -1;
130
131     if (avctx->color_primaries == AVCOL_PRI_BT709) {
132         p_schro_params->format->colour_primaries = SCHRO_COLOUR_PRIMARY_HDTV;
133     } else if (avctx->color_primaries == AVCOL_PRI_BT470BG) {
134         p_schro_params->format->colour_primaries = SCHRO_COLOUR_PRIMARY_SDTV_625;
135     } else if (avctx->color_primaries == AVCOL_PRI_SMPTE170M) {
136         p_schro_params->format->colour_primaries = SCHRO_COLOUR_PRIMARY_SDTV_525;
137     }
138
139     if (avctx->colorspace == AVCOL_SPC_BT709) {
140         p_schro_params->format->colour_matrix = SCHRO_COLOUR_MATRIX_HDTV;
141     } else if (avctx->colorspace == AVCOL_SPC_BT470BG) {
142         p_schro_params->format->colour_matrix = SCHRO_COLOUR_MATRIX_SDTV;
143     }
144
145     if (avctx->color_trc == AVCOL_TRC_BT709) {
146         p_schro_params->format->transfer_function = SCHRO_TRANSFER_CHAR_TV_GAMMA;
147     }
148
149     if (ff_get_schro_frame_format(p_schro_params->format->chroma_format,
150                                   &p_schro_params->frame_format) == -1) {
151         av_log(avctx, AV_LOG_ERROR,
152                "This codec currently supports only planar YUV 4:2:0, 4:2:2"
153                " and 4:4:4 formats.\n");
154         return -1;
155     }
156
157     p_schro_params->format->frame_rate_numerator   = avctx->time_base.den;
158     p_schro_params->format->frame_rate_denominator = avctx->time_base.num;
159
160     p_schro_params->frame_size = av_image_get_buffer_size(avctx->pix_fmt,
161                                                           avctx->width,
162                                                           avctx->height, 1);
163
164     if (!avctx->gop_size) {
165         schro_encoder_setting_set_double(p_schro_params->encoder,
166                                          "gop_structure",
167                                          SCHRO_ENCODER_GOP_INTRA_ONLY);
168
169         if (avctx->coder_type == FF_CODER_TYPE_VLC)
170             schro_encoder_setting_set_double(p_schro_params->encoder,
171                                              "enable_noarith", 1);
172     } else {
173         schro_encoder_setting_set_double(p_schro_params->encoder,
174                                          "au_distance", avctx->gop_size);
175         avctx->has_b_frames = 1;
176         p_schro_params->dts = -1;
177     }
178
179     /* FIXME - Need to handle SCHRO_ENCODER_RATE_CONTROL_LOW_DELAY. */
180     if (avctx->flags & AV_CODEC_FLAG_QSCALE) {
181         if (!avctx->global_quality) {
182             /* lossless coding */
183             schro_encoder_setting_set_double(p_schro_params->encoder,
184                                              "rate_control",
185                                              SCHRO_ENCODER_RATE_CONTROL_LOSSLESS);
186         } else {
187             int quality;
188             schro_encoder_setting_set_double(p_schro_params->encoder,
189                                              "rate_control",
190                                              SCHRO_ENCODER_RATE_CONTROL_CONSTANT_QUALITY);
191
192             quality = avctx->global_quality / FF_QP2LAMBDA;
193             if (quality > 10)
194                 quality = 10;
195             schro_encoder_setting_set_double(p_schro_params->encoder,
196                                              "quality", quality);
197         }
198     } else {
199         schro_encoder_setting_set_double(p_schro_params->encoder,
200                                          "rate_control",
201                                          SCHRO_ENCODER_RATE_CONTROL_CONSTANT_BITRATE);
202
203         schro_encoder_setting_set_double(p_schro_params->encoder,
204                                          "bitrate", avctx->bit_rate);
205     }
206
207     if (avctx->flags & AV_CODEC_FLAG_INTERLACED_ME)
208         /* All material can be coded as interlaced or progressive
209            irrespective of the type of source material. */
210         schro_encoder_setting_set_double(p_schro_params->encoder,
211                                          "interlaced_coding", 1);
212
213     schro_encoder_setting_set_double(p_schro_params->encoder, "open_gop",
214                                      !(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP));
215
216     /* FIXME: Signal range hardcoded to 8-bit data until both libschroedinger
217      * and libdirac support other bit-depth data. */
218     schro_video_format_set_std_signal_range(p_schro_params->format,
219                                             SCHRO_SIGNAL_RANGE_8BIT_VIDEO);
220
221     /* Set the encoder format. */
222     schro_encoder_set_video_format(p_schro_params->encoder,
223                                    p_schro_params->format);
224
225     /* Set the debug level. */
226     schro_debug_set_level(avctx->debug);
227
228     schro_encoder_start(p_schro_params->encoder);
229
230     /* Initialize the encoded frame queue. */
231     ff_schro_queue_init(&p_schro_params->enc_frame_queue);
232     return 0;
233 }
234
235 static SchroFrame *libschroedinger_frame_from_data(AVCodecContext *avctx,
236                                                    const AVFrame *frame)
237 {
238     SchroEncoderParams *p_schro_params = avctx->priv_data;
239     SchroFrame *in_frame = ff_create_schro_frame(avctx,
240                                                  p_schro_params->frame_format);
241
242     if (in_frame) {
243         /* Copy input data to SchroFrame buffers (they match the ones
244          * referenced by the AVFrame stored in priv) */
245         if (av_frame_copy(in_frame->priv, frame) < 0) {
246             av_log(avctx, AV_LOG_ERROR, "Failed to copy input data\n");
247             return NULL;
248         }
249     }
250
251     return in_frame;
252 }
253
254 static void libschroedinger_free_frame(void *data)
255 {
256     FFSchroEncodedFrame *enc_frame = data;
257
258     av_freep(&enc_frame->p_encbuf);
259     av_free(enc_frame);
260 }
261
262 static int libschroedinger_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
263                                         const AVFrame *frame, int *got_packet)
264 {
265     int enc_size = 0;
266     SchroEncoderParams *p_schro_params = avctx->priv_data;
267     SchroEncoder *encoder = p_schro_params->encoder;
268     struct FFSchroEncodedFrame *p_frame_output = NULL;
269     int go = 1;
270     SchroBuffer *enc_buf;
271     int presentation_frame;
272     int parse_code;
273     int last_frame_in_sequence = 0;
274     int pkt_size, ret;
275
276     if (!frame) {
277         /* Push end of sequence if not already signalled. */
278         if (!p_schro_params->eos_signalled) {
279             schro_encoder_end_of_stream(encoder);
280             p_schro_params->eos_signalled = 1;
281         }
282     } else {
283         /* Allocate frame data to schro input buffer. */
284         SchroFrame *in_frame = libschroedinger_frame_from_data(avctx, frame);
285         if (!in_frame)
286             return AVERROR(ENOMEM);
287         /* Load next frame. */
288         schro_encoder_push_frame(encoder, in_frame);
289     }
290
291     if (p_schro_params->eos_pulled)
292         go = 0;
293
294     /* Now check to see if we have any output from the encoder. */
295     while (go) {
296         int err;
297         SchroStateEnum state;
298         state = schro_encoder_wait(encoder);
299         switch (state) {
300         case SCHRO_STATE_HAVE_BUFFER:
301         case SCHRO_STATE_END_OF_STREAM:
302             enc_buf = schro_encoder_pull(encoder, &presentation_frame);
303             if (enc_buf->length <= 0)
304                 return AVERROR_BUG;
305             parse_code = enc_buf->data[4];
306
307             /* All non-frame data is prepended to actual frame data to
308              * be able to set the pts correctly. So we don't write data
309              * to the frame output queue until we actually have a frame
310              */
311             if ((err = av_reallocp(&p_schro_params->enc_buf,
312                                    p_schro_params->enc_buf_size +
313                                    enc_buf->length)) < 0) {
314                 p_schro_params->enc_buf_size = 0;
315                 return err;
316             }
317
318             memcpy(p_schro_params->enc_buf + p_schro_params->enc_buf_size,
319                    enc_buf->data, enc_buf->length);
320             p_schro_params->enc_buf_size += enc_buf->length;
321
322
323             if (state == SCHRO_STATE_END_OF_STREAM) {
324                 p_schro_params->eos_pulled = 1;
325                 go = 0;
326             }
327
328             if (!SCHRO_PARSE_CODE_IS_PICTURE(parse_code)) {
329                 schro_buffer_unref(enc_buf);
330                 break;
331             }
332
333             /* Create output frame. */
334             p_frame_output = av_mallocz(sizeof(FFSchroEncodedFrame));
335             if (!p_frame_output)
336                 return AVERROR(ENOMEM);
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_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(avctx, 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_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_packet2(avctx, pkt, pkt_size, 0)) < 0)
385         goto error;
386
387     memcpy(pkt->data, p_frame_output->p_encbuf, p_frame_output->size);
388 #if FF_API_CODED_FRAME
389 FF_DISABLE_DEPRECATION_WARNINGS
390     avctx->coded_frame->key_frame = p_frame_output->key_frame;
391     avctx->coded_frame->pts = p_frame_output->frame_num;
392 FF_ENABLE_DEPRECATION_WARNINGS
393 #endif
394     /* Use the frame number of the encoded frame as the pts. It is OK to
395      * do so since Dirac is a constant frame rate codec. It expects input
396      * to be of constant frame rate. */
397     pkt->pts = p_frame_output->frame_num;
398     pkt->dts = p_schro_params->dts++;
399     enc_size = p_frame_output->size;
400
401     /* Append the end of sequence information to the last frame in the
402      * sequence. */
403     if (last_frame_in_sequence && p_schro_params->enc_buf_size > 0) {
404         memcpy(pkt->data + enc_size, p_schro_params->enc_buf,
405                p_schro_params->enc_buf_size);
406         enc_size += p_schro_params->enc_buf_size;
407         av_freep(&p_schro_params->enc_buf);
408         p_schro_params->enc_buf_size = 0;
409     }
410
411     if (p_frame_output->key_frame)
412         pkt->flags |= AV_PKT_FLAG_KEY;
413     *got_packet = 1;
414
415 error:
416     /* free frame */
417     libschroedinger_free_frame(p_frame_output);
418     return ret;
419 }
420
421
422 static int libschroedinger_encode_close(AVCodecContext *avctx)
423 {
424     SchroEncoderParams *p_schro_params = avctx->priv_data;
425
426     /* Close the encoder. */
427     schro_encoder_free(p_schro_params->encoder);
428
429     /* Free data in the output frame queue. */
430     ff_schro_queue_free(&p_schro_params->enc_frame_queue,
431                         libschroedinger_free_frame);
432
433
434     /* Free the encoder buffer. */
435     if (p_schro_params->enc_buf_size)
436         av_freep(&p_schro_params->enc_buf);
437
438     /* Free the video format structure. */
439     av_freep(&p_schro_params->format);
440
441     return 0;
442 }
443
444
445 AVCodec ff_libschroedinger_encoder = {
446     .name           = "libschroedinger",
447     .long_name      = NULL_IF_CONFIG_SMALL("libschroedinger Dirac 2.2"),
448     .type           = AVMEDIA_TYPE_VIDEO,
449     .id             = AV_CODEC_ID_DIRAC,
450     .priv_data_size = sizeof(SchroEncoderParams),
451     .init           = libschroedinger_encode_init,
452     .encode2        = libschroedinger_encode_frame,
453     .close          = libschroedinger_encode_close,
454     .capabilities   = AV_CODEC_CAP_DELAY,
455     .pix_fmts       = (const enum AVPixelFormat[]){
456         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_NONE
457     },
458 };