File: libmfx_core.h

package info (click to toggle)
onevpl-intel-gpu 26.1.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 58,920 kB
  • sloc: cpp: 1,444,019; ansic: 29,778; asm: 17,754; makefile: 6
file content (1045 lines) | stat: -rw-r--r-- 39,182 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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
// Copyright (c) 2007-2025 Intel Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#ifndef __LIBMFX_CORE_H__
#define __LIBMFX_CORE_H__

#include <map>

#include "umc_mutex.h"
#include "libmfx_allocator.h"
#include "mfxvideo.h"
#include "mfxvideo++int.h"
#include "mfx_ext_buffers.h"
#include "fast_copy.h"
#include "libmfx_core_interface.h"

#include <memory>
#include <deque>
#include <chrono>
#include <limits>


using AffinityMaskType = std::pair<mfxU32/*size*/, std::vector<mfxU8>/*mask*/>;

class CommonCORE : public VideoCORE
{
public:

    friend class FactoryCORE;

    virtual ~CommonCORE() override { Close(); }

    virtual mfxStatus GetHandle(mfxHandleType type, mfxHDL *handle)          override;
    virtual mfxStatus SetHandle(mfxHandleType type, mfxHDL handle)           override;

    virtual mfxStatus SetBufferAllocator(mfxBufferAllocator *)               override;
    virtual mfxStatus SetFrameAllocator(mfxFrameAllocator *allocator)        override;

    // Utility functions for memory access
    virtual mfxStatus AllocBuffer(mfxU32 nbytes, mfxU16 type, mfxMemId *mid) override;
    virtual mfxStatus LockBuffer(mfxMemId mid, mfxU8 **ptr)                  override;
    virtual mfxStatus UnlockBuffer(mfxMemId mid)                             override;
    virtual mfxStatus FreeBuffer(mfxMemId mid)                               override;

    // DEPRECATED
    virtual mfxStatus CheckHandle() override { return MFX_ERR_NONE; }

    virtual mfxStatus GetFrameHDL(mfxMemId mid, mfxHDL *handle, bool ExtendedSearch = true)               override;

    virtual mfxStatus AllocFrames(mfxFrameAllocRequest *request,
                                   mfxFrameAllocResponse *response, bool isNeedCopy = true)               override;

    virtual mfxStatus LockFrame(mfxMemId mid, mfxFrameData *ptr)                                          override;
    virtual mfxStatus UnlockFrame(mfxMemId mid, mfxFrameData *ptr = nullptr)                              override;
    virtual mfxStatus FreeFrames(mfxFrameAllocResponse *response, bool ExtendedSearch = true)             override;

    virtual mfxStatus LockExternalFrame(mfxMemId mid, mfxFrameData *ptr, bool ExtendedSearch = true)      override;
    virtual mfxStatus GetExternalFrameHDL(mfxMemId mid, mfxHDL *handle, bool ExtendedSearch = true)       override;
    virtual mfxStatus UnlockExternalFrame(mfxMemId mid, mfxFrameData *ptr=0, bool ExtendedSearch = true)  override;

    virtual mfxMemId MapIdx(mfxMemId mid)                                                                 override;

    // Increment Surface lock caring about opaq
    virtual mfxStatus IncreaseReference(mfxFrameData *ptr, bool ExtendedSearch = true)                    override;
    // Decrement Surface lock caring about opaq
    virtual mfxStatus DecreaseReference(mfxFrameData *ptr, bool ExtendedSearch = true)                    override;

    // no care about surface, opaq and all round. Just increasing reference
    virtual mfxStatus IncreasePureReference(mfxU16 &Locked)                                               override;
    // no care about surface, opaq and all round. Just decreasing reference
    virtual mfxStatus DecreasePureReference(mfxU16 &Locked)                                               override;

    // Get Video Accelerator.
    virtual void  GetVA(mfxHDL* phdl, mfxU16)                   override { *phdl = nullptr; }
    virtual void  GetVaArray(std::vector<mfxHDL>* phdl_array, mfxU16) override { phdl_array = nullptr; }
    virtual mfxStatus CreateVA(mfxVideoParam *, mfxFrameAllocRequest *, mfxFrameAllocResponse *, UMC::FrameAllocator *) override { MFX_RETURN(MFX_ERR_UNSUPPORTED); }
    virtual mfxStatus CreateVaArray(mfxVideoParam*, mfxFrameAllocRequest*, mfxFrameAllocResponse*, UMC::FrameAllocator*, mfxU8) override { MFX_RETURN(MFX_ERR_UNSUPPORTED); }

    // Get the current working adapter's number
    virtual mfxU32 GetAdapterNumber()                           override { return 0; }
#ifdef _MSVC_LANG
#pragma warning(push)
#pragma warning(disable : 26812)
#endif
    //
    virtual eMFXPlatform GetPlatformType()                      override { return MFX_PLATFORM_SOFTWARE; }
#ifdef _MSVC_LANG
#pragma warning(pop)
#endif

    // Get Video Processing
    virtual void  GetVideoProcessing(mfxHDL* phdl)              override { *phdl = 0; }
    virtual mfxStatus CreateVideoProcessing(mfxVideoParam *)    override { MFX_RETURN(MFX_ERR_UNSUPPORTED); }

    // Get the current number of working threads
    virtual mfxU32 GetNumWorkingThreads()                       override { return m_numThreadsAvailable; }
    virtual void INeedMoreThreadsInside(const void *pComponent) override;

    virtual mfxStatus DoFastCopy(mfxFrameSurface1 *pDst, mfxFrameSurface1 *pSrc)                      override;
    virtual mfxStatus DoFastCopyExtended(mfxFrameSurface1 *pDst, mfxFrameSurface1 *pSrc, mfxU32 = MFX_COPY_USE_ANY) override;

    virtual mfxStatus DoFastCopyWrapper(mfxFrameSurface1 *pDst, mfxU16 dstMemType, mfxFrameSurface1 *pSrc, mfxU16 srcMemType, mfxU32 = MFX_COPY_USE_ANY) override;

    // DEPRECATED
    virtual bool IsFastCopyEnabled()              override { return true; }

    virtual bool IsExternalFrameAllocator() const override;
    virtual eMFXHWType GetHWType()                override { return MFX_HW_UNKNOWN; }

    virtual mfxU16    GetHWDeviceId()             override { return 0; }

    virtual mfxStatus CopyFrame(mfxFrameSurface1 *dst, mfxFrameSurface1 *src) override;

    virtual mfxStatus CopyBuffer(mfxU8 *, mfxU32, mfxFrameSurface1 *)         override { MFX_RETURN(MFX_ERR_UNKNOWN); }

    virtual mfxStatus CopyFrameEx(mfxFrameSurface1 *pDst, mfxU16 dstMemType, mfxFrameSurface1 *pSrc, mfxU16 srcMemType) override
    {
        return DoFastCopyWrapper(pDst, dstMemType, pSrc, srcMemType);
    }

    virtual mfxStatus IsGuidSupported(const GUID, mfxVideoParam *, bool)      override { return MFX_ERR_NONE; }

    virtual eMFXVAType GetVAType() const                   override { return MFX_HW_NO; }

    virtual bool SetCoreId(mfxU32 Id)                      override;
    virtual void* QueryCoreInterface(const MFX_GUID &guid) override;

    virtual mfxSession GetSession()                        override { return m_session; }

    virtual mfxU16 GetAutoAsyncDepth()                     override;

    // keep frame response structure describing plug-in memory surfaces
    void AddPluginAllocResponse(mfxFrameAllocResponse& response);

    // get response which corresponds required conditions: same mids and number
    mfxFrameAllocResponse* GetPluginAllocResponse(mfxFrameAllocResponse& temp_response);

    // non-virtual QueryPlatform, as we should not change vtable
    mfxStatus QueryPlatform(mfxPlatform* platform);

protected:

    CommonCORE(const mfxU32 numThreadsAvailable, const mfxSession session = nullptr);

    class API_1_19_Adapter : public IVideoCore_API_1_19
    {
    public:
        API_1_19_Adapter(CommonCORE * core) : m_core(core) {}
        virtual mfxStatus QueryPlatform(mfxPlatform* platform);

    private:
        CommonCORE *m_core;
    };


    virtual mfxStatus          DefaultAllocFrames(mfxFrameAllocRequest *request, mfxFrameAllocResponse *response);
    mfxFrameAllocator*         GetAllocatorAndMid(mfxMemId& mid);
    mfxBaseWideFrameAllocator* GetAllocatorByReq(mfxU16 type) const;
    virtual void               Close();
    mfxStatus                  FreeMidArray(mfxFrameAllocator* pAlloc, mfxFrameAllocResponse *response);
    mfxStatus                  RegisterMids(mfxFrameAllocResponse *response, mfxU16 memType, bool IsDefaultAlloc, mfxBaseWideFrameAllocator* pAlloc = 0);

    bool                       GetUniqID(mfxMemId& mId);
    bool IsEqual (const mfxFrameAllocResponse &resp1, const mfxFrameAllocResponse &resp2) const
    {
        if (resp1.NumFrameActual != resp2.NumFrameActual)
            return false;

        for (mfxU32 i=0; i < resp1.NumFrameActual; i++)
        {
            if (resp1.mids[i] != resp2.mids[i])
                return false;
        }
        return true;
    };

    typedef struct
    {
        mfxMemId InternalMid;
        bool isDefaultMem;
        mfxU16 memType;

    } MemDesc;

    typedef std::map<mfxMemId, MemDesc> CorrespTbl;
    typedef std::map<mfxMemId, mfxBaseWideFrameAllocator*> AllocQueue;
    typedef std::map<mfxMemId*, mfxMemId*> MemIDMap;

    CorrespTbl       m_CTbl;
    AllocQueue       m_AllocatorQueue;
    MemIDMap         m_RespMidQ;

    // Number of available threads
    const
    mfxU32                                     m_numThreadsAvailable;
    // Handler to the owning session
    const
    mfxSession                                 m_session;

    // Common I/F
    mfxWideBufferAllocator                     m_bufferAllocator;
    mfxBaseWideFrameAllocator                  m_FrameAllocator;

    mfxU32                                     m_NumAllocators;
    mfxHDL                                     m_hdl;

    mfxHDL                                     m_DXVA2DecodeHandle;

    mfxHDL                                     m_D3DDecodeHandle;
    mfxHDL                                     m_D3DEncodeHandle;
    mfxHDL                                     m_D3DVPPHandle;

    bool                                       m_bSetExtBufAlloc;
    bool                                       m_bSetExtFrameAlloc;

    std::unique_ptr<mfxMemId[]>                m_pMemId;
    std::unique_ptr<mfxBaseWideFrameAllocator> m_pcAlloc;

    std::unique_ptr<FastCopy>                  m_pFastCopy;
    bool                                       m_bUseExtManager;
    UMC::Mutex                                 m_guard;

    mfxU32                                     m_CoreId;

    EncodeHWCaps                               m_encode_caps;
    EncodeHWCaps                               m_encode_mbprocrate;


    std::vector<mfxFrameAllocResponse>         m_PlugInMids;

    API_1_19_Adapter                           m_API_1_19;

#if defined(MFX_ENABLE_PXP)
    mfxHDL                                     m_pPXPCtxHdl;
#endif // MFX_ENABLE_PXP

    mfxU16                                     m_deviceId;

    class mfxMemoryInterfaceWrapper : public mfxMemoryInterface
    {
    public:
        mfxMemoryInterfaceWrapper(mfxSession session)
        {
            Context            = session;
            Version.Version    = MFX_MEMORYINTERFACE_VERSION;
            ImportFrameSurface = ImportFrameSurface_impl;
            GetBitstreamBuffer = GetBitstreamBuffer_impl;
        }

        static mfxStatus ImportFrameSurface_impl(mfxMemoryInterface* memory_interface, mfxSurfaceComponent surf_component, mfxSurfaceHeader* ext_surface, mfxFrameSurface1** imported_surface)
        {
            MFX_CHECK_NULL_PTR2(memory_interface, ext_surface);

            auto session = reinterpret_cast<mfxSession>(memory_interface->Context);

            switch (surf_component)
            {
            case MFX_SURFACE_COMPONENT_ENCODE:
                MFX_CHECK(session->m_pENCODE, MFX_ERR_NOT_INITIALIZED);

                MFX_RETURN(session->m_pENCODE->GetSurface(imported_surface, ext_surface));

            case MFX_SURFACE_COMPONENT_DECODE:
                MFX_CHECK(session->m_pDECODE, MFX_ERR_NOT_INITIALIZED);
                MFX_CHECK_NULL_PTR1(imported_surface);

                MFX_RETURN(session->m_pDECODE->GetSurface(*imported_surface, ext_surface));

            case MFX_SURFACE_COMPONENT_VPP_INPUT:
                MFX_CHECK(session->m_pVPP, MFX_ERR_NOT_INITIALIZED);

                MFX_RETURN(session->m_pVPP->GetSurfaceFromIn(imported_surface, ext_surface));

            case MFX_SURFACE_COMPONENT_VPP_OUTPUT:
                MFX_CHECK(session->m_pVPP, MFX_ERR_NOT_INITIALIZED);

                MFX_RETURN(session->m_pVPP->GetSurfaceFromOut(imported_surface, ext_surface));

            default:
                MFX_RETURN(MFX_ERR_INVALID_VIDEO_PARAM);
            }
        }

        static mfxStatus GetBitstreamBuffer_impl(mfxMemoryInterface* memory_interface, mfxBitstream* queried_bsBuffer)
        {
            MFX_CHECK(memory_interface, MFX_ERR_INVALID_HANDLE);
            MFX_CHECK_NULL_PTR1(queried_bsBuffer);

            auto session = reinterpret_cast<mfxSession>(memory_interface->Context);
            MFX_CHECK(session, MFX_ERR_INVALID_HANDLE);

            MFX_CHECK(session->m_pDECODE, MFX_ERR_NOT_INITIALIZED);

            MFX_RETURN(session->m_pDECODE->GetBitstreamBuffer(queried_bsBuffer));
        }
    } m_memory_interface;

    CommonCORE & operator = (const CommonCORE &) = delete;
};

mfxStatus CoreDoSWFastCopy(mfxFrameSurface1 & dst, const mfxFrameSurface1 & src, int copyFlag);

// Refactored MSDK 2.0 core

template<class Base>
class deprecate_from_base : public Base
{
public:
    virtual ~deprecate_from_base() {}

    virtual mfxMemId MapIdx(mfxMemId mid)                      override { return mid; }

    // Clean up code from buffer allocator usage and uncomment following items
    /* Deprecated functionality : buffer allocator */
    /*
    virtual mfxStatus SetBufferAllocator(mfxBufferAllocator *) override
    {
        return MFX_ERR_UNSUPPORTED;
    }

    virtual mfxStatus AllocBuffer(mfxU32, mfxU16, mfxMemId *)  override
    {
        return MFX_ERR_UNSUPPORTED;
    }

    virtual mfxStatus LockBuffer(mfxMemId, mfxU8 **)           override
    {
        return MFX_ERR_UNSUPPORTED;
    }

    virtual mfxStatus UnlockBuffer(mfxMemId)                   override
    {
        return MFX_ERR_UNSUPPORTED;
    }

    virtual mfxStatus FreeBuffer(mfxMemId)                     override
    {
        return MFX_ERR_UNSUPPORTED;
    }
    */

    virtual bool SetCoreId(mfxU32)                                                        override
    {
        return false;
    }

protected:
    virtual mfxStatus DefaultAllocFrames(mfxFrameAllocRequest *, mfxFrameAllocResponse *) override
    {
        return MFX_ERR_UNSUPPORTED;
    }

    deprecate_from_base(const mfxU32 numThreadsAvailable, const mfxSession session = nullptr)
        : Base(numThreadsAvailable, session)
    {}

    deprecate_from_base(const mfxU32 adapterNum, const AffinityMaskType& affinityMask, const mfxU32 numThreadsAvailable, const mfxSession session = nullptr)
        : Base(adapterNum, affinityMask, numThreadsAvailable, session)
    {}
};

class CommonCORE_VPL : public deprecate_from_base<CommonCORE>
{
public:

    friend class FactoryCORE;

    virtual mfxStatus SetFrameAllocator(mfxFrameAllocator *allocator)                             override;

    virtual mfxStatus GetFrameHDL(mfxMemId mid, mfxHDL *handle, bool = true)                      override;

    virtual mfxStatus AllocFrames(mfxFrameAllocRequest *request, mfxFrameAllocResponse *response, bool isNeedCopy = true) override;

    virtual mfxStatus LockFrame(mfxMemId mid, mfxFrameData *ptr)                                  override;
    virtual mfxStatus UnlockFrame(mfxMemId mid, mfxFrameData *ptr = nullptr)                      override;
    virtual mfxStatus FreeFrames(mfxFrameAllocResponse *response, bool = true)                    override;

    virtual mfxStatus LockExternalFrame(mfxMemId mid, mfxFrameData *ptr, bool = true)             override;
    virtual mfxStatus GetExternalFrameHDL(mfxMemId mid, mfxHDL *handle, bool = true)              override;
    virtual mfxStatus UnlockExternalFrame(mfxMemId mid, mfxFrameData *ptr = nullptr, bool = true) override;

    std::pair<mfxStatus, bool> Lock(mfxFrameSurface1& surf, mfxU32 flags);
    std::pair<mfxStatus, bool> LockExternal(mfxFrameSurface1& surf, mfxU32 flags);
    std::pair<mfxStatus, bool> LockInternal(mfxFrameSurface1& surf, mfxU32 flags);
    mfxStatus Unlock(mfxFrameSurface1& surf);
    mfxStatus UnlockExternal(mfxFrameSurface1& surf);
    mfxStatus UnlockInternal(mfxFrameSurface1& surf);
    mfxStatus SwitchMemidInSurface(mfxFrameSurface1 & surf, mfxHDLPair& handle_pair);
    mfxStatus DeriveMemoryType(const mfxFrameSurface1& surf, mfxU16& derived_memtype);

    virtual mfxStatus DoFastCopyExtended(mfxFrameSurface1 *pDst, mfxFrameSurface1 *pSrc, mfxU32 = MFX_COPY_USE_ANY)                                      override;

    virtual mfxStatus DoFastCopyWrapper(mfxFrameSurface1 *pDst, mfxU16 dstMemType, mfxFrameSurface1 *pSrc, mfxU16 srcMemType, mfxU32 = MFX_COPY_USE_ANY) override;

    virtual bool IsExternalFrameAllocator() const                             override;

    virtual mfxStatus CopyFrame(mfxFrameSurface1 *dst, mfxFrameSurface1 *src) override;

    virtual void* QueryCoreInterface(const MFX_GUID &guid)                    override;

    virtual mfxStatus CreateSurface(mfxU16 type, const mfxFrameInfo& info, mfxFrameSurface1* &surf, mfxSurfaceHeader* import_surface);

protected:

    CommonCORE_VPL(const mfxU32 numThreadsAvailable, const mfxSession session = nullptr);

    FrameAllocatorWrapper m_frame_allocator_wrapper;
};

enum class SurfaceLockType
{
    LOCK_NONE    = 0,
    LOCK_GENERAL = 1,
    LOCK_EXTERNAL,
    LOCK_INTERNAL
};

// Potentially can be put to std::lock_guard and etc
class mfxFrameSurface1_scoped_lock
{
public:
    mfxFrameSurface1_scoped_lock(mfxFrameSurface1* surf = nullptr, CommonCORE_VPL* core = nullptr)
        : surf(surf)
        , core(core)
        , mid(surf ? surf->Data.MemId : nullptr)
    {}

    mfxStatus lock(mfxU32 flags = MFX_MAP_READ_WRITE, SurfaceLockType lock = SurfaceLockType::LOCK_GENERAL)
    {
        MFX_CHECK_HDL(core);
        MFX_CHECK_NULL_PTR1(surf);

        mfxStatus sts;
        bool was_locked = false;

        switch (lock)
        {
        case SurfaceLockType::LOCK_NONE:
            sts = MFX_ERR_NONE;
            break;
        case SurfaceLockType::LOCK_GENERAL:
            std::tie(sts, was_locked) = core->Lock(*surf, flags);
            break;
        case SurfaceLockType::LOCK_EXTERNAL:
            std::tie(sts, was_locked) = core->LockExternal(*surf, flags);
            break;
        case SurfaceLockType::LOCK_INTERNAL:
            std::tie(sts, was_locked) = core->LockInternal(*surf, flags);
            break;
        default:
            MFX_RETURN(MFX_ERR_UNKNOWN);
        }

        MFX_CHECK_STS(sts);

        lock_type = was_locked ? lock : SurfaceLockType::LOCK_NONE;
        return MFX_ERR_NONE;
    }

    mfxStatus unlock()
    {
        MFX_CHECK_HDL(core);
        MFX_CHECK_NULL_PTR1(surf);

        // In some cases MSDK zeroes memid before copying. Following assignment guarantees correct unlock in such case
        surf->Data.MemId = mid;

        switch (lock_type)
        {
        case SurfaceLockType::LOCK_NONE:
            return MFX_ERR_NONE;

        case SurfaceLockType::LOCK_GENERAL:
            MFX_SAFE_CALL(core->Unlock(*surf));
            break;
        case SurfaceLockType::LOCK_EXTERNAL:
            MFX_SAFE_CALL(core->UnlockExternal(*surf));
            break;
        case SurfaceLockType::LOCK_INTERNAL:
            MFX_SAFE_CALL(core->UnlockInternal(*surf));
            break;
        default:
            MFX_RETURN(MFX_ERR_UNKNOWN);
        }

        // Do not unlock in destructor
        lock_type = SurfaceLockType::LOCK_NONE;
        return MFX_ERR_NONE;
    }

    ~mfxFrameSurface1_scoped_lock()
    {
        std::ignore = MFX_STS_TRACE(unlock());
    }

private:
    mfxFrameSurface1*  surf      = nullptr;
    CommonCORE_VPL*    core      = nullptr;
    mfxMemId           mid       = nullptr;
    SurfaceLockType    lock_type = SurfaceLockType::LOCK_NONE;
};

template <>
struct mfxRefCountableInstance<mfxSurfacePoolInterface>
{
    static mfxRefCountable* Get(mfxSurfacePoolInterface* object)
    { return reinterpret_cast<mfxRefCountable*>(object->Context); }
};

class SurfaceCache
    : public mfxRefCountableImpl<mfxSurfacePoolInterface>
{
public:
    static SurfaceCache* Create(CommonCORE_VPL& core, mfxU16 type, const mfxFrameInfo& frame_info)
    {
        auto cache = new SurfaceCache(core, type, frame_info);
        cache->AddRef();

        return cache;
    }

    static mfxStatus SetNumSurfaces_impl(mfxSurfacePoolInterface *pool_interface, mfxU32 num_surfaces)
    {
        MFX_CHECK_NULL_PTR1(pool_interface);
        MFX_CHECK_HDL(pool_interface->Context);

        auto cache = reinterpret_cast<SurfaceCache*>(pool_interface->Context);

        return cache->UpdateLimits(num_surfaces);
    }

    static mfxStatus RevokeSurfaces_impl(mfxSurfacePoolInterface *pool_interface, mfxU32 num_surfaces)
    {
        MFX_CHECK_NULL_PTR1(pool_interface);
        MFX_CHECK_HDL(pool_interface->Context);

        auto cache = reinterpret_cast<SurfaceCache*>(pool_interface->Context);

        return cache->RevokeSurfaces(num_surfaces);
    }

    static mfxStatus GetAllocationPolicy_impl(mfxSurfacePoolInterface *pool_interface, mfxPoolAllocationPolicy *policy)
    {
        MFX_CHECK_NULL_PTR2(pool_interface, policy);
        MFX_CHECK_HDL(pool_interface->Context);

        auto cache = reinterpret_cast<SurfaceCache*>(pool_interface->Context);

        *policy = cache->ReportPolicy();

        return MFX_ERR_NONE;
    }

    static mfxStatus GetMaximumPoolSize_impl(mfxSurfacePoolInterface *pool_interface, mfxU32 *size)
    {
        MFX_CHECK_NULL_PTR2(pool_interface, size);
        MFX_CHECK_HDL(pool_interface->Context);

        auto cache = reinterpret_cast<SurfaceCache*>(pool_interface->Context);

        *size = cache->ReportMaxSize();

        return MFX_ERR_NONE;
    }

    static mfxStatus GetCurrentPoolSize_impl(mfxSurfacePoolInterface *pool_interface, mfxU32 *size)
    {
        MFX_CHECK_NULL_PTR2(pool_interface, size);
        MFX_CHECK_HDL(pool_interface->Context);

        auto cache = reinterpret_cast<SurfaceCache*>(pool_interface->Context);

        *size = cache->ReportCurrentSize();

        return MFX_ERR_NONE;
    }

    std::chrono::milliseconds GetTimeout() const
    {
        return m_time_to_wait;
    }

    mfxStatus GetSurface(mfxFrameSurface1*& output_surface, bool emulate_zero_refcount_base = false, mfxSurfaceHeader* import_surface = nullptr)
    {
        return GetSurface(output_surface, m_time_to_wait, emulate_zero_refcount_base, import_surface);
    }

    mfxStatus GetSurface(mfxFrameSurface1* & output_surface, std::chrono::milliseconds current_time_to_wait, bool emulate_zero_refcount_base = false, mfxSurfaceHeader* import_surface = nullptr)
    {
        /*
            Note: emulate_zero_refcount_base flag is required for some corner cases in decoders. More precisely
            it is required to comply with mfx_UMC_FrameAllocator adapter design: It has it's own refcounting
            logic (We repeat it's AddRef / Release in our "real" refcounting logic of surface), but implementation
            in mfx_UMC_FrameAllocator assumes that surface refcount started from zero while surface arrive,
            but that is not true for VPL memory, our new surfaces arrive with refcount equal to 1. So this trick
            is just allows us to emulate that zero refcount base, and leave mfx_UMC_FrameAllocator code as is.
        */
        std::unique_lock<std::mutex> lock(m_mutex);

        if (!import_surface)
        {
            // Try to export existing surface from cache first

            output_surface = FreeSurfaceLookup(emulate_zero_refcount_base);
            if (output_surface)
            {
                return MFX_ERR_NONE;
            }

            if (m_cached_surfaces.size() + m_num_pending_insertion >= m_limit)
            {
                using namespace std::chrono;

                MFX_CHECK(current_time_to_wait != 0ms, MFX_WRN_ALLOC_TIMEOUT_EXPIRED);

                // Cannot allocate (no free slots) surface, but we can wait
                bool wait_succeeded = m_cv_wait_free_surface.wait_for(lock, current_time_to_wait,
                    [&output_surface, emulate_zero_refcount_base, this]()
                {
                    output_surface = FreeSurfaceLookup(emulate_zero_refcount_base);

                    return output_surface != nullptr;
                });

                MFX_CHECK(wait_succeeded, MFX_WRN_ALLOC_TIMEOUT_EXPIRED);

                return MFX_ERR_NONE;
            }
        }
        // Check if there is a free slot for insertion
        else if (m_cached_surfaces.size() + m_num_pending_insertion >= m_limit)
        {
            // We try to reallocate one of the existing free surfaces if cache limit reached, but user asks to import surface
            auto it = std::find_if(std::begin(m_cached_surfaces), std::end(m_cached_surfaces), [](const SurfaceHolder& surface) { return !surface.m_in_use; });

            if (it == std::end(m_cached_surfaces))
            {
                using namespace std::chrono;

                MFX_CHECK(current_time_to_wait != 0ms, MFX_WRN_ALLOC_TIMEOUT_EXPIRED);

                // Cannot allocate (no free slots) surface, but we can wait
                bool wait_succeeded = m_cv_wait_free_surface.wait_for(lock, current_time_to_wait,
                    [&it, this]()
                    {
                        it = std::find_if(std::begin(m_cached_surfaces), std::end(m_cached_surfaces), [](const SurfaceHolder& surface) { return !surface.m_in_use; });

                        return it != std::end(m_cached_surfaces);
                    });

                MFX_CHECK(wait_succeeded, MFX_WRN_ALLOC_TIMEOUT_EXPIRED);

                m_cached_surfaces.erase(it);
            }
        }

        // Get the new one from allocator
        ++m_num_pending_insertion;
        lock.unlock();

        mfxFrameSurface1* surf = nullptr;
        // Surfaces returned by CreateSurface already have RefCounter == 1
        mfxStatus sts = m_core.CreateSurface(m_type, m_frame_info, surf, import_surface);
        MFX_CHECK_STS(sts);

        lock.lock();
        m_cached_surfaces.emplace_back(*surf, *this);
        --m_num_pending_insertion;
        m_cached_surfaces.back().m_in_use = true;
        // We can relax this in future if actually copy happened during import
        m_cached_surfaces.back().m_created_from_external_handle = !!import_surface;

        if (emulate_zero_refcount_base)
        {
            m_cached_surfaces.back().FrameInterface->AddRef = &skip_one_addref;
        }

        output_surface = &m_cached_surfaces.back();

        TRACE_EVENT(MFX_TRACE_API_GETSURFACE_TASK, EVENT_TYPE_INFO, TR_KEY_INTERNAl, make_event_data(m_cached_surfaces.size()));

        return MFX_ERR_NONE;
    }

    mfxFrameSurface1* FindSurface(const mfxMemId memid)
    {
        std::lock_guard<std::mutex> guard(m_mutex);

        auto it = std::find_if(std::begin(m_cached_surfaces), std::end(m_cached_surfaces), [memid](const SurfaceHolder& surface) { return surface.Data.MemId == memid; });

        return it != std::end(m_cached_surfaces) ? &(*it) : nullptr;
    }

    mfxStatus SetupPolicy(const mfxExtAllocationHints& hints_buffer)
    {
        std::lock_guard<std::mutex> guard(m_mutex);

        m_policy = hints_buffer.AllocationPolicy;

        // Setup upper limit on surface amount
        if (m_policy == MFX_ALLOCATION_LIMITED)
        {
            m_limit = size_t(hints_buffer.NumberToPreAllocate) + hints_buffer.DeltaToAllocateOnTheFly;
        }
        else if (m_policy != MFX_ALLOCATION_UNLIMITED)
        {
            m_limit = 0;
        }

        // Preallocate surfaces if requested
        if ((m_policy == MFX_ALLOCATION_LIMITED || m_policy == MFX_ALLOCATION_UNLIMITED) && hints_buffer.NumberToPreAllocate)
        {
            std::list<SurfaceHolder> preallocated_surfaces;
            mfxFrameSurface1* surf;

            for (mfxU32 i = 0; i < hints_buffer.NumberToPreAllocate; ++i)
            {
                MFX_SAFE_CALL(m_core.CreateSurface(m_type, m_frame_info, surf, nullptr));
                preallocated_surfaces.emplace_back(*surf, *this);
            }

            m_cached_surfaces = std::move(preallocated_surfaces);
        }

        m_time_to_wait = std::chrono::milliseconds(hints_buffer.Wait);

        return MFX_ERR_NONE;
    }

    mfxStatus UpdateLimits(mfxU32 num_surfaces_requested_by_component)
    {
        MFX_CHECK(m_policy != MFX_ALLOCATION_LIMITED && m_policy != MFX_ALLOCATION_UNLIMITED, MFX_WRN_INCOMPATIBLE_VIDEO_PARAM);

        std::lock_guard<std::mutex> guard(m_mutex);

        switch (m_policy)
        {
        case MFX_ALLOCATION_OPTIMAL:
            m_limit += num_surfaces_requested_by_component;
            break;

        default:
            MFX_RETURN(MFX_ERR_UNKNOWN);
        }

        m_requests.push_back(num_surfaces_requested_by_component);

        return MFX_ERR_NONE;
    }

    mfxStatus RevokeSurfaces(mfxU32 num_surfaces_requested_by_component)
    {
        MFX_CHECK(m_policy != MFX_ALLOCATION_LIMITED && m_policy != MFX_ALLOCATION_UNLIMITED, MFX_WRN_INCOMPATIBLE_VIDEO_PARAM);

        std::unique_lock<std::mutex> lock(m_mutex);

        auto it_to_del = std::find(std::begin(m_requests), std::end(m_requests), num_surfaces_requested_by_component);
        MFX_CHECK(it_to_del != std::end(m_requests), MFX_WRN_OUT_OF_RANGE);

        m_requests.erase(it_to_del);

        size_t num_to_revoke = 0;

        switch (m_policy)
        {
        case MFX_ALLOCATION_OPTIMAL:

            m_limit -= num_surfaces_requested_by_component;

            if (m_cached_surfaces.size() <= m_limit)
                return MFX_ERR_NONE;

            num_to_revoke = m_cached_surfaces.size() - m_limit;

            break;

        default:
            MFX_RETURN(MFX_ERR_UNKNOWN);
        }

        // Decommit surfaces
        if (num_to_revoke)
        {
            m_num_to_revoke += num_to_revoke;

            DecomitSurfaces(lock);
        }

        return MFX_ERR_NONE;
    }

    void DecomitSurfaces(std::unique_lock<std::mutex>& outer_lock)
    {
        // Actual delete will happen after mutex unlock
        std::list<SurfaceHolder> surfaces_to_decommit;

        std::unique_lock<std::mutex> lock(std::move(outer_lock));

        auto should_remove_predicate =
            [](const SurfaceHolder& surface_holder)
        {
            // Check if surface is still owned by somebody
            return !surface_holder.m_in_use;
        };

        // splice_if
        for (auto it = std::begin(m_cached_surfaces); it != std::end(m_cached_surfaces) && m_num_to_revoke;)
        {
            auto it_to_transfer = it++;
            if (should_remove_predicate(*it_to_transfer))
            {
                surfaces_to_decommit.splice(std::end(surfaces_to_decommit), m_cached_surfaces, it_to_transfer);
                --m_num_to_revoke;
            }
        }
    }

    mfxU32 ReportCurrentSize() const
    {
        std::lock_guard<std::mutex> guard(m_mutex);
        return mfxU32(m_cached_surfaces.size());
    }

    mfxU32 ReportMaxSize() const
    {
        std::lock_guard<std::mutex> guard(m_mutex);
        return mfxU32(m_limit);
    }

    mfxPoolAllocationPolicy ReportPolicy() const
    {
        // Right now policy is not changing during runtime, so this function don't have mutex protection
        return m_policy;
    }

    mfxStatus MarkSurfaceFree(mfxMemId mid)
    {
        // Actual delete will happen after mutex unlock
        std::list<SurfaceHolder> surface_to_delete;

        std::unique_lock<std::mutex> lock(m_mutex);

        auto p_holder = std::find_if(std::begin(m_cached_surfaces), std::end(m_cached_surfaces), [mid](const SurfaceHolder& surface) { return surface.Data.MemId == mid; });
        MFX_CHECK(p_holder != std::end(m_cached_surfaces), MFX_ERR_NOT_FOUND);

        // Mark as free
        p_holder->m_in_use = false;

#ifndef NDEBUG
        assert(!p_holder->m_was_released);
        p_holder->m_was_released = true;
#endif
        // For imported surfaces we delete it immidiately, without returning to cache (since we don't control lifetime of HW handle)
        if (p_holder->m_created_from_external_handle)
        {
            surface_to_delete.splice(std::end(surface_to_delete), m_cached_surfaces, p_holder);

            return MFX_ERR_NONE;
        }

        // Remove surfaces from pool if required or notify waiters about free surface
        if (!m_num_to_revoke)
        {
            // If no surfaces to decommit, notify some waiter
            lock.unlock();
            m_cv_wait_free_surface.notify_one();
            return MFX_ERR_NONE;
        }

        // Decommit current surface
        surface_to_delete.splice(std::end(surface_to_delete), m_cached_surfaces, p_holder);
        --m_num_to_revoke;

        return MFX_ERR_NONE;
    }

private:

    SurfaceCache(CommonCORE_VPL& core, mfxU16 type, const mfxFrameInfo& frame_info)
        : m_core(core)
        , m_type((type & ~MFX_MEMTYPE_EXTERNAL_FRAME) | MFX_MEMTYPE_INTERNAL_FRAME)
        , m_frame_info(frame_info)
    {
        Context = this;

        mfxSurfacePoolInterface::SetNumSurfaces      = &SurfaceCache::SetNumSurfaces_impl;
        mfxSurfacePoolInterface::RevokeSurfaces      = &SurfaceCache::RevokeSurfaces_impl;
        mfxSurfacePoolInterface::GetAllocationPolicy = &SurfaceCache::GetAllocationPolicy_impl;
        mfxSurfacePoolInterface::GetMaximumPoolSize  = &SurfaceCache::GetMaximumPoolSize_impl;
        mfxSurfacePoolInterface::GetCurrentPoolSize  = &SurfaceCache::GetCurrentPoolSize_impl;
    }

    mfxFrameSurface1* FreeSurfaceLookup(bool emulate_zero_refcount_base = false)
    {
        // This function is called only from thread safe context, so no mutex acquiring here

        auto it = std::find_if(std::begin(m_cached_surfaces), std::end(m_cached_surfaces), [](const SurfaceHolder& surface) { return !surface.m_in_use; });

        if (it == std::end(m_cached_surfaces))
            return nullptr;

        it->m_in_use = true;
        if (emulate_zero_refcount_base)
        {
            it->FrameInterface->AddRef = &skip_one_addref;
        }
#ifndef NDEBUG
        it->m_was_released = false;
#endif
        return &(*it);
    }

    static mfxStatus skip_one_addref(mfxFrameSurface1* surface)
    {
        MFX_CHECK_NULL_PTR1(surface);
        MFX_CHECK_HDL(surface->FrameInterface);

        // Return back original AddRef function
        surface->FrameInterface->AddRef = mfxFrameSurfaceBaseInterface::_AddRef;

        return MFX_ERR_NONE;
    }

    class SurfaceHolder : public mfxFrameSurface1
    {
    public:
        // Right now in usage
        bool m_in_use                       = false;
        // Current surface was Imported (i.e. created from user-provided handle)
        bool m_created_from_external_handle = false;
#ifndef NDEBUG
        bool m_was_released = false;
#endif

        SurfaceHolder(mfxFrameSurface1& surf, SurfaceCache& cache)
            : mfxFrameSurface1(surf)
            , m_cache(cache)
            , m_surface_interface(*FrameInterface)
            , original_release(m_surface_interface.Release)
        {
            FrameInterface->Release = m_surface_interface.Release = proxy_release;

            // Connect surface with it's pool (cache instance)
            reinterpret_cast<mfxFrameSurfaceBaseInterface*>(m_surface_interface.Context)->SetParentPool(&m_cache);
        }

        ~SurfaceHolder()
        {
            // Untie surface from pool
            reinterpret_cast<mfxFrameSurfaceBaseInterface*>(m_surface_interface.Context)->SetParentPool(nullptr);

            m_surface_interface.Release = original_release;

            *FrameInterface = m_surface_interface;

            std::ignore = MFX_STS_TRACE(m_surface_interface.Release(this));
        }

    private:

        // To decommit surfaces on release
        SurfaceCache & m_cache;

        // Store it to protect against user zeroing this pointer
        mfxFrameSurfaceInterface m_surface_interface;

        mfxStatus(MFX_CDECL *original_release)(mfxFrameSurface1* surface);

        static mfxStatus proxy_release(mfxFrameSurface1* surface)
        {
            MFX_CHECK_NULL_PTR1(surface);
            MFX_CHECK_HDL(surface->FrameInterface);
            MFX_CHECK_HDL(surface->FrameInterface->Context);

            static std::mutex proxy_release_mutex;
            std::lock_guard<std::mutex> lock(proxy_release_mutex);

            mfxU32 ref_counter = reinterpret_cast<mfxFrameSurfaceBaseInterface*>(surface->FrameInterface->Context)->GetRefCounter();

            if (ref_counter > 1)
            {
                // Bypass to original release function
                return reinterpret_cast<mfxFrameSurfaceBaseInterface*>(surface->FrameInterface->Context)->Release();
            }

            // Return back to pool, don't touch ref counter
            auto pool = reinterpret_cast<mfxFrameSurfaceBaseInterface*>(surface->FrameInterface->Context)->QueryParentPool();
            MFX_CHECK_HDL(pool);
            auto cache = reinterpret_cast<SurfaceCache*>(pool->Context);
            MFX_CHECK_HDL(cache);
            mfx::OnExit release_cache([cache]() { cache->Release(); });

            return cache->MarkSurfaceFree(surface->Data.MemId);
        }
    };

    mutable std::mutex        m_mutex;
    std::condition_variable   m_cv_wait_free_surface;

    std::chrono::milliseconds m_time_to_wait = std::chrono::milliseconds(0);

    CommonCORE_VPL&           m_core;
    mfxU16                    m_type;
    mfxFrameInfo              m_frame_info;

    mfxPoolAllocationPolicy   m_policy = MFX_ALLOCATION_UNLIMITED;
    // Default is MFX_ALLOCATION_UNLIMITED
    size_t                    m_limit                 = std::numeric_limits<size_t>::max();
    // Counter of surfaces being constructed
    size_t                    m_num_pending_insertion = 0;
    size_t                    m_num_to_revoke         = 0;

    std::list<SurfaceHolder>  m_cached_surfaces;
    std::list<mfxU32>         m_requests;
};

inline bool SupportsVPLFeatureSet(VideoCORE& core)
{
    return !!core.QueryCoreInterface(MFXICommonCORE_VPL_GUID);
}

inline bool IsD3D9Simulation(VideoCORE& core)
{
    bool* cored3d9on11_interface = reinterpret_cast<bool*>(core.QueryCoreInterface(MFXI_IS_CORED3D9ON11_GUID));
    return cored3d9on11_interface && *cored3d9on11_interface;
}

#endif