Merge commit 'e60a6e7545dd6f5b25e3a65de9c6fdcc6e2e9d6b'
[ffmpeg.git] / libavcodec / dxva2_mpeg2.c
1 /*
2  * MPEG-2 HW acceleration.
3  *
4  * copyright (c) 2010 Laurent Aimar
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include "libavutil/log.h"
24 #include "dxva2_internal.h"
25 #include "mpegutils.h"
26 #include "mpegvideo.h"
27
28 #define MAX_SLICES 1024
29 struct dxva2_picture_context {
30     DXVA_PictureParameters pp;
31     DXVA_QmatrixData       qm;
32     unsigned               slice_count;
33     DXVA_SliceInfo         slice[MAX_SLICES];
34
35     const uint8_t          *bitstream;
36     unsigned               bitstream_size;
37 };
38
39 static void fill_picture_parameters(AVCodecContext *avctx,
40                                     AVDXVAContext *ctx,
41                                     const struct MpegEncContext *s,
42                                     DXVA_PictureParameters *pp)
43 {
44     const Picture *current_picture = s->current_picture_ptr;
45     int is_field = s->picture_structure != PICT_FRAME;
46
47     memset(pp, 0, sizeof(*pp));
48     pp->wDecodedPictureIndex         = ff_dxva2_get_surface_index(avctx, ctx, current_picture->f);
49     pp->wDeblockedPictureIndex       = 0;
50     if (s->pict_type != AV_PICTURE_TYPE_I)
51         pp->wForwardRefPictureIndex  = ff_dxva2_get_surface_index(avctx, ctx, s->last_picture.f);
52     else
53         pp->wForwardRefPictureIndex  = 0xffff;
54     if (s->pict_type == AV_PICTURE_TYPE_B)
55         pp->wBackwardRefPictureIndex = ff_dxva2_get_surface_index(avctx, ctx, s->next_picture.f);
56     else
57         pp->wBackwardRefPictureIndex = 0xffff;
58     pp->wPicWidthInMBminus1          = s->mb_width  - 1;
59     pp->wPicHeightInMBminus1         = (s->mb_height >> is_field) - 1;
60     pp->bMacroblockWidthMinus1       = 15;
61     pp->bMacroblockHeightMinus1      = 15;
62     pp->bBlockWidthMinus1            = 7;
63     pp->bBlockHeightMinus1           = 7;
64     pp->bBPPminus1                   = 7;
65     pp->bPicStructure                = s->picture_structure;
66     pp->bSecondField                 = is_field && !s->first_field;
67     pp->bPicIntra                    = s->pict_type == AV_PICTURE_TYPE_I;
68     pp->bPicBackwardPrediction       = s->pict_type == AV_PICTURE_TYPE_B;
69     pp->bBidirectionalAveragingMode  = 0;
70     pp->bMVprecisionAndChromaRelation= 0; /* FIXME */
71     pp->bChromaFormat                = s->chroma_format;
72     pp->bPicScanFixed                = 1;
73     pp->bPicScanMethod               = s->alternate_scan ? 1 : 0;
74     pp->bPicReadbackRequests         = 0;
75     pp->bRcontrol                    = 0;
76     pp->bPicSpatialResid8            = 0;
77     pp->bPicOverflowBlocks           = 0;
78     pp->bPicExtrapolation            = 0;
79     pp->bPicDeblocked                = 0;
80     pp->bPicDeblockConfined          = 0;
81     pp->bPic4MVallowed               = 0;
82     pp->bPicOBMC                     = 0;
83     pp->bPicBinPB                    = 0;
84     pp->bMV_RPS                      = 0;
85     pp->bReservedBits                = 0;
86     pp->wBitstreamFcodes             = (s->mpeg_f_code[0][0] << 12) |
87                                        (s->mpeg_f_code[0][1] <<  8) |
88                                        (s->mpeg_f_code[1][0] <<  4) |
89                                        (s->mpeg_f_code[1][1]      );
90     pp->wBitstreamPCEelements        = (s->intra_dc_precision         << 14) |
91                                        (s->picture_structure          << 12) |
92                                        (s->top_field_first            << 11) |
93                                        (s->frame_pred_frame_dct       << 10) |
94                                        (s->concealment_motion_vectors <<  9) |
95                                        (s->q_scale_type               <<  8) |
96                                        (s->intra_vlc_format           <<  7) |
97                                        (s->alternate_scan             <<  6) |
98                                        (s->repeat_first_field         <<  5) |
99                                        (s->chroma_420_type            <<  4) |
100                                        (s->progressive_frame          <<  3);
101     pp->bBitstreamConcealmentNeed    = 0;
102     pp->bBitstreamConcealmentMethod  = 0;
103 }
104
105 static void fill_quantization_matrices(AVCodecContext *avctx,
106                                        AVDXVAContext *ctx,
107                                        const struct MpegEncContext *s,
108                                        DXVA_QmatrixData *qm)
109 {
110     int i;
111     for (i = 0; i < 4; i++)
112         qm->bNewQmatrix[i] = 1;
113     for (i = 0; i < 64; i++) {
114         int n = s->idsp.idct_permutation[ff_zigzag_direct[i]];
115         qm->Qmatrix[0][i] = s->intra_matrix[n];
116         qm->Qmatrix[1][i] = s->inter_matrix[n];
117         qm->Qmatrix[2][i] = s->chroma_intra_matrix[n];
118         qm->Qmatrix[3][i] = s->chroma_inter_matrix[n];
119     }
120 }
121
122 static void fill_slice(AVCodecContext *avctx,
123                        const struct MpegEncContext *s,
124                        DXVA_SliceInfo *slice,
125                        unsigned position,
126                        const uint8_t *buffer, unsigned size)
127 {
128     int is_field = s->picture_structure != PICT_FRAME;
129     GetBitContext gb;
130
131     memset(slice, 0, sizeof(*slice));
132     slice->wHorizontalPosition = s->mb_x;
133     slice->wVerticalPosition   = s->mb_y >> is_field;
134     slice->dwSliceBitsInBuffer = 8 * size;
135     slice->dwSliceDataLocation = position;
136     slice->bStartCodeBitOffset = 0;
137     slice->bReservedBits       = 0;
138     /* XXX We store the index of the first MB and it will be fixed later */
139     slice->wNumberMBsInSlice   = (s->mb_y >> is_field) * s->mb_width + s->mb_x;
140     slice->wBadSliceChopping   = 0;
141
142     init_get_bits(&gb, &buffer[4], 8 * (size - 4));
143
144     slice->wQuantizerScaleCode = get_bits(&gb, 5);
145     skip_1stop_8data_bits(&gb);
146
147     slice->wMBbitOffset        = 4 * 8 + get_bits_count(&gb);
148 }
149 static int commit_bitstream_and_slice_buffer(AVCodecContext *avctx,
150                                              DECODER_BUFFER_DESC *bs,
151                                              DECODER_BUFFER_DESC *sc)
152 {
153     const struct MpegEncContext *s = avctx->priv_data;
154     AVDXVAContext *ctx = avctx->hwaccel_context;
155     struct dxva2_picture_context *ctx_pic =
156         s->current_picture_ptr->hwaccel_picture_private;
157     const int is_field = s->picture_structure != PICT_FRAME;
158     const unsigned mb_count = s->mb_width * (s->mb_height >> is_field);
159     void     *dxva_data_ptr;
160     uint8_t  *dxva_data, *current, *end;
161     unsigned dxva_size;
162     unsigned i;
163     unsigned type;
164
165 #if CONFIG_D3D11VA
166     if (avctx->pix_fmt == AV_PIX_FMT_D3D11VA_VLD) {
167         type = D3D11_VIDEO_DECODER_BUFFER_BITSTREAM;
168         if (FAILED(ID3D11VideoContext_GetDecoderBuffer(D3D11VA_CONTEXT(ctx)->video_context,
169                                                        D3D11VA_CONTEXT(ctx)->decoder,
170                                                        type,
171                                                        &dxva_size, &dxva_data_ptr)))
172             return -1;
173     }
174 #endif
175 #if CONFIG_DXVA2
176     if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD) {
177         type = DXVA2_BitStreamDateBufferType;
178         if (FAILED(IDirectXVideoDecoder_GetBuffer(DXVA2_CONTEXT(ctx)->decoder,
179                                                   type,
180                                                   &dxva_data_ptr, &dxva_size)))
181             return -1;
182     }
183 #endif
184
185     dxva_data = dxva_data_ptr;
186     current = dxva_data;
187     end = dxva_data + dxva_size;
188
189     for (i = 0; i < ctx_pic->slice_count; i++) {
190         DXVA_SliceInfo *slice = &ctx_pic->slice[i];
191         unsigned position = slice->dwSliceDataLocation;
192         unsigned size     = slice->dwSliceBitsInBuffer / 8;
193         if (size > end - current) {
194             av_log(avctx, AV_LOG_ERROR, "Failed to build bitstream");
195             break;
196         }
197         slice->dwSliceDataLocation = current - dxva_data;
198
199         if (i < ctx_pic->slice_count - 1)
200             slice->wNumberMBsInSlice =
201                 slice[1].wNumberMBsInSlice - slice[0].wNumberMBsInSlice;
202         else
203             slice->wNumberMBsInSlice =
204                 mb_count - slice[0].wNumberMBsInSlice;
205
206         memcpy(current, &ctx_pic->bitstream[position], size);
207         current += size;
208     }
209 #if CONFIG_D3D11VA
210     if (avctx->pix_fmt == AV_PIX_FMT_D3D11VA_VLD)
211         if (FAILED(ID3D11VideoContext_ReleaseDecoderBuffer(D3D11VA_CONTEXT(ctx)->video_context, D3D11VA_CONTEXT(ctx)->decoder, type)))
212             return -1;
213 #endif
214 #if CONFIG_DXVA2
215     if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD)
216         if (FAILED(IDirectXVideoDecoder_ReleaseBuffer(DXVA2_CONTEXT(ctx)->decoder, type)))
217             return -1;
218 #endif
219     if (i < ctx_pic->slice_count)
220         return -1;
221
222 #if CONFIG_D3D11VA
223     if (avctx->pix_fmt == AV_PIX_FMT_D3D11VA_VLD) {
224         D3D11_VIDEO_DECODER_BUFFER_DESC *dsc11 = bs;
225         memset(dsc11, 0, sizeof(*dsc11));
226         dsc11->BufferType           = type;
227         dsc11->DataSize             = current - dxva_data;
228         dsc11->NumMBsInBuffer       = mb_count;
229
230         type = D3D11_VIDEO_DECODER_BUFFER_SLICE_CONTROL;
231     }
232 #endif
233 #if CONFIG_DXVA2
234     if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD) {
235         DXVA2_DecodeBufferDesc *dsc2 = bs;
236         memset(dsc2, 0, sizeof(*dsc2));
237         dsc2->CompressedBufferType = type;
238         dsc2->DataSize             = current - dxva_data;
239         dsc2->NumMBsInBuffer       = mb_count;
240
241         type = DXVA2_SliceControlBufferType;
242     }
243 #endif
244
245     return ff_dxva2_commit_buffer(avctx, ctx, sc,
246                                   type,
247                                   ctx_pic->slice,
248                                   ctx_pic->slice_count * sizeof(*ctx_pic->slice),
249                                   mb_count);
250 }
251
252 static int dxva2_mpeg2_start_frame(AVCodecContext *avctx,
253                                    av_unused const uint8_t *buffer,
254                                    av_unused uint32_t size)
255 {
256     const struct MpegEncContext *s = avctx->priv_data;
257     AVDXVAContext *ctx = avctx->hwaccel_context;
258     struct dxva2_picture_context *ctx_pic =
259         s->current_picture_ptr->hwaccel_picture_private;
260
261     if (DXVA_CONTEXT_DECODER(avctx, ctx) == NULL ||
262         DXVA_CONTEXT_CFG(avctx, ctx) == NULL ||
263         DXVA_CONTEXT_COUNT(avctx, ctx) <= 0)
264         return -1;
265     assert(ctx_pic);
266
267     fill_picture_parameters(avctx, ctx, s, &ctx_pic->pp);
268     fill_quantization_matrices(avctx, ctx, s, &ctx_pic->qm);
269
270     ctx_pic->slice_count    = 0;
271     ctx_pic->bitstream_size = 0;
272     ctx_pic->bitstream      = NULL;
273     return 0;
274 }
275
276 static int dxva2_mpeg2_decode_slice(AVCodecContext *avctx,
277                                     const uint8_t *buffer, uint32_t size)
278 {
279     const struct MpegEncContext *s = avctx->priv_data;
280     struct dxva2_picture_context *ctx_pic =
281         s->current_picture_ptr->hwaccel_picture_private;
282     unsigned position;
283
284     if (ctx_pic->slice_count >= MAX_SLICES) {
285         avpriv_request_sample(avctx, "%d slices in dxva2",
286                               ctx_pic->slice_count);
287         return -1;
288     }
289     if (!ctx_pic->bitstream)
290         ctx_pic->bitstream = buffer;
291     ctx_pic->bitstream_size += size;
292
293     position = buffer - ctx_pic->bitstream;
294     fill_slice(avctx, s, &ctx_pic->slice[ctx_pic->slice_count++], position,
295                buffer, size);
296     return 0;
297 }
298
299 static int dxva2_mpeg2_end_frame(AVCodecContext *avctx)
300 {
301     struct MpegEncContext *s = avctx->priv_data;
302     struct dxva2_picture_context *ctx_pic =
303         s->current_picture_ptr->hwaccel_picture_private;
304     int ret;
305
306     if (ctx_pic->slice_count <= 0 || ctx_pic->bitstream_size <= 0)
307         return -1;
308     ret = ff_dxva2_common_end_frame(avctx, s->current_picture_ptr->f,
309                                     &ctx_pic->pp, sizeof(ctx_pic->pp),
310                                     &ctx_pic->qm, sizeof(ctx_pic->qm),
311                                     commit_bitstream_and_slice_buffer);
312     if (!ret)
313         ff_mpeg_draw_horiz_band(s, 0, avctx->height);
314     return ret;
315 }
316
317 #if CONFIG_MPEG2_DXVA2_HWACCEL
318 AVHWAccel ff_mpeg2_dxva2_hwaccel = {
319     .name           = "mpeg2_dxva2",
320     .type           = AVMEDIA_TYPE_VIDEO,
321     .id             = AV_CODEC_ID_MPEG2VIDEO,
322     .pix_fmt        = AV_PIX_FMT_DXVA2_VLD,
323     .start_frame    = dxva2_mpeg2_start_frame,
324     .decode_slice   = dxva2_mpeg2_decode_slice,
325     .end_frame      = dxva2_mpeg2_end_frame,
326     .frame_priv_data_size = sizeof(struct dxva2_picture_context),
327 };
328 #endif
329
330 #if CONFIG_MPEG2_D3D11VA_HWACCEL
331 AVHWAccel ff_mpeg2_d3d11va_hwaccel = {
332     .name           = "mpeg2_d3d11va",
333     .type           = AVMEDIA_TYPE_VIDEO,
334     .id             = AV_CODEC_ID_MPEG2VIDEO,
335     .pix_fmt        = AV_PIX_FMT_D3D11VA_VLD,
336     .start_frame    = dxva2_mpeg2_start_frame,
337     .decode_slice   = dxva2_mpeg2_decode_slice,
338     .end_frame      = dxva2_mpeg2_end_frame,
339     .frame_priv_data_size = sizeof(struct dxva2_picture_context),
340 };
341 #endif