File: vaapiencoder_vp8.cpp

package info (click to toggle)
libyami 1.3.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 4,152 kB
  • sloc: cpp: 44,247; ansic: 1,255; makefile: 728; lisp: 479; sh: 21; python: 19
file content (530 lines) | stat: -rwxr-xr-x 16,191 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
/*
 * Copyright (C) 2014-2016 Intel Corporation. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "vaapiencoder_vp8.h"
#include "common/scopedlogger.h"
#include "common/common_def.h"
#include "vaapi/vaapicontext.h"
#include "vaapi/vaapidisplay.h"
#include "vaapicodedbuffer.h"
#include "vaapiencpicture.h"
#include <algorithm>
#include <vector>

namespace YamiMediaCodec{

//golden, alter, last
#define MAX_REFERECNE_FRAME 3
#define VP8_DEFAULT_QP     40

class VaapiEncPictureVP8 : public VaapiEncPicture
{
public:
    VaapiEncPictureVP8(const ContextPtr& context, const SurfacePtr& surface,
                       int64_t timeStamp)
        : VaapiEncPicture(context, surface, timeStamp)
    {
        return;
    }

    VAGenericID getCodedBufferID()
    {
        return m_codedBuffer->getID();
    }
};

struct RefFlags
{
    /* exactly same things in VAEncPictureParameterBufferVP8 */
    uint32_t refresh_golden_frame           : 1;
    uint32_t refresh_alternate_frame        : 1;
    uint32_t refresh_last                   : 1;
    uint32_t copy_buffer_to_golden          : 2;
    uint32_t copy_buffer_to_alternate       : 2;
    uint32_t no_ref_last                    : 1;
    uint32_t no_ref_gf                      : 1;
    uint32_t no_ref_arf                     : 1;

    RefFlags()
    {
        memset(this, 0, sizeof(RefFlags));

    }
};

class Vp8Encoder {
public:
    virtual void getRefFlags(RefFlags&, uint8_t temporalLayer) = 0;
    virtual void getLayerIds(LayerIDs& ids) const = 0;
    virtual bool getErrorResilient() const = 0;
    virtual bool getRefreshEntropyProbs() const = 0;
    virtual uint8_t getTemporalLayer(uint32_t frameNum) const = 0;
    virtual uint8_t getLayerNum() const = 0;
    virtual void getLayerFrameRates(LayerFrameRates& frameRates) const = 0;
    virtual void resetRefNum() = 0;
    virtual ~Vp8Encoder() {}
};

class Vp8EncoderNormal : public Vp8Encoder {
public:
    void getRefFlags(RefFlags&, uint8_t temporalLayer);
    void getLayerIds(LayerIDs& ids) const { ASSERT(0 && "not suppose call this"); }
    bool getErrorResilient() const { return false; }
    bool getRefreshEntropyProbs() const { return false; }
    uint8_t getTemporalLayer(uint32_t frameNum) const { return 0; }
    uint8_t getLayerNum() const { return 1; }
    void getLayerFrameRates(LayerFrameRates& frameRates) const { return; }
    void resetRefNum() { return; }
};

void Vp8EncoderNormal::getRefFlags(RefFlags& refFlags, uint8_t temporalLayer)
{
    refFlags.refresh_last = 1;
    refFlags.refresh_golden_frame = 0;
    refFlags.copy_buffer_to_golden = 1;
    refFlags.refresh_alternate_frame = 0;
    refFlags.copy_buffer_to_alternate = 2;

}
class Vp8EncoderSvct : public Vp8Encoder {
public:
    Vp8EncoderSvct(const VideoFrameRate& frameRate, const VideoTemporalLayerIDs& layerIDs, uint8_t layerIndex)
        : m_layerIndex(layerIndex % VP8_MAX_TEMPORAL_LAYER_NUM)
        , m_goldenRefreshed(false)
    {
        m_layerIDs.reset(new Vp8LayerID(frameRate, layerIDs, m_layerIndex));
    }
    void getRefFlags(RefFlags&, uint8_t temporalLayer);
    void getLayerIds(LayerIDs& ids) const;
    void getLayerFrameRates(LayerFrameRates& frameRates) const { return m_layerIDs->getLayerFrameRates(frameRates); }

    bool getErrorResilient() const { return true; }
    bool getRefreshEntropyProbs() const { return false; }
    uint8_t getTemporalLayer(uint32_t frameNum) const;
    uint8_t getLayerNum() const { return m_layerIDs->getLayerNum(); }
    void resetRefNum();

private:
    uint8_t m_layerIndex;
    bool m_goldenRefreshed;
    TemporalLayerIDPtr m_layerIDs;
};

void Vp8EncoderSvct::resetRefNum()
{
    m_goldenRefreshed = false;
}

uint8_t Vp8EncoderSvct::getTemporalLayer(uint32_t frameNum) const
{
    return m_layerIDs->getTemporalLayer(frameNum);
}

void Vp8EncoderSvct::getLayerIds(LayerIDs& ids) const
{
    m_layerIDs->getLayerIds(ids);
}

void Vp8EncoderSvct::getRefFlags(RefFlags& refFlags, uint8_t temporalLayer)
{
    refFlags.no_ref_arf = 1;
    switch (temporalLayer) {
    case 2:
        if (!m_goldenRefreshed)
            refFlags.no_ref_gf = 1;
        refFlags.refresh_alternate_frame = 1;
        //allow to drop the third layer's frames on terrible network condition,
        //so the third layer's frames don't reference to each other.
        break;
    case 1:
        if (!m_goldenRefreshed)
            refFlags.no_ref_gf = 1;
        refFlags.refresh_golden_frame = 1;
        m_goldenRefreshed = true;
        break;
    case 0:
        refFlags.refresh_last = 1;
        refFlags.no_ref_gf = 1;
        break;
    default:
        ERROR("temporal layer %d is out of the range[0, 2].", temporalLayer);
        break;
    }
}

VaapiEncoderVP8::VaapiEncoderVP8():
	m_frameCount(0),
	m_qIndex(VP8_DEFAULT_QP)
{
    m_videoParamCommon.profile = VAProfileVP8Version0_3;
    m_videoParamCommon.rcParams.minQP = 9;
    m_videoParamCommon.rcParams.maxQP = 127;
    m_videoParamCommon.rcParams.initQP = VP8_DEFAULT_QP;
}

VaapiEncoderVP8::~VaapiEncoderVP8()
{
}

YamiStatus VaapiEncoderVP8::getMaxOutSize(uint32_t* maxSize)
{
    FUNC_ENTER();
    *maxSize = m_maxCodedbufSize;
    return YAMI_SUCCESS;
}

//if the context is very complex and the quantization value is very small,
//the coded slice data will be very close to the limitation value width() * height() * 3 / 2.
//And the coded bitstream (slice_data + frame headers) will more than width() * height() * 3 / 2.
//so we add VP8_HEADER_MAX_SIZE to m_maxCodedbufSize to make sure it's not overflow.
#define VP8_HEADER_MAX_SIZE 0x4000

void VaapiEncoderVP8::resetParams()
{
    m_maxCodedbufSize = width() * height() * 3 / 2 + VP8_HEADER_MAX_SIZE;
    if (ipPeriod() == 0)
        m_videoParamCommon.intraPeriod = 1;

    VideoFrameRate frameRate;
    frameRate.frameRateDenom = frameRateDenom();
    frameRate.frameRateNum = frameRateNum();
    uint8_t layerIndex = m_videoParamCommon.temporalLayers.numLayersMinus1;
    if (layerIndex > 0) {
#ifndef __ENABLE_VP8_SVCT__
        assert(0 && "Please enable --enable-vp8svct during compilation!");
#endif
        m_encoder.reset(new Vp8EncoderSvct(frameRate, m_videoParamCommon.temporalLayerIDs, layerIndex));
        m_encoder->getLayerFrameRates(m_svctFrameRate);
        assert((layerIndex + 1) == m_encoder->getLayerNum());
    }
    else {
        m_encoder.reset(new Vp8EncoderNormal());
    }
}

YamiStatus VaapiEncoderVP8::start()
{
    FUNC_ENTER();
    resetParams();
    return VaapiEncoderBase::start();
}

void VaapiEncoderVP8::flush()
{
    FUNC_ENTER();
    m_frameCount = 0;
    m_last.reset();
    m_golden.reset();
    m_alt.reset();
    VaapiEncoderBase::flush();
}

YamiStatus VaapiEncoderVP8::stop()
{
    flush();
    return VaapiEncoderBase::stop();
}

YamiStatus VaapiEncoderVP8::setParameters(VideoParamConfigType type, Yami_PTR videoEncParams)
{
    YamiStatus status = YAMI_SUCCESS;
    FUNC_ENTER();
    if (!videoEncParams)
        return YAMI_INVALID_PARAM;

    switch (type) {
    default:
        status = VaapiEncoderBase::setParameters(type, videoEncParams);
        break;
    }
    return status;
}

YamiStatus VaapiEncoderVP8::getParameters(VideoParamConfigType type, Yami_PTR videoEncParams)
{
    FUNC_ENTER();
    if (!videoEncParams)
        return YAMI_INVALID_PARAM;

    // TODO, update video resolution basing on hw requirement
    return VaapiEncoderBase::getParameters(type, videoEncParams);
}

YamiStatus VaapiEncoderVP8::doEncode(const SurfacePtr& surface, uint64_t timeStamp, bool forceKeyFrame)
{
    YamiStatus ret;
    if (!surface)
        return YAMI_INVALID_PARAM;

    PicturePtr picture(new VaapiEncPictureVP8(m_context, surface, timeStamp));

    if (!(m_frameCount % keyFramePeriod()) || forceKeyFrame)
        picture->m_type = VAAPI_PICTURE_I;
    else
        picture->m_type = VAAPI_PICTURE_P;

    picture->m_temporalID = m_encoder->getTemporalLayer(m_frameCount % keyFramePeriod());
    m_frameCount++;

    m_qIndex = (initQP() > minQP() && initQP() < maxQP()) ? initQP() : VP8_DEFAULT_QP;

    CodedBufferPtr codedBuffer = VaapiCodedBuffer::create(m_context, m_maxCodedbufSize);
    if (!codedBuffer)
        return YAMI_OUT_MEMORY;
    picture->m_codedBuffer = codedBuffer;
    codedBuffer->setFlag(ENCODE_BUFFERFLAG_ENDOFFRAME);
    INFO("picture->m_type: 0x%x\n", picture->m_type);
    if (picture->m_type == VAAPI_PICTURE_I) {
        codedBuffer->setFlag(ENCODE_BUFFERFLAG_SYNCFRAME);
    }
    ret = encodePicture(picture);
    if (ret != YAMI_SUCCESS) {
        return ret;
    }
    output(picture);
    return YAMI_SUCCESS;
}


bool VaapiEncoderVP8::fill(VAEncSequenceParameterBufferVP8* seqParam) const
{
    seqParam->frame_width = width();
    seqParam->frame_height = height();
    seqParam->bits_per_second = bitRate();
    seqParam->intra_period = intraPeriod();
    seqParam->error_resilient = m_encoder->getErrorResilient();
    return true;
}

void VaapiEncoderVP8::fill(VAEncPictureParameterBufferVP8* picParam, const RefFlags& refFlags) const
{
    picParam->pic_flags.bits.refresh_golden_frame = refFlags.refresh_golden_frame;
    picParam->pic_flags.bits.refresh_alternate_frame = refFlags.refresh_alternate_frame;
    picParam->pic_flags.bits.refresh_last = refFlags.refresh_last;
    picParam->pic_flags.bits.copy_buffer_to_golden = refFlags.copy_buffer_to_golden;
    picParam->pic_flags.bits.copy_buffer_to_alternate = refFlags.copy_buffer_to_alternate;

#ifdef __ENABLE_VP8_SVCT__
    picParam->ref_flags.bits.no_ref_last = refFlags.no_ref_last;
    picParam->ref_flags.bits.no_ref_gf = refFlags.no_ref_gf;
    picParam->ref_flags.bits.no_ref_arf = refFlags.no_ref_arf;
    if (!picParam->ref_flags.bits.no_ref_last)
        picParam->ref_flags.bits.first_ref = 0x01;
    if (!picParam->ref_flags.bits.no_ref_gf)
        picParam->ref_flags.bits.second_ref = 0x02;
#endif
}

/* Fills in VA picture parameter buffer */
bool VaapiEncoderVP8::fill(VAEncPictureParameterBufferVP8* picParam, const PicturePtr& picture,
                            const SurfacePtr& surface, RefFlags& refFlags) const
{
    picParam->reconstructed_frame = surface->getID();
    picParam->ref_last_frame = VA_INVALID_SURFACE;
    picParam->ref_gf_frame = VA_INVALID_SURFACE;
    picParam->ref_arf_frame = VA_INVALID_SURFACE;

    if (picture->m_type == VAAPI_PICTURE_P) {
        picParam->pic_flags.bits.frame_type = 1;
        m_encoder->getRefFlags(refFlags, picture->m_temporalID);
        if (!refFlags.no_ref_arf)
            picParam->ref_arf_frame = m_alt->getID();
        if (!refFlags.no_ref_gf)
            picParam->ref_gf_frame = m_golden->getID();
        if (!refFlags.no_ref_last)
            picParam->ref_last_frame = m_last->getID();

        fill(picParam, refFlags);
    }
    else {
        m_encoder->resetRefNum();
    }

    picParam->coded_buf = picture->getCodedBufferID();
#ifdef __ENABLE_VP8_SVCT__
    picParam->ref_flags.bits.temporal_id = picture->m_temporalID;
#endif

    picParam->pic_flags.bits.show_frame = 1;
    /*TODO: multi partition*/
    picParam->pic_flags.bits.num_token_partitions = 0;
    //REMOVE THIS
    picParam->pic_flags.bits.refresh_entropy_probs = 0;
    /*pic_flags end */
    for (int i = 0; i < 4; i++) {
        picParam->loop_filter_level[i] = 19;
    }

    picParam->clamp_qindex_low = minQP();
    picParam->clamp_qindex_high = maxQP();
    return TRUE;
}

bool VaapiEncoderVP8::fill(VAQMatrixBufferVP8* qMatrix) const
{
    size_t i;

    for (i = 0; i < N_ELEMENTS(qMatrix->quantization_index); i++) {
        qMatrix->quantization_index[i] = m_qIndex;
    }

    for (i = 0; i < N_ELEMENTS(qMatrix->quantization_index_delta); i++) {
        qMatrix->quantization_index_delta[i] = 0;
    }

    return true;
}


bool VaapiEncoderVP8::ensureSequence(const PicturePtr& picture)
{
    if (picture->m_type != VAAPI_PICTURE_I)
        return true;

    VAEncSequenceParameterBufferVP8* seqParam;
    if (!picture->editSequence(seqParam) || !fill(seqParam)) {
        ERROR("failed to create sequence parameter buffer (SPS)");
        return false;
    }
    return true;
}

bool VaapiEncoderVP8::ensurePicture (const PicturePtr& picture,
                                     const SurfacePtr& surface,
                                     RefFlags& refFlags)
{
    VAEncPictureParameterBufferVP8 *picParam;

    if (!picture->editPicture(picParam) || !fill(picParam, picture, surface, refFlags)) {
        ERROR("failed to create picture parameter buffer (PPS)");
        return false;
    }
    return true;
}

bool VaapiEncoderVP8::ensureQMatrix (const PicturePtr& picture)
{
    VAQMatrixBufferVP8 *qMatrix;

    if (!picture->editQMatrix(qMatrix) || !fill(qMatrix)) {
        ERROR("failed to create qMatrix");
        return false;
    }
    return true;
}

/* Section 9.7 */
const SurfacePtr& VaapiEncoderVP8::referenceUpdate(
    const SurfacePtr& to, const SurfacePtr& from,
    const SurfacePtr& recon, bool refresh, uint32_t copy) const
{
    if (refresh)
        return recon;
    switch (copy) {
        case 0:
            return to;
        case 1:
            return m_last;
        case 2:
            return from;
        default:
            ASSERT(0 && "invalid copy to flags");
            return to;
    }

}

bool VaapiEncoderVP8::referenceListUpdate (const PicturePtr& pic, const SurfacePtr& recon, const RefFlags& refFlags)
{
    if (VAAPI_PICTURE_I == pic->m_type) {
        m_last = recon;
        m_golden = recon;
        m_alt = recon;
    }
    else {
        /* 9.7 and 9.8 */
        m_golden = referenceUpdate(m_golden, m_alt, recon,
            refFlags.refresh_golden_frame, refFlags.copy_buffer_to_golden);
        m_alt = referenceUpdate(m_alt, m_golden, recon,
            refFlags.refresh_alternate_frame, refFlags.copy_buffer_to_alternate);
        if (refFlags.refresh_last)
            m_last = recon;
    }
    return true;
}
/* Generates additional control parameters */
bool VaapiEncoderVP8::ensureMiscParams(VaapiEncPicture* picture)
{
    VideoRateControl mode = rateControlMode();
    if (mode == RATE_CONTROL_CBR || mode == RATE_CONTROL_VBR) {
        if (m_videoParamCommon.temporalLayers.numLayersMinus1 > 0) {
            VAEncMiscParameterTemporalLayerStructure* layerParam = NULL;
            if (!picture->newMisc(VAEncMiscParameterTypeTemporalLayerStructure,
                    layerParam))
                return false;

            LayerIDs ids;
            m_encoder->getLayerIds(ids);
            if (layerParam) {
                layerParam->number_of_layers = m_videoParamCommon.temporalLayers.numLayersMinus1 + 1;
                layerParam->periodicity = ids.size();
                for (uint32_t i = 1; i < layerParam->periodicity; i++)
                    layerParam->layer_id[i - 1] = ids[i];
                layerParam->layer_id[layerParam->periodicity - 1] = ids[0];
            }
        }
    }

    if (!VaapiEncoderBase::ensureMiscParams(picture))
        return false;

    return true;
}

YamiStatus VaapiEncoderVP8::encodePicture(const PicturePtr& picture)
{
    YamiStatus ret = YAMI_FAIL;
    SurfacePtr reconstruct = createSurface();
    if (!reconstruct)
        return ret;

    if (!ensureSequence (picture))
        return ret;

    if (!ensureMiscParams (picture.get()))
        return ret;

    RefFlags refFlags;
    if (!ensurePicture(picture, reconstruct, refFlags))
        return ret;

    if (!ensureQMatrix(picture))
        return ret;

    if (!picture->encode())
        return ret;

    if (!referenceListUpdate(picture, reconstruct, refFlags))
        return ret;

    return YAMI_SUCCESS;
}

}