This repository has been archived by the owner on May 17, 2023. It is now read-only.
/
pipeline_encode.cpp
2856 lines (2395 loc) · 98 KB
/
pipeline_encode.cpp
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************\
Copyright (c) 2005-2020, Intel Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This sample was distributed or derived from the Intel's Media Samples package.
The original version of this sample may be obtained from https://software.intel.com/en-us/intel-media-server-studio
or https://software.intel.com/en-us/media-client-solutions-support.
\**********************************************************************************/
#include "mfx_samples_config.h"
#include "pipeline_encode.h"
#include "sysmem_allocator.h"
#include "parameters_dumper.h"
#if D3D_SURFACES_SUPPORT
#include "d3d_allocator.h"
#include "d3d11_allocator.h"
#include "d3d_device.h"
#include "d3d11_device.h"
#endif
#ifdef LIBVA_SUPPORT
#include "vaapi_allocator.h"
#include "vaapi_device.h"
#endif
#include "plugin_loader.h"
#include "sample_utils.h"
#if defined (ENABLE_V4L2_SUPPORT)
#include <pthread.h>
#endif
#include "version.h"
#include <algorithm>
#ifndef MFX_VERSION
#error MFX_VERSION not defined
#endif
/* obtain the clock tick of an uninterrupted master clock */
msdk_tick time_get_tick(void)
{
return msdk_time_get_tick();
}
/* obtain the clock resolution */
msdk_tick time_get_frequency(void)
{
return msdk_time_get_frequency();
}
void LockPreEncAuxBuffer(PreEncAuxBuffer* pBuff)
{
if (!pBuff) return;
msdk_atomic_inc16(&pBuff->Locked);
}
void UnlockPreEncAuxBuffer(PreEncAuxBuffer* pBuff)
{
if (!pBuff) return;
msdk_atomic_dec16(&pBuff->Locked);
}
CEncTaskPool::CEncTaskPool()
{
m_pTasks = NULL;
m_pmfxSession = NULL;
m_nTaskBufferStart = 0;
m_nPoolSize = 0;
m_bGpuHangRecovery = false;
}
CEncTaskPool::~CEncTaskPool()
{
Close();
}
sTask::sTask()
: pAux(nullptr)
, EncSyncP(0)
, pWriter(NULL)
{
}
mfxStatus CEncTaskPool::Init(MFXVideoSession* pmfxSession, CSmplBitstreamWriter* pWriter, mfxU32 nPoolSize, mfxU32 nBufferSize, CSmplBitstreamWriter *pOtherWriter)
{
MSDK_CHECK_POINTER(pmfxSession, MFX_ERR_NULL_PTR);
MSDK_CHECK_ERROR(nPoolSize, 0, MFX_ERR_UNDEFINED_BEHAVIOR);
MSDK_CHECK_ERROR(nBufferSize, 0, MFX_ERR_UNDEFINED_BEHAVIOR);
// nPoolSize must be even in case of 2 output bitstreams
if (pOtherWriter && (0 != nPoolSize % 2))
return MFX_ERR_UNDEFINED_BEHAVIOR;
m_pmfxSession = pmfxSession;
m_nPoolSize = nPoolSize;
m_pTasks = new sTask [m_nPoolSize];
MSDK_CHECK_POINTER(m_pTasks, MFX_ERR_MEMORY_ALLOC);
mfxStatus sts = MFX_ERR_NONE;
if (pOtherWriter) // 2 bitstreams on output
{
for (mfxU32 i = 0; i < m_nPoolSize; i+=2)
{
sts = m_pTasks[i+0].Init(nBufferSize, pWriter);
sts = m_pTasks[i+1].Init(nBufferSize, pOtherWriter);
MSDK_CHECK_STATUS(sts, "m_pTasks[i+1].Init failed");
}
}
else
{
for (mfxU32 i = 0; i < m_nPoolSize; i++)
{
sts = m_pTasks[i].Init(nBufferSize, pWriter);
MSDK_CHECK_STATUS(sts, "m_pTasks[i].Init failed");
}
}
return MFX_ERR_NONE;
}
mfxStatus CEncTaskPool::SynchronizeFirstTask()
{
m_statOverall.StartTimeMeasurement();
MSDK_CHECK_POINTER(m_pTasks, MFX_ERR_NOT_INITIALIZED);
MSDK_CHECK_POINTER(m_pmfxSession, MFX_ERR_NOT_INITIALIZED);
mfxStatus sts = MFX_ERR_NONE;
bool bGpuHang = false;
// non-null sync point indicates that task is in execution
if (NULL != m_pTasks[m_nTaskBufferStart].EncSyncP)
{
sts = m_pmfxSession->SyncOperation(m_pTasks[m_nTaskBufferStart].EncSyncP, MSDK_WAIT_INTERVAL);
if (sts == MFX_ERR_GPU_HANG && m_bGpuHangRecovery)
{
bGpuHang = true;
{
for (mfxU32 i = 0; i < m_nPoolSize; i++)
if (m_pTasks[i].EncSyncP != NULL)
{
sts = m_pmfxSession->SyncOperation(m_pTasks[i].EncSyncP, 0);//MSDK_WAIT_INTERVAL
}
}
ClearTasks();
sts = MFX_ERR_NONE;
msdk_printf(MSDK_STRING("GPU hang happened\n"));
}
MSDK_CHECK_STATUS_NO_RET(sts, "SyncOperation failed");
if (MFX_ERR_NONE == sts)
{
m_statFile.StartTimeMeasurement();
sts = m_pTasks[m_nTaskBufferStart].WriteBitstream();
m_statFile.StopTimeMeasurement();
MSDK_CHECK_STATUS(sts, "m_pTasks[m_nTaskBufferStart].WriteBitstream failed");
sts = m_pTasks[m_nTaskBufferStart].Reset();
MSDK_CHECK_STATUS(sts, "m_pTasks[m_nTaskBufferStart].Reset failed");
if(m_pTasks[m_nTaskBufferStart].pAux)
{
UnlockPreEncAuxBuffer(m_pTasks[m_nTaskBufferStart].pAux);
}
// move task buffer start to the next executing task
// the first transform frame to the right with non zero sync point
for (mfxU32 i = 0; i < m_nPoolSize; i++)
{
m_nTaskBufferStart = (m_nTaskBufferStart + 1) % m_nPoolSize;
if (NULL != m_pTasks[m_nTaskBufferStart].EncSyncP)
{
break;
}
}
}
else if (MFX_ERR_ABORTED == sts)
{
while (!m_pTasks[m_nTaskBufferStart].DependentVppTasks.empty())
{
// find out if the error occurred in a VPP task to perform recovery procedure if applicable
sts = m_pmfxSession->SyncOperation(*m_pTasks[m_nTaskBufferStart].DependentVppTasks.begin(), 0);
if (sts == MFX_ERR_GPU_HANG && m_bGpuHangRecovery)
{
bGpuHang = true;
ClearTasks();
sts = MFX_ERR_NONE;
msdk_printf(MSDK_STRING("GPU hang happened\n"));
}
if (MFX_ERR_NONE == sts)
{
m_pTasks[m_nTaskBufferStart].DependentVppTasks.pop_front();
sts = MFX_ERR_ABORTED; // save the status of the encode task
continue; // go to next vpp task
}
else
{
break;
}
}
}
}
else
{
sts = MFX_ERR_NOT_FOUND; // no tasks left in task buffer
}
m_statOverall.StopTimeMeasurement();
return bGpuHang ? MFX_ERR_GPU_HANG : sts;
}
mfxU32 CEncTaskPool::GetFreeTaskIndex()
{
mfxU32 off = 0;
if (m_pTasks)
{
for (off = 0; off < m_nPoolSize; off++)
{
if (NULL == m_pTasks[(m_nTaskBufferStart + off) % m_nPoolSize].EncSyncP)
{
break;
}
}
}
if (off >= m_nPoolSize)
return m_nPoolSize;
return (m_nTaskBufferStart + off) % m_nPoolSize;
}
mfxStatus CEncTaskPool::GetFreeTask(sTask **ppTask)
{
MSDK_CHECK_POINTER(ppTask, MFX_ERR_NULL_PTR);
MSDK_CHECK_POINTER(m_pTasks, MFX_ERR_NOT_INITIALIZED);
mfxU32 index = GetFreeTaskIndex();
if (index >= m_nPoolSize)
{
return MFX_ERR_NOT_FOUND;
}
// return the address of the task
*ppTask = &m_pTasks[index];
return MFX_ERR_NONE;
}
void CEncTaskPool::Close()
{
if (m_pTasks)
{
for (mfxU32 i = 0; i < m_nPoolSize; i++)
{
m_pTasks[i].Close();
}
}
MSDK_SAFE_DELETE_ARRAY(m_pTasks);
m_pmfxSession = NULL;
m_nTaskBufferStart = 0;
m_nPoolSize = 0;
}
void CEncTaskPool::SetGpuHangRecoveryFlag()
{
m_bGpuHangRecovery = true;
}
void CEncTaskPool::ClearTasks()
{
for (size_t i = 0; i < m_nPoolSize; i++)
{
m_pTasks[i].Reset();
}
m_nTaskBufferStart = 0;
}
mfxStatus sTask::Init(mfxU32 nBufferSize, CSmplBitstreamWriter *pwriter)
{
Close();
pWriter = pwriter;
mfxStatus sts = Reset();
MSDK_CHECK_STATUS(sts, "Reset failed");
mfxBS.Extend(nBufferSize);
return sts;
}
mfxStatus sTask::Close()
{
EncSyncP = 0;
DependentVppTasks.clear();
return MFX_ERR_NONE;
}
mfxStatus sTask::WriteBitstream()
{
if (pWriter)
return pWriter->WriteNextFrame(&mfxBS);
else
return MFX_ERR_NONE;
}
mfxStatus sTask::Reset()
{
// mark sync point as free
EncSyncP = NULL;
// prepare bit stream
mfxBS.DataOffset = 0;
mfxBS.DataLength = 0;
DependentVppTasks.clear();
return MFX_ERR_NONE;
}
void CEncodingPipeline::InitExtMVCBuffers(mfxExtMVCSeqDesc *mvcBuffer) const
{
// a simple example of mfxExtMVCSeqDesc structure filling
// actually equal to the "Default dependency mode" - when the structure fields are left 0,
// but we show how to properly allocate and fill the fields
mfxU32 i;
// mfxMVCViewDependency array
mvcBuffer->NumView = m_nNumView;
mvcBuffer->NumViewAlloc = m_nNumView;
mvcBuffer->View = new mfxMVCViewDependency[mvcBuffer->NumViewAlloc];
for (i = 0; i < mvcBuffer->NumViewAlloc; ++i)
{
mvcBuffer->View[i] = {};
mvcBuffer->View[i].ViewId = (mfxU16) i; // set view number as view id
}
// set up dependency for second view
mvcBuffer->View[1].NumAnchorRefsL0 = 1;
mvcBuffer->View[1].AnchorRefL0[0] = 0; // ViewId 0 - base view
mvcBuffer->View[1].NumNonAnchorRefsL0 = 1;
mvcBuffer->View[1].NonAnchorRefL0[0] = 0; // ViewId 0 - base view
// viewId array
mvcBuffer->NumViewId = m_nNumView;
mvcBuffer->NumViewIdAlloc = m_nNumView;
mvcBuffer->ViewId = new mfxU16[mvcBuffer->NumViewIdAlloc];
for (i = 0; i < mvcBuffer->NumViewIdAlloc; ++i)
{
mvcBuffer->ViewId[i] = (mfxU16) i;
}
// create a single operation point containing all views
mvcBuffer->NumOP = 1;
mvcBuffer->NumOPAlloc = 1;
mvcBuffer->OP = new mfxMVCOperationPoint[mvcBuffer->NumOPAlloc];
for (i = 0; i < mvcBuffer->NumOPAlloc; ++i)
{
mvcBuffer->OP[i] = {};
mvcBuffer->OP[i].NumViews = (mfxU16) m_nNumView;
mvcBuffer->OP[i].NumTargetViews = (mfxU16) m_nNumView;
mvcBuffer->OP[i].TargetViewId = mvcBuffer->ViewId; // points to mfxExtMVCSeqDesc::ViewId
}
}
mfxStatus CEncodingPipeline::InitVppFilters()
{
auto vppExtParams = m_mfxVppParams.AddExtBuffer<mfxExtVPPDoNotUse>();
vppExtParams->NumAlg = 4;
if(vppExtParams->AlgList)
delete[] vppExtParams->AlgList;
vppExtParams->AlgList = new mfxU32 [vppExtParams->NumAlg];
vppExtParams->AlgList[0] = MFX_EXTBUFF_VPP_DENOISE; // turn off denoising (on by default)
vppExtParams->AlgList[1] = MFX_EXTBUFF_VPP_SCENE_ANALYSIS; // turn off scene analysis (on by default)
vppExtParams->AlgList[2] = MFX_EXTBUFF_VPP_DETAIL; // turn off detail enhancement (on by default)
vppExtParams->AlgList[3] = MFX_EXTBUFF_VPP_PROCAMP; // turn off processing amplified (on by default)
if(MVC_ENABLED & m_MVCflags)
{
auto mvcBuffer = m_mfxVppParams.AddExtBuffer<mfxExtMVCSeqDesc>();
InitExtMVCBuffers(mvcBuffer);
}
return MFX_ERR_NONE;
} // CEncodingPipeline::InitVppFilters()
void CEncodingPipeline::FreeVppFilters()
{
auto vppExtParams = m_mfxVppParams.GetExtBuffer<mfxExtVPPDoNotUse>();
if(vppExtParams)
MSDK_SAFE_DELETE_ARRAY(vppExtParams->AlgList);
}
void CEncodingPipeline::DeallocateExtMVCBuffers()
{
auto mvcBuffer = m_mfxEncParams.GetExtBuffer<mfxExtMVCSeqDesc>();
if(mvcBuffer)
{
MSDK_SAFE_DELETE_ARRAY(mvcBuffer->View);
MSDK_SAFE_DELETE_ARRAY(mvcBuffer->ViewId);
MSDK_SAFE_DELETE_ARRAY(mvcBuffer->OP);
}
}
PreEncAuxBuffer* CEncodingPipeline::GetFreePreEncAuxBuffer()
{
for(mfxU32 i = 0; i < m_PreEncAuxPool.size(); i++)
{
if (!m_PreEncAuxPool[i].Locked)
return &(m_PreEncAuxPool[i]);
}
return nullptr;
}
mfxStatus CEncodingPipeline::InitMfxPreEncParams(sInputParams *pInParams)
{
MSDK_CHECK_POINTER(pInParams, MFX_ERR_NULL_PTR);
MSDK_CHECK_ERROR(pInParams->bEnableExtLA, false, MFX_ERR_INVALID_VIDEO_PARAM);
m_mfxPreEncParams.mfx = {};
// Plugin needs AVC for init
m_mfxPreEncParams.mfx.CodecId = MFX_CODEC_AVC;
m_mfxPreEncParams.mfx.TargetUsage = pInParams->nTargetUsage;
m_mfxPreEncParams.mfx.FrameInfo = m_pmfxVPP ? m_mfxVppParams.vpp.Out : m_mfxEncParams.mfx.FrameInfo;
m_mfxPreEncParams.AsyncDepth = pInParams->nAsyncDepth;
m_mfxPreEncParams.IOPattern = m_mfxEncParams.IOPattern;
// configure and attach external parameters
auto laCtrl = m_mfxPreEncParams.AddExtBuffer<mfxExtLAControl>();
laCtrl->LookAheadDepth = pInParams->nLADepth ? pInParams->nLADepth : 40;
laCtrl->NumOutStream = 1;
laCtrl->OutStream[0].Width = m_mfxPreEncParams.mfx.FrameInfo.Width;
laCtrl->OutStream[0].Height = m_mfxPreEncParams.mfx.FrameInfo.Height;
m_mfxPreEncParams.mfx.GopPicSize = pInParams->nGopPicSize ? pInParams->nGopPicSize : 1500;
m_mfxPreEncParams.mfx.GopRefDist = pInParams->nGopRefDist;
m_mfxPreEncParams.mfx.TargetUsage = pInParams->nTargetUsage;
return MFX_ERR_NONE;
}
mfxStatus CEncodingPipeline::InitMfxEncParams(sInputParams *pInParams)
{
MSDK_CHECK_POINTER(pInParams, MFX_ERR_NULL_PTR);
m_mfxEncParams.mfx.CodecId = pInParams->CodecId;
m_mfxEncParams.mfx.TargetUsage = pInParams->nTargetUsage; // trade-off between quality and speed
m_mfxEncParams.mfx.RateControlMethod = pInParams->nRateControlMethod;
m_mfxEncParams.mfx.GopRefDist = pInParams->nGopRefDist;
m_mfxEncParams.mfx.GopPicSize = pInParams->nGopPicSize;
m_mfxEncParams.mfx.NumRefFrame = pInParams->nNumRefFrame;
m_mfxEncParams.mfx.IdrInterval = pInParams->nIdrInterval;
m_mfxEncParams.mfx.CodecProfile = pInParams->CodecProfile;
m_mfxEncParams.mfx.CodecLevel = pInParams->CodecLevel;
m_mfxEncParams.mfx.MaxKbps = (mfxU16)pInParams->MaxKbps;
m_mfxEncParams.mfx.InitialDelayInKB = (mfxU16)pInParams->InitialDelayInKB;
m_mfxEncParams.mfx.GopOptFlag = pInParams->GopOptFlag;
m_mfxEncParams.mfx.BufferSizeInKB = (mfxU16)pInParams->BufferSizeInKB;
m_mfxEncParams.mfx.BRCParamMultiplier = pInParams->nBitRateMultiplier;
if (m_mfxEncParams.mfx.RateControlMethod == MFX_RATECONTROL_CQP)
{
m_mfxEncParams.mfx.QPI = pInParams->nQPI;
m_mfxEncParams.mfx.QPP = pInParams->nQPP;
m_mfxEncParams.mfx.QPB = pInParams->nQPB;
}
else if (m_mfxEncParams.mfx.RateControlMethod == MFX_RATECONTROL_ICQ ||
m_mfxEncParams.mfx.RateControlMethod == MFX_RATECONTROL_LA_ICQ)
{
m_mfxEncParams.mfx.ICQQuality = pInParams->ICQQuality;
}
else if (m_mfxEncParams.mfx.RateControlMethod == MFX_RATECONTROL_AVBR)
{
m_mfxEncParams.mfx.Accuracy = pInParams->Accuracy;
m_mfxEncParams.mfx.TargetKbps = (mfxU16)pInParams->nBitRate;
m_mfxEncParams.mfx.Convergence = pInParams->Convergence;
}
else
{
m_mfxEncParams.mfx.TargetKbps = (mfxU16)pInParams->nBitRate; // in Kbps
}
if(pInParams->enableQSVFF)
{
m_mfxEncParams.mfx.LowPower = MFX_CODINGOPTION_ON;
}
m_mfxEncParams.mfx.NumSlice = pInParams->nNumSlice;
ConvertFrameRate(pInParams->dFrameRate, &m_mfxEncParams.mfx.FrameInfo.FrameRateExtN, &m_mfxEncParams.mfx.FrameInfo.FrameRateExtD);
m_bQPFileMode = pInParams->QPFileMode;
m_mfxEncParams.mfx.EncodedOrder = m_bQPFileMode || m_pmfxPreENC ? 1 : 0; // binary flag, 0 signals encoder to take frames in display order
if (m_bQPFileMode)
{
mfxStatus sts = m_QPFileReader.Read(pInParams->strQPFilePath, pInParams->CodecId);
MSDK_CHECK_STATUS(sts, m_QPFileReader.GetErrorMessage().c_str());
}
m_bTCBRCFileMode = pInParams->TCBRCFileMode;
if (m_bTCBRCFileMode)
{
mfxStatus sts = m_TCBRCFileReader.Read(pInParams->strTCBRCFilePath, pInParams->CodecId);
MSDK_CHECK_STATUS(sts, m_TCBRCFileReader.GetErrorMessage().c_str());
m_mfxEncParams.AsyncDepth = 1;
m_mfxEncParams.mfx.RateControlMethod = MFX_RATECONTROL_VBR;
m_mfxEncParams.mfx.GopRefDist = 1;
pInParams->nNalHrdConformance = MFX_CODINGOPTION_OFF;
pInParams->LowDelayBRC = MFX_CODINGOPTION_ON;
}
// specify memory type
if (D3D9_MEMORY == pInParams->memType || D3D11_MEMORY == pInParams->memType)
{
m_mfxEncParams.IOPattern = MFX_IOPATTERN_IN_VIDEO_MEMORY;
}
else
{
m_mfxEncParams.IOPattern = MFX_IOPATTERN_IN_SYSTEM_MEMORY;
}
// frame info parameters
m_mfxEncParams.mfx.FrameInfo.FourCC = pInParams->EncodeFourCC;
m_mfxEncParams.mfx.FrameInfo.ChromaFormat = FourCCToChroma(pInParams->EncodeFourCC);
m_mfxEncParams.mfx.FrameInfo.PicStruct = pInParams->nPicStruct;
m_mfxEncParams.mfx.FrameInfo.Shift = pInParams->shouldUseShifted10BitEnc;
// width must be a multiple of 16
// height must be a multiple of 16 in case of frame picture and a multiple of 32 in case of field picture
m_mfxEncParams.mfx.FrameInfo.Width = MSDK_ALIGN16(pInParams->nDstWidth);
m_mfxEncParams.mfx.FrameInfo.Height = (MFX_PICSTRUCT_PROGRESSIVE == m_mfxEncParams.mfx.FrameInfo.PicStruct)?
MSDK_ALIGN16(pInParams->nDstHeight) : MSDK_ALIGN32(pInParams->nDstHeight);
m_mfxEncParams.mfx.FrameInfo.CropX = 0;
m_mfxEncParams.mfx.FrameInfo.CropY = 0;
m_mfxEncParams.mfx.FrameInfo.CropW = pInParams->nDstWidth;
m_mfxEncParams.mfx.FrameInfo.CropH = pInParams->nDstHeight;
if (pInParams->nEncTileRows && pInParams->nEncTileCols)
{
if (m_mfxEncParams.mfx.CodecId == MFX_CODEC_HEVC)
{
auto hevcTiles = m_mfxEncParams.AddExtBuffer<mfxExtHEVCTiles>();
hevcTiles->NumTileRows = pInParams->nEncTileRows;
hevcTiles->NumTileColumns = pInParams->nEncTileCols;
}
#if (MFX_VERSION >= 1029)
else if (m_mfxEncParams.mfx.CodecId == MFX_CODEC_VP9)
{
auto vp9Param = m_mfxEncParams.AddExtBuffer<mfxExtVP9Param>();
vp9Param->NumTileRows = pInParams->nEncTileRows;
vp9Param->NumTileColumns = pInParams->nEncTileCols;
}
#endif
}
if (*pInParams->uSEI && (pInParams->CodecId == MFX_CODEC_AVC || pInParams->CodecId == MFX_CODEC_HEVC))
{
auto pl = new mfxPayload;
mfxU16 size = 0;
std::vector<mfxU8> data;
std::vector<mfxU8> uuid;
std::string msg;
mfxU16 type = 5; //user data unregister
pl->CtrlFlags = 0;
mfxU16 index = 0;
for(; index < 16; index++)
{
mfxU8 bt = Char2Hex(pInParams->uSEI[index * 2]) * 16 +
Char2Hex(pInParams->uSEI[index * 2 + 1]);
uuid.push_back(bt);
}
index = 32; //32 characters for uuid
if(msdk_strlen(pInParams->uSEI) > index)
{
index++; //skip the delimiter
if(pInParams->CodecId == MFX_CODEC_HEVC)
{
pl->CtrlFlags = pInParams->uSEI[index++] == '0' ? 0 : MFX_PAYLOAD_CTRL_SUFFIX;
}
else
{
pl->CtrlFlags = pInParams->uSEI[index++] == '0';
}
}
if(msdk_strlen(pInParams->uSEI) > index)
{
index++;
// Converting to byte-string if necessary
msdk_tstring tstr(pInParams->uSEI+index);
std::transform(tstr.begin(), tstr.end(), std::back_inserter(msg), [](msdk_char c) {
return (char)c;
});
}
size = (mfxU16)uuid.size();
size += (mfxU16)msg.length();
SEICalcSizeType(data, type, size);
mfxU16 calc_size = (mfxU16)data.size();
size += calc_size;
pl->BufSize = size;
pl->Data = new mfxU8[pl->BufSize];
pl->NumBit = pl->BufSize * 8;
pl->Type = type;
mfxU8* p = pl->Data;
memcpy(p, data.data(), calc_size);
p += calc_size;
memcpy(p, uuid.data(), uuid.size());
p += uuid.size();
memcpy(p, msg.c_str(), msg.length());
m_UserDataUnregSEI.push_back(pl);
}
// we don't specify profile and level and let the encoder choose those basing on parameters
// we must specify profile only for MVC codec
if (MVC_ENABLED & m_MVCflags)
{
m_mfxEncParams.mfx.CodecProfile = MFX_PROFILE_AVC_STEREO_HIGH;
}
// configure and attach external parameters
if (MVC_ENABLED & pInParams->MVC_flags)
{
m_mfxEncParams.AddExtBuffer<mfxExtMVCSeqDesc>();
}
if (MVC_VIEWOUTPUT & pInParams->MVC_flags)
{
auto codingOption = m_mfxEncParams.AddExtBuffer<mfxExtCodingOption>();
// ViewOuput option requested
codingOption->ViewOutput = MFX_CODINGOPTION_ON;
}
if (pInParams->nPicTimingSEI || pInParams->nNalHrdConformance || pInParams->nVuiNalHrdParameters)
{
auto codingOption = m_mfxEncParams.AddExtBuffer<mfxExtCodingOption>();
codingOption->PicTimingSEI = pInParams->nPicTimingSEI;
codingOption->NalHrdConformance = pInParams->nNalHrdConformance;
codingOption->VuiNalHrdParameters = pInParams->nVuiNalHrdParameters;
}
// configure the depth of the look ahead BRC if specified in command line
if (pInParams->nLADepth || pInParams->nMaxSliceSize || pInParams->nMaxFrameSize || pInParams->nBRefType ||
(pInParams->BitrateLimit && pInParams->CodecId == MFX_CODEC_AVC) ||
(pInParams->nExtBRC && (pInParams->CodecId == MFX_CODEC_HEVC || pInParams->CodecId == MFX_CODEC_AVC)) ||
pInParams->IntRefType || pInParams->IntRefCycleSize || pInParams->IntRefQPDelta ||
pInParams->AdaptiveI || pInParams->AdaptiveB)
{
auto codingOption2 = m_mfxEncParams.AddExtBuffer<mfxExtCodingOption2>();
codingOption2->LookAheadDepth = pInParams->nLADepth;
codingOption2->MaxSliceSize = pInParams->nMaxSliceSize;
codingOption2->MaxFrameSize = pInParams->nMaxFrameSize;
codingOption2->BRefType = pInParams->nBRefType;
codingOption2->BitrateLimit = pInParams->BitrateLimit;
if (pInParams->nExtBRC != EXTBRC_DEFAULT && (pInParams->CodecId == MFX_CODEC_HEVC || pInParams->CodecId == MFX_CODEC_AVC))
{
codingOption2->ExtBRC = (mfxU16)(pInParams->nExtBRC == EXTBRC_OFF ? MFX_CODINGOPTION_OFF : MFX_CODINGOPTION_ON);
}
else
{
codingOption2->ExtBRC = 0;
}
codingOption2->IntRefType = pInParams->IntRefType;
codingOption2->IntRefCycleSize = pInParams->IntRefCycleSize;
codingOption2->IntRefQPDelta = pInParams->IntRefQPDelta;
codingOption2->AdaptiveI = pInParams->AdaptiveI;
codingOption2->AdaptiveB = pInParams->AdaptiveB;
}
#if (MFX_VERSION >= 1024)
// This is for explicit extbrc only. In case of implicit (built-into-library) version - we don't need this extended buffer
if (pInParams->nExtBRC == EXTBRC_ON && (pInParams->CodecId == MFX_CODEC_HEVC || pInParams->CodecId == MFX_CODEC_AVC))
{
auto extBRC = m_mfxEncParams.AddExtBuffer<mfxExtBRC>();
HEVCExtBRC::Create(*extBRC);
}
#endif
// set up mfxCodingOption3
if (pInParams->nGPB || pInParams->LowDelayBRC || pInParams->WeightedPred || pInParams->WeightedBiPred
|| pInParams->nPRefType || pInParams->IntRefCycleDist || pInParams->nAdaptiveMaxFrameSize
|| pInParams->nNumRefActiveP || pInParams->nNumRefActiveBL0 || pInParams->nNumRefActiveBL1
|| pInParams->ExtBrcAdaptiveLTR || pInParams->QVBRQuality || pInParams->WinBRCSize
#if (MFX_VERSION >= 1027)
|| pInParams->TargetBitDepthLuma || pInParams->TargetBitDepthChroma
#endif
#if (MFX_VERSION >= MFX_VERSION_NEXT)
|| pInParams->DeblockingAlphaTcOffset || pInParams->DeblockingBetaOffset
#endif
|| pInParams->WinBRCMaxAvgKbps || pInParams->nTransformSkip)
{
auto codingOption3 = m_mfxEncParams.AddExtBuffer<mfxExtCodingOption3>();
if (pInParams->CodecId == MFX_CODEC_HEVC)
{
codingOption3->GPB = pInParams->nGPB;
std::fill(codingOption3->NumRefActiveP, codingOption3->NumRefActiveP + 8, pInParams->nNumRefActiveP);
std::fill(codingOption3->NumRefActiveBL0, codingOption3->NumRefActiveBL0 + 8, pInParams->nNumRefActiveBL0);
std::fill(codingOption3->NumRefActiveBL1, codingOption3->NumRefActiveBL1 + 8, pInParams->nNumRefActiveBL1);
#if (MFX_VERSION >= 1026)
codingOption3->TransformSkip = pInParams->nTransformSkip;
#endif
}
codingOption3->WeightedPred = pInParams->WeightedPred;
codingOption3->WeightedBiPred = pInParams->WeightedBiPred;
#if (MFX_VERSION >= 1023)
codingOption3->LowDelayBRC = pInParams->LowDelayBRC;
#endif
codingOption3->PRefType = pInParams->nPRefType;
codingOption3->IntRefCycleDist= pInParams->IntRefCycleDist;
codingOption3->AdaptiveMaxFrameSize = pInParams->nAdaptiveMaxFrameSize;
codingOption3->QVBRQuality = pInParams->QVBRQuality;
#if (MFX_VERSION >= 1026)
codingOption3->ExtBrcAdaptiveLTR = pInParams->ExtBrcAdaptiveLTR;
#endif
#if (MFX_VERSION >= 1027)
codingOption3->TargetBitDepthLuma = pInParams->TargetBitDepthLuma;
codingOption3->TargetBitDepthChroma = pInParams->TargetBitDepthChroma;
#endif
codingOption3->WinBRCSize = pInParams->WinBRCSize;
codingOption3->WinBRCMaxAvgKbps = pInParams->WinBRCMaxAvgKbps;
#if (MFX_VERSION >= MFX_VERSION_NEXT)
if (pInParams->DeblockingAlphaTcOffset || pInParams->DeblockingBetaOffset)
{
codingOption3->DeblockingAlphaTcOffset = pInParams->DeblockingAlphaTcOffset;
codingOption3->DeblockingBetaOffset = pInParams->DeblockingBetaOffset;
}
#endif
}
if (pInParams->nAvcTemp)
{
auto avcTemporalLayers = m_mfxEncParams.AddExtBuffer<mfxExtAvcTemporalLayers>();
avcTemporalLayers->BaseLayerPID = pInParams->nBaseLayerPID;
for (int i = 0; i < 8; i++)
{
avcTemporalLayers->Layer[i].Scale = pInParams->nAvcTemporalLayers[i];
}
}
if (pInParams->nSPSId || pInParams->nPPSId)
{
if (pInParams->CodecId == MFX_CODEC_HEVC)
{
auto codingOptionSPSPPS = m_mfxEncParams.AddExtBuffer<mfxExtCodingOptionSPSPPS>();
codingOptionSPSPPS->SPSId = pInParams->nSPSId;
codingOptionSPSPPS->PPSId = pInParams->nPPSId;
}
}
// In case of HEVC when height and/or width divided with 8 but not divided with 16
// add extended parameter to increase performance
if ( ( !((m_mfxEncParams.mfx.FrameInfo.CropW & 15 ) ^ 8 ) ||
!((m_mfxEncParams.mfx.FrameInfo.CropH & 15 ) ^ 8 ) ) &&
(m_mfxEncParams.mfx.CodecId == MFX_CODEC_HEVC) && !m_bIsFieldSplitting)
{
auto encHEVCParam = m_mfxEncParams.AddExtBuffer<mfxExtHEVCParam>();
encHEVCParam->PicWidthInLumaSamples = m_mfxEncParams.mfx.FrameInfo.CropW;
encHEVCParam->PicHeightInLumaSamples = m_mfxEncParams.mfx.FrameInfo.CropH;
}
if (pInParams->TransferMatrix)
{
auto videoSignalInfo = m_mfxEncParams.AddExtBuffer<mfxExtVideoSignalInfo>();
videoSignalInfo->ColourDescriptionPresent = 1;
videoSignalInfo->MatrixCoefficients = pInParams->TransferMatrix;
}
// JPEG encoder settings overlap with other encoders settings in mfxInfoMFX structure
if (MFX_CODEC_JPEG == pInParams->CodecId)
{
m_mfxEncParams.mfx.Interleaved = 1;
m_mfxEncParams.mfx.Quality = pInParams->nQuality;
m_mfxEncParams.mfx.RestartInterval = 0;
MSDK_ZERO_MEMORY(m_mfxEncParams.mfx.reserved5);
}
m_mfxEncParams.AsyncDepth = pInParams->nAsyncDepth;
return MFX_ERR_NONE;
}
mfxU32 CEncodingPipeline::FileFourCC2EncFourCC(mfxU32 fcc)
{
// File reader automatically converts I420 and YV12 to NV12
if (fcc == MFX_FOURCC_I420 || fcc == MFX_FOURCC_YV12)
return MFX_FOURCC_NV12;
else
return fcc;
}
mfxStatus CEncodingPipeline::InitMfxVppParams(sInputParams *pInParams)
{
MSDK_CHECK_POINTER(pInParams, MFX_ERR_NULL_PTR);
// specify memory type
if (D3D9_MEMORY == pInParams->memType || D3D11_MEMORY == pInParams->memType)
{
m_mfxVppParams.IOPattern = MFX_IOPATTERN_IN_VIDEO_MEMORY | MFX_IOPATTERN_OUT_VIDEO_MEMORY;
}
else
{
m_mfxVppParams.IOPattern = MFX_IOPATTERN_IN_SYSTEM_MEMORY | MFX_IOPATTERN_OUT_SYSTEM_MEMORY;
}
m_mfxVppParams.vpp.In.PicStruct = pInParams->nPicStruct;
ConvertFrameRate(pInParams->dFrameRate, &m_mfxVppParams.vpp.In.FrameRateExtN, &m_mfxVppParams.vpp.In.FrameRateExtD);
// width must be a multiple of 16
// height must be a multiple of 16 in case of frame picture and a multiple of 32 in case of field picture
m_mfxVppParams.vpp.In.Width = MSDK_ALIGN16(pInParams->nWidth);
m_mfxVppParams.vpp.In.Height = (MFX_PICSTRUCT_PROGRESSIVE == m_mfxVppParams.vpp.In.PicStruct)?
MSDK_ALIGN16(pInParams->nHeight) : MSDK_ALIGN32(pInParams->nHeight);
// set crops in input mfxFrameInfo for correct work of file reader
// VPP itself ignores crops at initialization
m_mfxVppParams.vpp.In.CropW = pInParams->nWidth;
m_mfxVppParams.vpp.In.CropH = pInParams->nHeight;
// fill output frame info
MSDK_MEMCPY_VAR(m_mfxVppParams.vpp.Out,&m_mfxVppParams.vpp.In, sizeof(mfxFrameInfo));
m_mfxVppParams.vpp.In.FourCC = FileFourCC2EncFourCC(m_InputFourCC);
m_mfxVppParams.vpp.Out.FourCC = pInParams->EncodeFourCC;
m_mfxVppParams.vpp.In.ChromaFormat = FourCCToChroma(m_mfxVppParams.vpp.In.FourCC);
m_mfxVppParams.vpp.Out.ChromaFormat = FourCCToChroma(m_mfxVppParams.vpp.Out.FourCC);
// Fill Shift bit
m_mfxVppParams.vpp.In.Shift = pInParams->shouldUseShifted10BitVPP;
m_mfxVppParams.vpp.Out.Shift = pInParams->shouldUseShifted10BitEnc; // This output should correspond to Encoder settings
// input frame info
#if defined (ENABLE_V4L2_SUPPORT)
if (isV4L2InputEnabled)
{
m_mfxVppParams.vpp.In.FourCC = v4l2Pipeline.ConvertToMFXFourCC(pInParams->v4l2Format);
m_mfxVppParams.vpp.In.ChromaFormat = FourCCToChroma(m_mfxVppParams.vpp.In.FourCC);
m_mfxVppParams.vpp.Out.FourCC = MFX_FOURCC_NV12;
m_mfxVppParams.vpp.Out.ChromaFormat = FourCCToChroma(m_mfxVppParams.vpp.Out.FourCC);
}
#endif
// only resizing is supported
m_mfxVppParams.vpp.Out.Width = MSDK_ALIGN16(pInParams->nDstWidth);
m_mfxVppParams.vpp.Out.Height = (MFX_PICSTRUCT_PROGRESSIVE == m_mfxVppParams.vpp.Out.PicStruct)?
MSDK_ALIGN16(pInParams->nDstHeight) : MSDK_ALIGN32(pInParams->nDstHeight);
// configure and attach external parameters
InitVppFilters();
m_mfxVppParams.AsyncDepth = pInParams->nAsyncDepth;
return MFX_ERR_NONE;
}
mfxStatus CEncodingPipeline::CreateHWDevice()
{
mfxStatus sts = MFX_ERR_NONE;
#if D3D_SURFACES_SUPPORT
#if MFX_D3D11_SUPPORT
if (D3D11_MEMORY == m_memType)
m_hwdev = new CD3D11Device();
else
#endif // #if MFX_D3D11_SUPPORT
m_hwdev = new CD3D9Device();
if (NULL == m_hwdev)
return MFX_ERR_MEMORY_ALLOC;
sts = m_hwdev->Init(
NULL,
0,
MSDKAdapter::GetNumber(GetFirstSession()));
MSDK_CHECK_STATUS(sts, "m_hwdev->Init failed");
#elif LIBVA_SUPPORT
m_hwdev = CreateVAAPIDevice(m_strDevicePath);
if (NULL == m_hwdev)
{
return MFX_ERR_MEMORY_ALLOC;
}
sts = m_hwdev->Init(NULL, 0, MSDKAdapter::GetNumber(GetFirstSession()));
MSDK_CHECK_STATUS(sts, "m_hwdev->Init failed");
#endif
return MFX_ERR_NONE;
}
mfxStatus CEncodingPipeline::ResetDevice()
{
if (D3D9_MEMORY == m_memType || D3D11_MEMORY == m_memType)
{
return m_hwdev->Reset();
}
return MFX_ERR_NONE;
}
mfxStatus CEncodingPipeline::AllocFrames()
{
MSDK_CHECK_POINTER(GetFirstEncoder(), MFX_ERR_NOT_INITIALIZED);
mfxStatus sts = MFX_ERR_NONE;
mfxFrameAllocRequest EncRequest;
mfxFrameAllocRequest PreEncRequest;
mfxFrameAllocRequest VppRequest[2];
mfxU16 nEncSurfNum = 0; // number of surfaces for encoder
mfxU16 nVppSurfNum = 0; // number of surfaces for vpp
mfxU16 nPreEncSurfNum = 0; // number of surfaces for preenc
MSDK_ZERO_MEMORY(EncRequest);
MSDK_ZERO_MEMORY(PreEncRequest);
MSDK_ZERO_MEMORY(VppRequest[0]);
MSDK_ZERO_MEMORY(VppRequest[1]);
mfxU16 initialTargetKbps = m_mfxEncParams.mfx.TargetKbps;
auto co2 = m_mfxEncParams.GetExtBuffer<mfxExtCodingOption2>();
// Querying encoder
sts = GetFirstEncoder()->Query(&m_mfxEncParams, &m_mfxEncParams);
MSDK_CHECK_STATUS(sts, "Query (for encoder) failed");
if (co2 && co2->BitrateLimit != MFX_CODINGOPTION_OFF && initialTargetKbps != m_mfxEncParams.mfx.TargetKbps)
{
msdk_printf(MSDK_STRING("WARNING: -BitrateLimit:on, target bitrate was changed from %d kbps to %d kbps.\n"), initialTargetKbps, m_mfxEncParams.mfx.TargetKbps);
}
// Calculate the number of surfaces for components.
// QueryIOSurf functions tell how many surfaces are required to produce at least 1 output.
// To achieve better performance we provide extra surfaces.
// 1 extra surface at input allows to get 1 extra output.
sts = GetFirstEncoder()->QueryIOSurf(&m_mfxEncParams, &EncRequest);
MSDK_CHECK_STATUS(sts, "QueryIOSurf (for encoder) failed");
if (!m_pmfxVPP)
{
EncRequest.NumFrameMin = EncRequest.NumFrameSuggested = std::max(EncRequest.NumFrameSuggested, m_nPerfOpt);
}
if (EncRequest.NumFrameSuggested < m_mfxEncParams.AsyncDepth)
return MFX_ERR_MEMORY_ALLOC;
// The number of surfaces shared by vpp output and encode input.
nEncSurfNum = EncRequest.NumFrameSuggested;
if (m_pmfxVPP)
{
// Querying VPP
sts = m_pmfxVPP->Query(&m_mfxVppParams, &m_mfxVppParams);
MSDK_CHECK_STATUS(sts, "m_pmfxVPP->Query failed");
// VppRequest[0] for input frames request, VppRequest[1] for output frames request
sts = m_pmfxVPP->QueryIOSurf(&m_mfxVppParams, VppRequest);
MSDK_CHECK_STATUS(sts, "m_pmfxVPP->QueryIOSurf failed");