db72516187dd70a763d82d9e39ec79706aa25fbf
[ffmpeg.git] / libavcodec / vaapi_encode_mpeg2.c
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * FFmpeg is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with FFmpeg; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #include <va/va.h>
20 #include <va/va_enc_mpeg2.h>
21
22 #include "libavutil/avassert.h"
23
24 #include "avcodec.h"
25 #include "cbs.h"
26 #include "cbs_mpeg2.h"
27 #include "mpeg12.h"
28 #include "vaapi_encode.h"
29
30 typedef struct VAAPIEncodeMPEG2Context {
31     VAAPIEncodeContext common;
32
33     // User options.
34     int profile;
35     int level;
36
37     // Derived settings.
38     int mb_width;
39     int mb_height;
40
41     int quant_i;
42     int quant_p;
43     int quant_b;
44
45     unsigned int bit_rate;
46     unsigned int vbv_buffer_size;
47
48     AVRational frame_rate;
49
50     unsigned int f_code_horizontal;
51     unsigned int f_code_vertical;
52
53     // Stream state.
54     int64_t last_i_frame;
55
56     // Writer structures.
57     MPEG2RawSequenceHeader sequence_header;
58     MPEG2RawExtensionData  sequence_extension;
59     MPEG2RawExtensionData  sequence_display_extension;
60     MPEG2RawGroupOfPicturesHeader gop_header;
61     MPEG2RawPictureHeader  picture_header;
62     MPEG2RawExtensionData  picture_coding_extension;
63
64     CodedBitstreamContext *cbc;
65     CodedBitstreamFragment current_fragment;
66 } VAAPIEncodeMPEG2Context;
67
68
69 static int vaapi_encode_mpeg2_write_fragment(AVCodecContext *avctx,
70                                              char *data, size_t *data_len,
71                                              CodedBitstreamFragment *frag)
72 {
73     VAAPIEncodeMPEG2Context *priv = avctx->priv_data;
74     int err;
75
76     err = ff_cbs_write_fragment_data(priv->cbc, frag);
77     if (err < 0) {
78         av_log(avctx, AV_LOG_ERROR, "Failed to write packed header.\n");
79         return err;
80     }
81
82     if (*data_len < 8 * frag->data_size - frag->data_bit_padding) {
83         av_log(avctx, AV_LOG_ERROR, "Access unit too large: "
84                "%zu < %zu.\n", *data_len,
85                8 * frag->data_size - frag->data_bit_padding);
86         return AVERROR(ENOSPC);
87     }
88
89     memcpy(data, frag->data, frag->data_size);
90     *data_len = 8 * frag->data_size - frag->data_bit_padding;
91
92     return 0;
93 }
94
95 static int vaapi_encode_mpeg2_add_header(AVCodecContext *avctx,
96                                          CodedBitstreamFragment *frag,
97                                          int type, void *header)
98 {
99     VAAPIEncodeMPEG2Context *priv = avctx->priv_data;
100     int err;
101
102     err = ff_cbs_insert_unit_content(priv->cbc, frag, -1, type, header, NULL);
103     if (err < 0) {
104         av_log(avctx, AV_LOG_ERROR, "Failed to add header: "
105                "type = %d.\n", type);
106         return err;
107     }
108
109     return 0;
110 }
111
112 static int vaapi_encode_mpeg2_write_sequence_header(AVCodecContext *avctx,
113                                                     char *data, size_t *data_len)
114 {
115     VAAPIEncodeMPEG2Context *priv = avctx->priv_data;
116     CodedBitstreamFragment  *frag = &priv->current_fragment;
117     int err;
118
119     err = vaapi_encode_mpeg2_add_header(avctx, frag, MPEG2_START_SEQUENCE_HEADER,
120                                         &priv->sequence_header);
121     if (err < 0)
122         goto fail;
123
124     err = vaapi_encode_mpeg2_add_header(avctx, frag, MPEG2_START_EXTENSION,
125                                         &priv->sequence_extension);
126     if (err < 0)
127         goto fail;
128
129     err = vaapi_encode_mpeg2_add_header(avctx, frag, MPEG2_START_EXTENSION,
130                                         &priv->sequence_display_extension);
131     if (err < 0)
132         goto fail;
133
134     err = vaapi_encode_mpeg2_add_header(avctx, frag, MPEG2_START_GROUP,
135                                         &priv->gop_header);
136     if (err < 0)
137         goto fail;
138
139     err = vaapi_encode_mpeg2_write_fragment(avctx, data, data_len, frag);
140 fail:
141     ff_cbs_fragment_uninit(priv->cbc, frag);
142     return 0;
143 }
144
145 static int vaapi_encode_mpeg2_write_picture_header(AVCodecContext *avctx,
146                                                    VAAPIEncodePicture *pic,
147                                                    char *data, size_t *data_len)
148 {
149     VAAPIEncodeMPEG2Context *priv = avctx->priv_data;
150     CodedBitstreamFragment  *frag = &priv->current_fragment;
151     int err;
152
153     err = vaapi_encode_mpeg2_add_header(avctx, frag, MPEG2_START_PICTURE,
154                                         &priv->picture_header);
155     if (err < 0)
156         goto fail;
157
158     err = vaapi_encode_mpeg2_add_header(avctx, frag, MPEG2_START_EXTENSION,
159                                         &priv->picture_coding_extension);
160     if (err < 0)
161         goto fail;
162
163     err = vaapi_encode_mpeg2_write_fragment(avctx, data, data_len, frag);
164 fail:
165     ff_cbs_fragment_uninit(priv->cbc, frag);
166     return 0;
167 }
168
169 static int vaapi_encode_mpeg2_init_sequence_params(AVCodecContext *avctx)
170 {
171     VAAPIEncodeContext                 *ctx = avctx->priv_data;
172     VAAPIEncodeMPEG2Context           *priv = avctx->priv_data;
173     MPEG2RawSequenceHeader              *sh = &priv->sequence_header;
174     MPEG2RawSequenceExtension           *se = &priv->sequence_extension.data.sequence;
175     MPEG2RawSequenceDisplayExtension   *sde = &priv->sequence_display_extension.data.sequence_display;
176     MPEG2RawGroupOfPicturesHeader     *goph = &priv->gop_header;
177     MPEG2RawPictureHeader               *ph = &priv->picture_header;
178     MPEG2RawPictureCodingExtension     *pce = &priv->picture_coding_extension.data.picture_coding;
179     VAEncSequenceParameterBufferMPEG2 *vseq = ctx->codec_sequence_params;
180     VAEncPictureParameterBufferMPEG2  *vpic = ctx->codec_picture_params;
181     int code, ext_n, ext_d;
182
183     memset(sh,   0, sizeof(*sh));
184     memset(se,   0, sizeof(*se));
185     memset(sde,  0, sizeof(*sde));
186     memset(goph, 0, sizeof(*goph));
187     memset(ph,   0, sizeof(*ph));
188     memset(pce,  0, sizeof(*pce));
189
190
191     if (ctx->va_bit_rate > 0) {
192         priv->bit_rate = (ctx->va_bit_rate + 399) / 400;
193     } else {
194         // Unknown (not a bitrate-targetting mode), so just use the
195         // highest value.
196         priv->bit_rate = 0x3fffffff;
197     }
198     if (avctx->rc_buffer_size > 0) {
199         priv->vbv_buffer_size = (avctx->rc_buffer_size + (1 << 14) - 1) >> 14;
200     } else {
201         // Unknown, so guess a value from the bitrate.
202         priv->vbv_buffer_size = priv->bit_rate >> 14;
203     }
204
205     switch (avctx->level) {
206     case 4: // High.
207     case 6: // High 1440.
208         priv->f_code_horizontal = 9;
209         priv->f_code_vertical   = 5;
210         break;
211     case 8: // Main.
212         priv->f_code_horizontal = 8;
213         priv->f_code_vertical   = 5;
214         break;
215     case 10: // Low.
216     default:
217         priv->f_code_horizontal = 7;
218         priv->f_code_vertical   = 4;
219         break;
220     }
221
222
223     // Sequence header
224
225     sh->sequence_header_code = MPEG2_START_SEQUENCE_HEADER;
226
227     sh->horizontal_size_value = avctx->width  & 0xfff;
228     sh->vertical_size_value   = avctx->height & 0xfff;
229
230     if (avctx->sample_aspect_ratio.num != 0 &&
231         avctx->sample_aspect_ratio.den != 0) {
232         AVRational dar = av_div_q(avctx->sample_aspect_ratio,
233                                   (AVRational) { avctx->width, avctx->height });
234
235         if (av_cmp_q(avctx->sample_aspect_ratio, (AVRational) { 1, 1 }) == 0) {
236             sh->aspect_ratio_information = 1;
237         } else if (av_cmp_q(dar, (AVRational) { 3, 4 }) == 0) {
238             sh->aspect_ratio_information = 2;
239         } else if (av_cmp_q(dar, (AVRational) { 9, 16 }) == 0) {
240             sh->aspect_ratio_information = 3;
241         } else if (av_cmp_q(dar, (AVRational) { 100, 221 }) == 0) {
242             sh->aspect_ratio_information = 4;
243         } else {
244             av_log(avctx, AV_LOG_WARNING, "Sample aspect ratio %d:%d is not "
245                    "representable, signalling square pixels instead.\n",
246                    avctx->sample_aspect_ratio.num,
247                    avctx->sample_aspect_ratio.den);
248             sh->aspect_ratio_information = 1;
249         }
250     } else {
251         // Unknown - assume square pixels.
252         sh->aspect_ratio_information = 1;
253     }
254
255     if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
256         priv->frame_rate = avctx->framerate;
257     else
258         priv->frame_rate = av_inv_q(avctx->time_base);
259     ff_mpeg12_find_best_frame_rate(priv->frame_rate,
260                                    &code, &ext_n, &ext_d, 0);
261     sh->frame_rate_code = code;
262
263     sh->bit_rate_value        = priv->bit_rate & 0x3ffff;
264     sh->vbv_buffer_size_value = priv->vbv_buffer_size & 0x3ff;
265
266     sh->constrained_parameters_flag     = 0;
267     sh->load_intra_quantiser_matrix     = 0;
268     sh->load_non_intra_quantiser_matrix = 0;
269
270
271     // Sequence extension
272
273     priv->sequence_extension.extension_start_code = MPEG2_START_EXTENSION;
274     priv->sequence_extension.extension_start_code_identifier =
275         MPEG2_EXTENSION_SEQUENCE;
276
277     se->profile_and_level_indication = avctx->profile << 4 | avctx->level;
278     se->progressive_sequence = 1;
279     se->chroma_format        = 1;
280
281     se->horizontal_size_extension = avctx->width  >> 12;
282     se->vertical_size_extension   = avctx->height >> 12;
283
284     se->bit_rate_extension        = priv->bit_rate >> 18;
285     se->vbv_buffer_size_extension = priv->vbv_buffer_size >> 10;
286     se->low_delay                 = ctx->b_per_p == 0;
287
288     se->frame_rate_extension_n = ext_n;
289     se->frame_rate_extension_d = ext_d;
290
291
292     // Sequence display extension
293
294     priv->sequence_display_extension.extension_start_code =
295         MPEG2_START_EXTENSION;
296     priv->sequence_display_extension.extension_start_code_identifier =
297         MPEG2_EXTENSION_SEQUENCE_DISPLAY;
298
299     sde->video_format = 5;
300     if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
301         avctx->color_trc       != AVCOL_TRC_UNSPECIFIED ||
302         avctx->colorspace      != AVCOL_SPC_UNSPECIFIED) {
303         sde->colour_description       = 1;
304         sde->colour_primaries         = avctx->color_primaries;
305         sde->transfer_characteristics = avctx->color_trc;
306         sde->matrix_coefficients      = avctx->colorspace;
307     } else {
308         sde->colour_description = 0;
309     }
310
311     sde->display_horizontal_size = avctx->width;
312     sde->display_vertical_size   = avctx->height;
313
314
315     // GOP header
316
317     goph->group_start_code = MPEG2_START_GROUP;
318
319     goph->time_code   = 0;
320     goph->closed_gop  = 1;
321     goph->broken_link = 0;
322
323
324     // Defaults for picture header
325
326     ph->picture_start_code = MPEG2_START_PICTURE;
327
328     ph->vbv_delay = 0xffff; // Not currently calculated.
329
330     ph->full_pel_forward_vector  = 0;
331     ph->forward_f_code           = 7;
332     ph->full_pel_backward_vector = 0;
333     ph->forward_f_code           = 7;
334
335
336     // Defaults for picture coding extension
337
338     priv->picture_coding_extension.extension_start_code =
339         MPEG2_START_EXTENSION;
340     priv->picture_coding_extension.extension_start_code_identifier =
341         MPEG2_EXTENSION_PICTURE_CODING;
342
343     pce->intra_dc_precision         = 0;
344     pce->picture_structure          = 3;
345     pce->top_field_first            = 0;
346     pce->frame_pred_frame_dct       = 1;
347     pce->concealment_motion_vectors = 0;
348     pce->q_scale_type               = 0;
349     pce->intra_vlc_format           = 0;
350     pce->alternate_scan             = 0;
351     pce->repeat_first_field         = 0;
352     pce->progressive_frame          = 1;
353     pce->composite_display_flag     = 0;
354
355
356
357     *vseq = (VAEncSequenceParameterBufferMPEG2) {
358         .intra_period = avctx->gop_size,
359         .ip_period    = ctx->b_per_p + 1,
360
361         .picture_width  = avctx->width,
362         .picture_height = avctx->height,
363
364         .bits_per_second          = ctx->va_bit_rate,
365         .frame_rate               = av_q2d(priv->frame_rate),
366         .aspect_ratio_information = sh->aspect_ratio_information,
367         .vbv_buffer_size          = priv->vbv_buffer_size,
368
369         .sequence_extension.bits = {
370             .profile_and_level_indication = se->profile_and_level_indication,
371             .progressive_sequence         = se->progressive_sequence,
372             .chroma_format                = se->chroma_format,
373             .low_delay                    = se->low_delay,
374             .frame_rate_extension_n       = se->frame_rate_extension_n,
375             .frame_rate_extension_d       = se->frame_rate_extension_d,
376         },
377
378         .new_gop_header = 1,
379         .gop_header.bits = {
380             .time_code   = goph->time_code,
381             .closed_gop  = goph->closed_gop,
382             .broken_link = goph->broken_link,
383         },
384     };
385
386     *vpic = (VAEncPictureParameterBufferMPEG2) {
387         .forward_reference_picture  = VA_INVALID_ID,
388         .backward_reference_picture = VA_INVALID_ID,
389         .reconstructed_picture      = VA_INVALID_ID,
390         .coded_buf                  = VA_INVALID_ID,
391
392         .vbv_delay = 0xffff,
393         .f_code    = { { 15, 15 }, { 15, 15 } },
394
395         .picture_coding_extension.bits = {
396             .intra_dc_precision         = pce->intra_dc_precision,
397             .picture_structure          = pce->picture_structure,
398             .top_field_first            = pce->top_field_first,
399             .frame_pred_frame_dct       = pce->frame_pred_frame_dct,
400             .concealment_motion_vectors = pce->concealment_motion_vectors,
401             .q_scale_type               = pce->q_scale_type,
402             .intra_vlc_format           = pce->intra_vlc_format,
403             .alternate_scan             = pce->alternate_scan,
404             .repeat_first_field         = pce->repeat_first_field,
405             .progressive_frame          = pce->progressive_frame,
406             .composite_display_flag     = pce->composite_display_flag,
407         },
408
409         .composite_display.bits = {
410             .v_axis            = pce->v_axis,
411             .field_sequence    = pce->field_sequence,
412             .sub_carrier       = pce->sub_carrier,
413             .burst_amplitude   = pce->burst_amplitude,
414             .sub_carrier_phase = pce->sub_carrier_phase,
415         },
416     };
417
418     return 0;
419 }
420
421 static int vaapi_encode_mpeg2_init_picture_params(AVCodecContext *avctx,
422                                                  VAAPIEncodePicture *pic)
423 {
424     VAAPIEncodeMPEG2Context          *priv = avctx->priv_data;
425     MPEG2RawPictureHeader              *ph = &priv->picture_header;
426     MPEG2RawPictureCodingExtension    *pce = &priv->picture_coding_extension.data.picture_coding;
427     VAEncPictureParameterBufferMPEG2 *vpic = pic->codec_picture_params;
428
429     if (pic->type == PICTURE_TYPE_IDR || pic->type == PICTURE_TYPE_I) {
430         ph->temporal_reference  = 0;
431         ph->picture_coding_type = 1;
432         priv->last_i_frame = pic->display_order;
433     } else {
434         ph->temporal_reference = pic->display_order - priv->last_i_frame;
435         ph->picture_coding_type = pic->type == PICTURE_TYPE_B ? 3 : 2;
436     }
437
438     if (pic->type == PICTURE_TYPE_P || pic->type == PICTURE_TYPE_B) {
439         pce->f_code[0][0] = priv->f_code_horizontal;
440         pce->f_code[0][1] = priv->f_code_vertical;
441     } else {
442         pce->f_code[0][0] = 15;
443         pce->f_code[0][1] = 15;
444     }
445     if (pic->type == PICTURE_TYPE_B) {
446         pce->f_code[1][0] = priv->f_code_horizontal;
447         pce->f_code[1][1] = priv->f_code_vertical;
448     } else {
449         pce->f_code[1][0] = 15;
450         pce->f_code[1][1] = 15;
451     }
452
453     vpic->reconstructed_picture = pic->recon_surface;
454     vpic->coded_buf             = pic->output_buffer;
455
456     switch (pic->type) {
457     case PICTURE_TYPE_IDR:
458     case PICTURE_TYPE_I:
459         vpic->picture_type = VAEncPictureTypeIntra;
460         break;
461     case PICTURE_TYPE_P:
462         vpic->picture_type = VAEncPictureTypePredictive;
463         vpic->forward_reference_picture = pic->refs[0]->recon_surface;
464         break;
465     case PICTURE_TYPE_B:
466         vpic->picture_type = VAEncPictureTypeBidirectional;
467         vpic->forward_reference_picture  = pic->refs[0]->recon_surface;
468         vpic->backward_reference_picture = pic->refs[1]->recon_surface;
469         break;
470     default:
471         av_assert0(0 && "invalid picture type");
472     }
473
474     vpic->temporal_reference = ph->temporal_reference;
475     vpic->f_code[0][0]       = pce->f_code[0][0];
476     vpic->f_code[0][1]       = pce->f_code[0][1];
477     vpic->f_code[1][0]       = pce->f_code[1][0];
478     vpic->f_code[1][1]       = pce->f_code[1][1];
479
480     pic->nb_slices = priv->mb_height;
481
482     return 0;
483 }
484
485 static int vaapi_encode_mpeg2_init_slice_params(AVCodecContext *avctx,
486                                                VAAPIEncodePicture *pic,
487                                                VAAPIEncodeSlice *slice)
488 {
489     VAAPIEncodeMPEG2Context            *priv = avctx->priv_data;
490     VAEncSliceParameterBufferMPEG2   *vslice = slice->codec_slice_params;
491     int qp;
492
493     vslice->macroblock_address = priv->mb_width * slice->index;
494     vslice->num_macroblocks    = priv->mb_width;
495
496     switch (pic->type) {
497     case PICTURE_TYPE_IDR:
498     case PICTURE_TYPE_I:
499         qp = priv->quant_i;
500         break;
501     case PICTURE_TYPE_P:
502         qp = priv->quant_p;
503         break;
504     case PICTURE_TYPE_B:
505         qp = priv->quant_b;
506         break;
507     default:
508         av_assert0(0 && "invalid picture type");
509     }
510
511     vslice->quantiser_scale_code = qp;
512     vslice->is_intra_slice = (pic->type == PICTURE_TYPE_IDR ||
513                               pic->type == PICTURE_TYPE_I);
514
515     return 0;
516 }
517
518 static av_cold int vaapi_encode_mpeg2_configure(AVCodecContext *avctx)
519 {
520     VAAPIEncodeContext       *ctx = avctx->priv_data;
521     VAAPIEncodeMPEG2Context *priv = avctx->priv_data;
522     int err;
523
524     err = ff_cbs_init(&priv->cbc, AV_CODEC_ID_MPEG2VIDEO, avctx);
525     if (err < 0)
526         return err;
527
528     priv->mb_width  = FFALIGN(avctx->width,  16) / 16;
529     priv->mb_height = FFALIGN(avctx->height, 16) / 16;
530
531     if (ctx->va_rc_mode == VA_RC_CQP) {
532         priv->quant_p = av_clip(avctx->global_quality, 1, 31);
533         if (avctx->i_quant_factor > 0.0)
534             priv->quant_i = av_clip((avctx->global_quality *
535                                      avctx->i_quant_factor +
536                                      avctx->i_quant_offset) + 0.5,
537                                     1, 31);
538         else
539             priv->quant_i = priv->quant_p;
540         if (avctx->b_quant_factor > 0.0)
541             priv->quant_b = av_clip((avctx->global_quality *
542                                      avctx->b_quant_factor +
543                                      avctx->b_quant_offset) + 0.5,
544                                     1, 31);
545         else
546             priv->quant_b = priv->quant_p;
547
548         av_log(avctx, AV_LOG_DEBUG, "Using fixed quantiser "
549                "%d / %d / %d for I- / P- / B-frames.\n",
550                priv->quant_i, priv->quant_p, priv->quant_b);
551
552     } else {
553         av_assert0(0 && "Invalid RC mode.");
554     }
555
556     return 0;
557 }
558
559 static const VAAPIEncodeProfile vaapi_encode_mpeg2_profiles[] = {
560     { FF_PROFILE_MPEG2_MAIN,   8, 3, 1, 1, VAProfileMPEG2Main   },
561     { FF_PROFILE_MPEG2_SIMPLE, 8, 3, 1, 1, VAProfileMPEG2Simple },
562     { FF_PROFILE_UNKNOWN }
563 };
564
565 static const VAAPIEncodeType vaapi_encode_type_mpeg2 = {
566     .profiles              = vaapi_encode_mpeg2_profiles,
567
568     .configure             = &vaapi_encode_mpeg2_configure,
569
570     .sequence_params_size  = sizeof(VAEncSequenceParameterBufferMPEG2),
571     .init_sequence_params  = &vaapi_encode_mpeg2_init_sequence_params,
572
573     .picture_params_size   = sizeof(VAEncPictureParameterBufferMPEG2),
574     .init_picture_params   = &vaapi_encode_mpeg2_init_picture_params,
575
576     .slice_params_size     = sizeof(VAEncSliceParameterBufferMPEG2),
577     .init_slice_params     = &vaapi_encode_mpeg2_init_slice_params,
578
579     .sequence_header_type  = VAEncPackedHeaderSequence,
580     .write_sequence_header = &vaapi_encode_mpeg2_write_sequence_header,
581
582     .picture_header_type   = VAEncPackedHeaderPicture,
583     .write_picture_header  = &vaapi_encode_mpeg2_write_picture_header,
584 };
585
586 static av_cold int vaapi_encode_mpeg2_init(AVCodecContext *avctx)
587 {
588     VAAPIEncodeContext       *ctx = avctx->priv_data;
589     VAAPIEncodeMPEG2Context *priv = avctx->priv_data;
590
591     ctx->codec = &vaapi_encode_type_mpeg2;
592
593     if (avctx->profile == FF_PROFILE_UNKNOWN)
594         avctx->profile = priv->profile;
595     if (avctx->level == FF_LEVEL_UNKNOWN)
596         avctx->level = priv->level;
597
598     // Reject unknown levels (these are required to set f_code for
599     // motion vector encoding).
600     switch (avctx->level) {
601     case 4: // High
602     case 6: // High 1440
603     case 8: // Main
604     case 10: // Low
605         break;
606     default:
607         av_log(avctx, AV_LOG_ERROR, "Unknown MPEG-2 level %d.\n",
608                avctx->level);
609         return AVERROR(EINVAL);
610     }
611
612     if (avctx->height % 4096 == 0 || avctx->width % 4096 == 0) {
613         av_log(avctx, AV_LOG_ERROR, "MPEG-2 does not support picture "
614                "height or width divisible by 4096.\n");
615         return AVERROR(EINVAL);
616     }
617
618     ctx->va_packed_headers = VA_ENC_PACKED_HEADER_SEQUENCE |
619                              VA_ENC_PACKED_HEADER_PICTURE;
620
621     ctx->surface_width  = FFALIGN(avctx->width,  16);
622     ctx->surface_height = FFALIGN(avctx->height, 16);
623
624     return ff_vaapi_encode_init(avctx);
625 }
626
627 static av_cold int vaapi_encode_mpeg2_close(AVCodecContext *avctx)
628 {
629     VAAPIEncodeMPEG2Context *priv = avctx->priv_data;
630
631     ff_cbs_close(&priv->cbc);
632
633     return ff_vaapi_encode_close(avctx);
634 }
635
636 #define OFFSET(x) offsetof(VAAPIEncodeMPEG2Context, x)
637 #define FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
638 static const AVOption vaapi_encode_mpeg2_options[] = {
639     VAAPI_ENCODE_COMMON_OPTIONS,
640
641     { "profile", "Set profile (in profile_and_level_indication)",
642       OFFSET(profile), AV_OPT_TYPE_INT,
643       { .i64 = FF_PROFILE_UNKNOWN }, FF_PROFILE_UNKNOWN, 7, FLAGS, "profile" },
644
645 #define PROFILE(name, value)  name, NULL, 0, AV_OPT_TYPE_CONST, \
646       { .i64 = value }, 0, 0, FLAGS, "profile"
647     { PROFILE("simple", FF_PROFILE_MPEG2_SIMPLE) },
648     { PROFILE("main",   FF_PROFILE_MPEG2_MAIN)   },
649 #undef PROFILE
650
651     { "level", "Set level (in profile_and_level_indication)",
652       OFFSET(level), AV_OPT_TYPE_INT,
653       { .i64 = 4 }, 0, 15, FLAGS, "level" },
654
655 #define LEVEL(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
656       { .i64 = value }, 0, 0, FLAGS, "level"
657     { LEVEL("low",       10) },
658     { LEVEL("main",       8) },
659     { LEVEL("high_1440",  6) },
660     { LEVEL("high",       4) },
661 #undef LEVEL
662
663     { NULL },
664 };
665
666 static const AVCodecDefault vaapi_encode_mpeg2_defaults[] = {
667     { "b",              "0"   },
668     { "bf",             "1"   },
669     { "g",              "120" },
670     { "i_qfactor",      "1"   },
671     { "i_qoffset",      "0"   },
672     { "b_qfactor",      "6/5" },
673     { "b_qoffset",      "0"   },
674     { "global_quality", "10"  },
675     { "qmin",           "-1"  },
676     { "qmax",           "-1"  },
677     { NULL },
678 };
679
680 static const AVClass vaapi_encode_mpeg2_class = {
681     .class_name = "mpeg2_vaapi",
682     .item_name  = av_default_item_name,
683     .option     = vaapi_encode_mpeg2_options,
684     .version    = LIBAVUTIL_VERSION_INT,
685 };
686
687 AVCodec ff_mpeg2_vaapi_encoder = {
688     .name           = "mpeg2_vaapi",
689     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-2 (VAAPI)"),
690     .type           = AVMEDIA_TYPE_VIDEO,
691     .id             = AV_CODEC_ID_MPEG2VIDEO,
692     .priv_data_size = sizeof(VAAPIEncodeMPEG2Context),
693     .init           = &vaapi_encode_mpeg2_init,
694     .encode2        = &ff_vaapi_encode2,
695     .close          = &vaapi_encode_mpeg2_close,
696     .priv_class     = &vaapi_encode_mpeg2_class,
697     .capabilities   = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HARDWARE,
698     .defaults       = vaapi_encode_mpeg2_defaults,
699     .pix_fmts = (const enum AVPixelFormat[]) {
700         AV_PIX_FMT_VAAPI,
701         AV_PIX_FMT_NONE,
702     },
703     .wrapper_name   = "vaapi",
704 };