Welcome to mirror list, hosted at ThFree Co, Russian Federation.

cuvid.cpp « decoders « LAVVideo « decoder - github.com/mpc-hc/LAVFilters.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 759ead9f6d3e6d70f77919c3324fedf1be7549d2 (plain)
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
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
/*
 *      Copyright (C) 2010-2015 Hendrik Leppkes
 *      http://www.1f0.de
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "stdafx.h"
#include "cuvid.h"

#include "moreuuids.h"

#include "parsers/H264SequenceParser.h"
#include "parsers/MPEG2HeaderParser.h"
#include "parsers/VC1HeaderParser.h"
#include "parsers/HEVCSequenceParser.h"

#include "Media.h"

////////////////////////////////////////////////////////////////////////////////
// Constructor
////////////////////////////////////////////////////////////////////////////////

ILAVDecoder *CreateDecoderCUVID() {
  return new CDecCuvid();
}

////////////////////////////////////////////////////////////////////////////////
// CUVID codec map
////////////////////////////////////////////////////////////////////////////////

static struct {
  AVCodecID ffcodec;
  cudaVideoCodec cudaCodec;
} cuda_codecs[] = {
  { AV_CODEC_ID_MPEG1VIDEO, cudaVideoCodec_MPEG1 },
  { AV_CODEC_ID_MPEG2VIDEO, cudaVideoCodec_MPEG2 },
  { AV_CODEC_ID_VC1,        cudaVideoCodec_VC1   },
  { AV_CODEC_ID_H264,       cudaVideoCodec_H264  },
  { AV_CODEC_ID_MPEG4,      cudaVideoCodec_MPEG4 },
  { AV_CODEC_ID_HEVC,       cudaVideoCodec_HEVC  },
};

////////////////////////////////////////////////////////////////////////////////
// Compatibility tables
////////////////////////////////////////////////////////////////////////////////

#define LEVEL_C_LOW_LIMIT 0x0A20

static DWORD LevelCBlacklist[] = {
  0x0A22, 0x0A67,     // Geforce 315, no VDPAU at all
  0x0A68, 0x0A69,     // Geforce G105M, only B
  0x0CA0, 0x0CA7,     // Geforce GT 330, only A
  0x0CAC,             // Geforce GT 220, no VDPAU
  0x10C3              // Geforce 8400GS, only A
};

static DWORD LevelCWhitelist[] = {
  0x06C0,             // Geforce GTX 480
  0x06C4,             // Geforce GTX 465
  0x06CA,             // Geforce GTX 480M
  0x06CD,             // Geforce GTX 470
  0x08A5,             // Geforce 320M

  0x06D8, 0x06DC,     // Quadro 6000
  0x06D9,             // Quadro 5000
  0x06DA,             // Quadro 5000M
  0x06DD,             // Quadro 4000

  0x06D1,             // Tesla C2050 / C2070
  0x06D2,             // Tesla M2070
  0x06DE,             // Tesla T20 Processor
  0x06DF,             // Tesla M2070-Q
};

static BOOL IsLevelC(DWORD deviceId)
{
  int idx = 0;
  if (deviceId >= LEVEL_C_LOW_LIMIT) {
    for(idx = 0; idx < countof(LevelCBlacklist); idx++) {
      if (LevelCBlacklist[idx] == deviceId)
        return FALSE;
    }
    return TRUE;
  } else {
    for(idx = 0; idx < countof(LevelCWhitelist); idx++) {
      if (LevelCWhitelist[idx] == deviceId)
        return TRUE;
    }
    return FALSE;
  }
}

////////////////////////////////////////////////////////////////////////////////
// CUVID decoder implementation
////////////////////////////////////////////////////////////////////////////////

CDecCuvid::CDecCuvid(void)
  : CDecBase()
{
  ZeroMemory(&cuda, sizeof(cuda));
  ZeroMemory(&m_VideoFormat, sizeof(m_VideoFormat));
  ZeroMemory(&m_DXVAExtendedFormat, sizeof(m_DXVAExtendedFormat));
}

CDecCuvid::~CDecCuvid(void)
{
  DestroyDecoder(true);
}

STDMETHODIMP CDecCuvid::DestroyDecoder(bool bFull)
{
  if (m_AnnexBConverter) {
    SAFE_DELETE(m_AnnexBConverter);
  }

  if (m_hDecoder) {
    cuda.cuvidDestroyDecoder(m_hDecoder);
    m_hDecoder = 0;
  }

  if (m_hParser) {
    cuda.cuvidDestroyVideoParser(m_hParser);
    m_hParser = 0;
  }

  if (m_hStream) {
    cuda.cuStreamDestroy(m_hStream);
    m_hStream = 0;
  }

  if (m_pbRawNV12) {
    cuda.cuMemFreeHost(m_pbRawNV12);
    m_pbRawNV12 = nullptr;
    m_cRawNV12 = 0;
  }

  if(bFull) {
    if (m_cudaCtxLock) {
      cuda.cuvidCtxLockDestroy(m_cudaCtxLock);
      m_cudaCtxLock = 0;
    }

    if (m_cudaContext) {
      cuda.cuCtxDestroy(m_cudaContext);
      m_cudaContext = 0;
    }

    SafeRelease(&m_pD3DDevice);
    SafeRelease(&m_pD3D);

    FreeLibrary(cuda.cudaLib);
    FreeLibrary(cuda.cuvidLib);

    ZeroMemory(&cuda, sizeof(cuda));
  }

  return S_OK;
}

#define GET_PROC_EX(name, lib)                         \
  cuda.name = (t##name *)GetProcAddress(lib, #name); \
  if (cuda.name == nullptr) {                           \
    DbgLog((LOG_ERROR, 10, L"-> Failed to load function \"%s\"", TEXT(#name))); \
    return E_FAIL; \
  }

#define GET_PROC_CUDA(name) GET_PROC_EX(name, cuda.cudaLib)
#define GET_PROC_CUVID(name) GET_PROC_EX(name, cuda.cuvidLib)


STDMETHODIMP CDecCuvid::LoadCUDAFuncRefs()
{
  // Load CUDA functions
  cuda.cudaLib = LoadLibrary(L"nvcuda.dll");
  if (cuda.cudaLib == nullptr) {
    DbgLog((LOG_TRACE, 10, L"-> Loading nvcuda.dll failed"));
    return E_FAIL;
  }

  GET_PROC_CUDA(cuInit);
  GET_PROC_CUDA(cuCtxCreate);
  GET_PROC_CUDA(cuCtxDestroy);
  GET_PROC_CUDA(cuCtxPushCurrent);
  GET_PROC_CUDA(cuCtxPopCurrent);
  GET_PROC_CUDA(cuD3D9CtxCreate);
  GET_PROC_CUDA(cuMemAllocHost);
  GET_PROC_CUDA(cuMemFreeHost);
  GET_PROC_CUDA(cuMemcpyDtoH);
  GET_PROC_CUDA(cuMemcpyDtoHAsync);
  GET_PROC_CUDA(cuStreamCreate);
  GET_PROC_CUDA(cuStreamDestroy);
  GET_PROC_CUDA(cuStreamQuery);
  GET_PROC_CUDA(cuDeviceGetCount);
  GET_PROC_CUDA(cuDriverGetVersion);
  GET_PROC_CUDA(cuDeviceGetName);
  GET_PROC_CUDA(cuDeviceComputeCapability);
  GET_PROC_CUDA(cuDeviceGetAttribute);

  // Load CUVID function
  cuda.cuvidLib = LoadLibrary(L"nvcuvid.dll");
  if (cuda.cuvidLib == nullptr) {
    DbgLog((LOG_TRACE, 10, L"-> Loading nvcuvid.dll failed"));
    return E_FAIL;
  }

  GET_PROC_CUVID(cuvidCtxLockCreate);
  GET_PROC_CUVID(cuvidCtxLockDestroy);
  GET_PROC_CUVID(cuvidCtxLock);
  GET_PROC_CUVID(cuvidCtxUnlock);
  GET_PROC_CUVID(cuvidCreateVideoParser);
  GET_PROC_CUVID(cuvidParseVideoData);
  GET_PROC_CUVID(cuvidDestroyVideoParser);
  GET_PROC_CUVID(cuvidCreateDecoder);
  GET_PROC_CUVID(cuvidDecodePicture);
  GET_PROC_CUVID(cuvidDestroyDecoder);
  GET_PROC_CUVID(cuvidMapVideoFrame);
  GET_PROC_CUVID(cuvidUnmapVideoFrame);

  return S_OK;
}

STDMETHODIMP CDecCuvid::FlushParser()
{
  CUVIDSOURCEDATAPACKET pCuvidPacket;
  memset(&pCuvidPacket, 0, sizeof(pCuvidPacket));

  pCuvidPacket.flags |= CUVID_PKT_ENDOFSTREAM;
  CUresult result = CUDA_SUCCESS;

  cuda.cuvidCtxLock(m_cudaCtxLock, 0);
  __try {
    result = cuda.cuvidParseVideoData(m_hParser, &pCuvidPacket);
  } __except (1) {
    DbgLog((LOG_ERROR, 10, L"cuvidFlushParser(): cuvidParseVideoData threw an exception"));
    result = CUDA_ERROR_UNKNOWN;
  }
  cuda.cuvidCtxUnlock(m_cudaCtxLock, 0);

  return result;
}

// Beginning of GPU Architecture definitions
static int _ConvertSMVer2CoresDrvApi(int major, int minor)
{
  // Defines for GPU Architecture types (using the SM version to determine the # of cores per SM
  typedef struct {
    int SM; // 0xMm (hexidecimal notation), M = SM Major version, and m = SM minor version
    int Cores;
  } sSMtoCores;

  sSMtoCores nGpuArchCoresPerSM[] =
  {
    { 0x10,   8 },
    { 0x11,   8 },
    { 0x12,   8 },
    { 0x13,   8 },
    { 0x20,  32 },
    { 0x21,  48 },
    { 0x30, 192 },
    { 0x32, 192 },
    { 0x35, 192 },
    { 0x37, 192 },
    { 0x50, 128 },
    { 0x52, 128 },
    {   -1,  -1 }
  };

  int index = 0;
  while (nGpuArchCoresPerSM[index].SM != -1) {
    if (nGpuArchCoresPerSM[index].SM == ((major << 4) + minor) ) {
      return nGpuArchCoresPerSM[index].Cores;
    }
    index++;
  }
  printf("MapSMtoCores undefined SMversion %d.%d!\n", major, minor);
  return -1;
}

int CDecCuvid::GetMaxGflopsGraphicsDeviceId()
{
  CUdevice current_device = 0, max_perf_device = 0;
  int device_count     = 0, sm_per_multiproc = 0;
  int max_compute_perf = 0, best_SM_arch     = 0;
  int major = 0, minor = 0, multiProcessorCount, clockRate;
  int bTCC = 0, version;
  char deviceName[256];

  cuda.cuDeviceGetCount(&device_count);
  if (device_count <= 0)
    return -1;

  cuda.cuDriverGetVersion(&version);

  // Find the best major SM Architecture GPU device that are graphics devices
  while ( current_device < device_count ) {
    cuda.cuDeviceGetName(deviceName, 256, current_device);
    cuda.cuDeviceComputeCapability(&major, &minor, current_device);

    if (version >= 3020) {
      cuda.cuDeviceGetAttribute(&bTCC, CU_DEVICE_ATTRIBUTE_TCC_DRIVER, current_device);
    } else {
      // Assume a Tesla GPU is running in TCC if we are running CUDA 3.1
      if (deviceName[0] == 'T') bTCC = 1;
    }
    if (!bTCC) {
      if (major > 0 && major < 9999) {
        best_SM_arch = max(best_SM_arch, major);
      }
    }
    current_device++;
  }

  // Find the best CUDA capable GPU device
  current_device = 0;
  while( current_device < device_count ) {
    cuda.cuDeviceGetAttribute(&multiProcessorCount, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, current_device);
    cuda.cuDeviceGetAttribute(&clockRate, CU_DEVICE_ATTRIBUTE_CLOCK_RATE, current_device);
    cuda.cuDeviceComputeCapability(&major, &minor, current_device);

    if (version >= 3020) {
      cuda.cuDeviceGetAttribute(&bTCC, CU_DEVICE_ATTRIBUTE_TCC_DRIVER, current_device);
    } else {
      // Assume a Tesla GPU is running in TCC if we are running CUDA 3.1
      if (deviceName[0] == 'T') bTCC = 1;
    }

    if (major == 9999 && minor == 9999) {
      sm_per_multiproc = 1;
    } else {
      sm_per_multiproc = _ConvertSMVer2CoresDrvApi(major, minor);
    }

    // If this is a Tesla based GPU and SM 2.0, and TCC is disabled, this is a contendor
    if (!bTCC) // Is this GPU running the TCC driver?  If so we pass on this
    {
      int compute_perf = multiProcessorCount * sm_per_multiproc * clockRate;
      if(compute_perf > max_compute_perf) {
        // If we find GPU with SM major > 2, search only these
        if (best_SM_arch > 2) {
          // If our device = dest_SM_arch, then we pick this one
          if (major == best_SM_arch) {
            max_compute_perf  = compute_perf;
            max_perf_device   = current_device;
          }
        } else {
          max_compute_perf  = compute_perf;
          max_perf_device   = current_device;
        }
      }

#ifdef DEBUG
      cuda.cuDeviceGetName(deviceName, 256, current_device);
      DbgLog((LOG_TRACE, 10, L"CUDA Device: %S, Compute: %d.%d, CUDA Cores: %d, Clock: %d MHz", deviceName, major, minor, multiProcessorCount * sm_per_multiproc, clockRate / 1000));
#endif
    }
    ++current_device;
  }
  return max_perf_device;
}

// ILAVDecoder
STDMETHODIMP CDecCuvid::Init()
{
  DbgLog((LOG_TRACE, 10, L"CDecCuvid::Init(): Trying to open CUVID device"));
  HRESULT hr = S_OK;
  CUresult cuStatus = CUDA_SUCCESS;

  hr = LoadCUDAFuncRefs();
  if (FAILED(hr)) {
    DbgLog((LOG_ERROR, 10, L"-> Loading CUDA interfaces failed (hr: 0x%x)", hr));
    return hr;
  }

  cuStatus = cuda.cuInit(0);
  if (cuStatus != CUDA_SUCCESS) {
    DbgLog((LOG_ERROR, 10, L"-> cuInit failed (status: %d)", cuStatus));
    return E_FAIL;
  }

  // TODO: select best device
  int best_device = GetMaxGflopsGraphicsDeviceId();
  int device = best_device;

  DWORD dwDeviceIndex = m_pCallback->GetGPUDeviceIndex();
  if (dwDeviceIndex != DWORD_MAX) {
    best_device = (int)dwDeviceIndex;
  }

  m_pD3D = Direct3DCreate9(D3D_SDK_VERSION);
  if (!m_pD3D) {
    DbgLog((LOG_ERROR, 10, L"-> Failed to acquire IDirect3D9"));
    return E_FAIL;
  }

  D3DADAPTER_IDENTIFIER9 d3dId;
  D3DPRESENT_PARAMETERS d3dpp;
  D3DDISPLAYMODE d3ddm;
  unsigned uAdapterCount = m_pD3D->GetAdapterCount();
  for (unsigned lAdapter=0; lAdapter<uAdapterCount; lAdapter++) {
    DbgLog((LOG_TRACE, 10, L"-> Trying D3D Adapter %d..", lAdapter));

    ZeroMemory(&d3dpp, sizeof(d3dpp));
    m_pD3D->GetAdapterDisplayMode(lAdapter, &d3ddm);

    d3dpp.Windowed               = TRUE;
    d3dpp.BackBufferWidth        = 640;
    d3dpp.BackBufferHeight       = 480;
    d3dpp.BackBufferCount        = 1;
    d3dpp.BackBufferFormat       = d3ddm.Format;
    d3dpp.SwapEffect             = D3DSWAPEFFECT_DISCARD;
    d3dpp.Flags                  = D3DPRESENTFLAG_VIDEO;

    IDirect3DDevice9 *pDev = nullptr;
    CUcontext cudaCtx = 0;
    hr = m_pD3D->CreateDevice(lAdapter, D3DDEVTYPE_HAL, GetShellWindow(), D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED | D3DCREATE_FPU_PRESERVE, &d3dpp, &pDev);
    if (SUCCEEDED(hr)) {
      m_pD3D->GetAdapterIdentifier(lAdapter, 0, &d3dId);
      cuStatus = cuda.cuD3D9CtxCreate(&cudaCtx, &device, CU_CTX_SCHED_BLOCKING_SYNC, pDev);
      if (cuStatus == CUDA_SUCCESS) {
        DbgLog((LOG_TRACE, 10, L"-> Created D3D Device on adapter %S (%d), using CUDA device %d", d3dId.Description, lAdapter, device));

        BOOL isLevelC = IsLevelC(d3dId.DeviceId);
        DbgLog((LOG_TRACE, 10, L"InitCUDA(): D3D Device with Id 0x%x is level C: %d", d3dId.DeviceId, isLevelC));

        if (m_bVDPAULevelC && !isLevelC) {
          DbgLog((LOG_TRACE, 10, L"InitCUDA(): We already had a Level C+ device, this one is not, skipping"));
          continue;
        }

        // Release old resources
        SafeRelease(&m_pD3DDevice);
        if (m_cudaContext)
          cuda.cuCtxDestroy(m_cudaContext);

        // Store resources
        m_pD3DDevice = pDev;
        m_cudaContext = cudaCtx;
        m_bVDPAULevelC = isLevelC;
        // Is this the one we want?
        if (device == best_device)
          break;
      } else {
        DbgLog((LOG_TRACE, 10, L"-> D3D Device on adapter %d is not CUDA capable", lAdapter));
        SafeRelease(&pDev);
      }
    }
  }

  cuStatus = CUDA_SUCCESS;

  if (dwDeviceIndex != DWORD_MAX && device != best_device) {
    DbgLog((LOG_ERROR, 10, L"-> No D3D Device found matching the requested device"));
    SafeRelease(&m_pD3DDevice);
    if (m_cudaContext)
      cuda.cuCtxDestroy(m_cudaContext);
  }

  if (!m_pD3DDevice) {
    DbgLog((LOG_TRACE, 10, L"-> No D3D device available, building non-D3D context on device %d", best_device));
    SafeRelease(&m_pD3D);
    cuStatus = cuda.cuCtxCreate(&m_cudaContext, CU_CTX_SCHED_BLOCKING_SYNC, best_device);

    int major, minor;
    cuda.cuDeviceComputeCapability(&major, &minor, best_device);
    m_bVDPAULevelC = (major >= 2);
    DbgLog((LOG_TRACE, 10, L"InitCUDA(): pure CUDA context of device with compute %d.%d", major, minor));
  }

  if (cuStatus == CUDA_SUCCESS) {
    // Switch to a floating context
    CUcontext curr_ctx = nullptr;
    cuStatus = cuda.cuCtxPopCurrent(&curr_ctx);
    if (cuStatus != CUDA_SUCCESS) {
      DbgLog((LOG_ERROR, 10, L"-> Storing context on the stack failed with error %d", cuStatus));
      return E_FAIL;
    }
    cuStatus = cuda.cuvidCtxLockCreate(&m_cudaCtxLock, m_cudaContext);
    if (cuStatus != CUDA_SUCCESS) {
      DbgLog((LOG_ERROR, 10, L"-> Creation of floating context failed with error %d", cuStatus));
      return E_FAIL;
    }
  } else {
    DbgLog((LOG_TRACE, 10, L"-> Creation of CUDA context failed with error %d", cuStatus));
    return E_FAIL;
  }

  return S_OK;
}

STDMETHODIMP CDecCuvid::InitDecoder(AVCodecID codec, const CMediaType *pmt)
{
  DbgLog((LOG_TRACE, 10, L"CDecCuvid::InitDecoder(): Initializing CUVID decoder"));
  HRESULT hr = S_OK;

  if (!m_cudaContext) {
    DbgLog((LOG_TRACE, 10, L"-> InitDecoder called without a cuda context"));
    return E_FAIL;
  }

  // Free old device
  DestroyDecoder(false);

  // Flush Display Queue
  memset(&m_DisplayQueue, 0, sizeof(m_DisplayQueue));
  for (int i=0; i<DISPLAY_DELAY; i++)
    m_DisplayQueue[i].picture_index = -1;
  m_DisplayPos = 0;

  m_DisplayDelay = DISPLAY_DELAY;

  // Reduce display delay for DVD decoding for lower decode latency
  if (m_pCallback->GetDecodeFlags() & LAV_VIDEO_DEC_FLAG_DVD)
    m_DisplayDelay /= 2;

  cudaVideoCodec cudaCodec = (cudaVideoCodec)-1;
  for (int i = 0; i < countof(cuda_codecs); i++) {
    if (cuda_codecs[i].ffcodec == codec) {
      cudaCodec = cuda_codecs[i].cudaCodec;
      break;
    }
  }

  if (cudaCodec == -1) {
    DbgLog((LOG_TRACE, 10, L"-> Codec id %d does not map to a CUVID codec", codec));
    return E_FAIL;
  }

  if (cudaCodec == cudaVideoCodec_MPEG4 && !m_bVDPAULevelC) {
    DbgLog((LOG_TRACE, 10, L"-> Device is not capable to decode this format (not >= Level C)"));
    return E_FAIL;
  }

  m_bUseTimestampQueue = (m_pCallback->GetDecodeFlags() & LAV_VIDEO_DEC_FLAG_ONLY_DTS)
                      || (cudaCodec == cudaVideoCodec_MPEG4 && pmt->formattype != FORMAT_MPEG2Video);
  m_bWaitForKeyframe = m_bUseTimestampQueue;
  m_bInterlaced = TRUE;
  m_bFormatIncompatible = FALSE;
  m_bTFF = TRUE;
  m_rtPrevDiff = AV_NOPTS_VALUE;
  m_bARPresent = TRUE;

  // Create the CUDA Video Parser
  CUVIDPARSERPARAMS oVideoParserParameters;
  ZeroMemory(&oVideoParserParameters, sizeof(CUVIDPARSERPARAMS));
  oVideoParserParameters.CodecType              = cudaCodec;
  oVideoParserParameters.ulMaxNumDecodeSurfaces = MAX_DECODE_FRAMES;
  oVideoParserParameters.ulMaxDisplayDelay      = m_DisplayDelay;
  oVideoParserParameters.pUserData              = this;
  oVideoParserParameters.pfnSequenceCallback    = CDecCuvid::HandleVideoSequence;    // Called before decoding frames and/or whenever there is a format change
  oVideoParserParameters.pfnDecodePicture       = CDecCuvid::HandlePictureDecode;    // Called when a picture is ready to be decoded (decode order)
  oVideoParserParameters.pfnDisplayPicture      = CDecCuvid::HandlePictureDisplay;   // Called whenever a picture is ready to be displayed (display order)
  oVideoParserParameters.ulErrorThreshold       = m_bUseTimestampQueue ? 100 : 0;

  memset(&m_VideoParserExInfo, 0, sizeof(CUVIDEOFORMATEX));

  // Handle AnnexB conversion for H.264 and HEVC
  if (pmt->formattype == FORMAT_MPEG2Video && (pmt->subtype == MEDIASUBTYPE_AVC1 || pmt->subtype == MEDIASUBTYPE_avc1 || pmt->subtype == MEDIASUBTYPE_CCV1 || pmt->subtype == MEDIASUBTYPE_HVC1)) {
    MPEG2VIDEOINFO *mp2vi = (MPEG2VIDEOINFO *)pmt->Format();
    m_AnnexBConverter = new CAnnexBConverter();
    m_AnnexBConverter->SetNALUSize(2);

    BYTE *annexBextra = nullptr;
    int size = 0;

    if (cudaCodec == cudaVideoCodec_H264) {
      m_AnnexBConverter->Convert(&annexBextra, &size, (BYTE *)mp2vi->dwSequenceHeader, mp2vi->cbSequenceHeader);
    } else if (cudaCodec == cudaVideoCodec_HEVC && mp2vi->cbSequenceHeader >= 23) {
      BYTE * bHEVCHeader = (BYTE *)mp2vi->dwSequenceHeader;
      int nal_len_size = (bHEVCHeader[21] & 3) + 1;
      if (nal_len_size != mp2vi->dwFlags) {
        DbgLog((LOG_ERROR, 10, L"hvcC nal length size doesn't match media type"));
      }
      m_AnnexBConverter->ConvertHEVCExtradata(&annexBextra, &size,  (BYTE *)mp2vi->dwSequenceHeader, mp2vi->cbSequenceHeader);
    }

    if (annexBextra && size) {
      memcpy(m_VideoParserExInfo.raw_seqhdr_data, annexBextra, size);
      m_VideoParserExInfo.format.seqhdr_data_length = size;
      av_freep(&annexBextra);
    }

    m_AnnexBConverter->SetNALUSize(mp2vi->dwFlags);
  } else {
    size_t hdr_len = 0;
    getExtraData(*pmt, nullptr, &hdr_len);
    if (hdr_len <= 1024) {
      getExtraData(*pmt, m_VideoParserExInfo.raw_seqhdr_data, &hdr_len);
      m_VideoParserExInfo.format.seqhdr_data_length = (unsigned int)hdr_len;
    }
  }

  m_bNeedSequenceCheck = FALSE;
  if (m_VideoParserExInfo.format.seqhdr_data_length) {
    if (cudaCodec == cudaVideoCodec_H264) {
      hr = CheckH264Sequence(m_VideoParserExInfo.raw_seqhdr_data, m_VideoParserExInfo.format.seqhdr_data_length);
      if (FAILED(hr)) {
        return VFW_E_UNSUPPORTED_VIDEO;
      } else if (hr == S_FALSE) {
        m_bNeedSequenceCheck = TRUE;
      }
    } else if (cudaCodec == cudaVideoCodec_MPEG2) {
      DbgLog((LOG_TRACE, 10, L"-> Scanning extradata for MPEG2 sequence header"));
      CMPEG2HeaderParser mpeg2parser(m_VideoParserExInfo.raw_seqhdr_data, m_VideoParserExInfo.format.seqhdr_data_length);
      if (mpeg2parser.hdr.valid) {
        if (mpeg2parser.hdr.chroma >= 2) {
          DbgLog((LOG_TRACE, 10, L"  -> Sequence header indicates incompatible chroma sampling (chroma: %d)", mpeg2parser.hdr.chroma));
          return VFW_E_UNSUPPORTED_VIDEO;
        }
        m_bInterlaced = mpeg2parser.hdr.interlaced;
      }
    } else if (cudaCodec == cudaVideoCodec_VC1) {
      CVC1HeaderParser vc1Parser(m_VideoParserExInfo.raw_seqhdr_data, m_VideoParserExInfo.format.seqhdr_data_length);
      m_bInterlaced = vc1Parser.hdr.interlaced;
    } else if (cudaCodec == cudaVideoCodec_HEVC) {
      hr = CheckHEVCSequence(m_VideoParserExInfo.raw_seqhdr_data, m_VideoParserExInfo.format.seqhdr_data_length);
      if (FAILED(hr)) {
        return VFW_E_UNSUPPORTED_VIDEO;
      } else if (hr == S_FALSE) {
        m_bNeedSequenceCheck = TRUE;
      }
    }
  } else {
    m_bNeedSequenceCheck = (cudaCodec == cudaVideoCodec_H264 || cudaCodec == cudaVideoCodec_HEVC);
  }

  oVideoParserParameters.pExtVideoInfo = &m_VideoParserExInfo;
  CUresult oResult = cuda.cuvidCreateVideoParser(&m_hParser, &oVideoParserParameters);
  if (oResult != CUDA_SUCCESS) {
    DbgLog((LOG_ERROR, 10, L"-> Creating parser for type %d failed with code %d", cudaCodec, oResult));
    return E_FAIL;
  }

  {
    cuda.cuvidCtxLock(m_cudaCtxLock, 0);
    oResult = cuda.cuStreamCreate(&m_hStream, 0);
    cuda.cuvidCtxUnlock(m_cudaCtxLock, 0);
    if (oResult != CUDA_SUCCESS) {
      DbgLog((LOG_ERROR, 10, L"::InitCodec(): Creating stream failed"));
      return E_FAIL;
    }
  }

  BITMAPINFOHEADER *bmi = nullptr;
  videoFormatTypeHandler(pmt->Format(), pmt->FormatType(), &bmi);

  {
    hr = CreateCUVIDDecoder(cudaCodec, bmi->biWidth, bmi->biHeight);
    if (FAILED(hr)) {
      DbgLog((LOG_ERROR, 10, L"-> Creating CUVID decoder failed"));
      return hr;
    }
  }

  m_bForceSequenceUpdate = TRUE;

  DecodeSequenceData();

  return S_OK;
}

STDMETHODIMP CDecCuvid::CreateCUVIDDecoder(cudaVideoCodec codec, DWORD dwWidth, DWORD dwHeight)
{
  DbgLog((LOG_TRACE, 10, L"CDecCuvid::CreateCUVIDDecoder(): Creating CUVID decoder instance"));
  HRESULT hr = S_OK;
  BOOL bDXVAMode = (m_pD3DDevice && m_pSettings->GetHWAccelDeintHQ() && IsVistaOrNewer()) || (codec == cudaVideoCodec_HEVC);

  cuda.cuvidCtxLock(m_cudaCtxLock, 0);
  CUVIDDECODECREATEINFO *dci = &m_VideoDecoderInfo;

retry:
  if (m_hDecoder) {
    cuda.cuvidDestroyDecoder(m_hDecoder);
    m_hDecoder = 0;
  }
  ZeroMemory(dci, sizeof(*dci));
  dci->ulWidth             = dwWidth;
  dci->ulHeight            = dwHeight;
  dci->ulNumDecodeSurfaces = MAX_DECODE_FRAMES;
  dci->CodecType           = codec;
  dci->ChromaFormat        = cudaVideoChromaFormat_420;
  dci->OutputFormat        = cudaVideoSurfaceFormat_NV12;
  dci->DeinterlaceMode     = (cudaVideoDeinterlaceMode)m_pSettings->GetHWAccelDeintMode();
  dci->ulNumOutputSurfaces = 1;

  dci->ulTargetWidth       = dwWidth;
  dci->ulTargetHeight      = dwHeight;

  // can't provide the original values here, or the decoder starts doing weird things - scaling to the size and cropping afterwards
  dci->display_area.right  = (short)dwWidth;
  dci->display_area.bottom = (short)dwHeight;

  dci->ulCreationFlags     = bDXVAMode ? cudaVideoCreate_PreferDXVA : cudaVideoCreate_PreferCUVID;
  dci->vidLock             = m_cudaCtxLock;

  // create the decoder
  CUresult oResult = cuda.cuvidCreateDecoder(&m_hDecoder, dci);
  if (oResult != CUDA_SUCCESS) {
    DbgLog((LOG_ERROR, 10, L"-> Creation of decoder for type %d failed with code %d", dci->CodecType, oResult));
    if (bDXVAMode) {
      DbgLog((LOG_ERROR, 10, L"  -> Retrying in pure CUVID mode"));
      bDXVAMode = FALSE;
      goto retry;
    }
    hr = E_FAIL;
  }
  cuda.cuvidCtxUnlock(m_cudaCtxLock, 0);

  return hr;
}

STDMETHODIMP CDecCuvid::DecodeSequenceData()
{
  CUresult oResult;

  CUVIDSOURCEDATAPACKET pCuvidPacket;
  ZeroMemory(&pCuvidPacket, sizeof(pCuvidPacket));

  pCuvidPacket.payload      = m_VideoParserExInfo.raw_seqhdr_data;
  pCuvidPacket.payload_size = m_VideoParserExInfo.format.seqhdr_data_length;

  if (pCuvidPacket.payload && pCuvidPacket.payload_size) {
    cuda.cuvidCtxLock(m_cudaCtxLock, 0);
    oResult = cuda.cuvidParseVideoData(m_hParser, &pCuvidPacket);
    cuda.cuvidCtxUnlock(m_cudaCtxLock, 0);
  }

  return S_OK;
}

CUVIDPARSERDISPINFO* CDecCuvid::GetNextFrame()
{
  int next = (m_DisplayPos + 1) % m_DisplayDelay;
  return &m_DisplayQueue[next];
}

int CUDAAPI CDecCuvid::HandleVideoSequence(void *obj, CUVIDEOFORMAT *cuvidfmt)
{
  DbgLog((LOG_TRACE, 10, L"CDecCuvid::HandleVideoSequence(): New Video Sequence"));
  CDecCuvid *filter = static_cast<CDecCuvid *>(obj);

  CUVIDDECODECREATEINFO *dci = &filter->m_VideoDecoderInfo;

  if ((cuvidfmt->codec != dci->CodecType)
    || (cuvidfmt->coded_width != dci->ulWidth)
    || (cuvidfmt->coded_height != dci->ulHeight)
    || (cuvidfmt->chroma_format != dci->ChromaFormat)
    || filter->m_bForceSequenceUpdate)
  {
    filter->m_bForceSequenceUpdate = FALSE;
    filter->CreateCUVIDDecoder(cuvidfmt->codec, cuvidfmt->coded_width, cuvidfmt->coded_height);
  }

  filter->m_bInterlaced = !cuvidfmt->progressive_sequence;
  filter->m_bDoubleRateDeint = filter->m_bInterlaced && (filter->m_pSettings->GetHWAccelDeintOutput() == DeintOutput_FramePerField) && (filter->m_VideoDecoderInfo.DeinterlaceMode != cudaVideoDeinterlaceMode_Weave) && !(filter->m_pSettings->GetDeinterlacingMode() == DeintMode_Disable);
  if (filter->m_bInterlaced && cuvidfmt->frame_rate.numerator && cuvidfmt->frame_rate.denominator) {
    double dFrameTime = 10000000.0 / ((double)cuvidfmt->frame_rate.numerator / cuvidfmt->frame_rate.denominator);
    if (filter->m_bDoubleRateDeint && (int)(dFrameTime / 10000.0) == 41) {
      filter->m_bDoubleRateDeint = TRUE;
    }
    if (cuvidfmt->codec != cudaVideoCodec_MPEG4)
      filter->m_rtAvgTimePerFrame = REFERENCE_TIME(dFrameTime + 0.5);
    else
      filter->m_rtAvgTimePerFrame = AV_NOPTS_VALUE; //TODO: base on media type
  } else {
    filter->m_rtAvgTimePerFrame = AV_NOPTS_VALUE;
  }

  // Adjust frame time for double-rate deint
  if (filter->m_bDoubleRateDeint && filter->m_rtAvgTimePerFrame != AV_NOPTS_VALUE)
    filter->m_rtAvgTimePerFrame /= 2;

  filter->m_VideoFormat = *cuvidfmt;

  if (cuvidfmt->chroma_format != cudaVideoChromaFormat_420) {
    DbgLog((LOG_TRACE, 10, L"CDecCuvid::HandleVideoSequence(): Incompatible Chroma Format detected"));
    filter->m_bFormatIncompatible = TRUE;
  }

  fillDXVAExtFormat(filter->m_DXVAExtendedFormat, filter->m_iFullRange, cuvidfmt->video_signal_description.color_primaries, cuvidfmt->video_signal_description.matrix_coefficients, cuvidfmt->video_signal_description.transfer_characteristics);

  return TRUE;
}

int CUDAAPI CDecCuvid::HandlePictureDecode(void *obj, CUVIDPICPARAMS *cuvidpic)
{
  CDecCuvid *filter = reinterpret_cast<CDecCuvid *>(obj);

  if (filter->m_bFlushing)
    return FALSE;

  if (filter->m_bWaitForKeyframe) {
    if (cuvidpic->intra_pic_flag)
      filter->m_bWaitForKeyframe = FALSE;
    else {
      // Pop timestamp from the queue, drop frame
      if (!filter->m_timestampQueue.empty()) {
        filter->m_timestampQueue.pop();
      }
      return FALSE;
    }
  }

  int flush_pos = filter->m_DisplayPos;
  for (;;) {
    bool frame_in_use = false;
    for (int i=0; i<filter->m_DisplayDelay; i++) {
      if (filter->m_DisplayQueue[i].picture_index == cuvidpic->CurrPicIdx) {
        frame_in_use = true;
        break;
      }
    }
    if (!frame_in_use) {
      // No problem: we're safe to use this frame
      break;
    }
    // The target frame is still pending in the display queue:
    // Flush the oldest entry from the display queue and repeat
    if (filter->m_DisplayQueue[flush_pos].picture_index >= 0) {
      filter->Display(&filter->m_DisplayQueue[flush_pos]);
      filter->m_DisplayQueue[flush_pos].picture_index = -1;
    }
    flush_pos = (flush_pos + 1) % filter->m_DisplayDelay;
  }

  filter->cuda.cuvidCtxLock(filter->m_cudaCtxLock, 0);
  filter->m_PicParams[cuvidpic->CurrPicIdx] = *cuvidpic;
  __try {
    CUresult cuStatus = filter->cuda.cuvidDecodePicture(filter->m_hDecoder, cuvidpic);
  #ifdef DEBUG
    if (cuStatus != CUDA_SUCCESS) {
      DbgLog((LOG_ERROR, 10, L"CDecCuvid::HandlePictureDecode(): cuvidDecodePicture returned error code %d", cuStatus));
    }
  #endif
  } __except(1) {
    DbgLog((LOG_ERROR, 10, L"CDecCuvid::HandlePictureDecode(): cuvidDecodePicture threw an exception"));
  }
  filter->cuda.cuvidCtxUnlock(filter->m_cudaCtxLock, 0);

  return TRUE;
}

int CUDAAPI CDecCuvid::HandlePictureDisplay(void *obj, CUVIDPARSERDISPINFO *cuviddisp)
{
  CDecCuvid *filter = reinterpret_cast<CDecCuvid *>(obj);

  if (filter->m_bFlushing)
    return FALSE;

  if (filter->m_bUseTimestampQueue) {
    if (filter->m_timestampQueue.empty()) {
      cuviddisp->timestamp = AV_NOPTS_VALUE;
    } else {
      cuviddisp->timestamp = filter->m_timestampQueue.front();
      filter->m_timestampQueue.pop();
    }
  }

  // Drop samples with negative timestamps (preroll) or during flushing
  if (cuviddisp->timestamp != AV_NOPTS_VALUE && cuviddisp->timestamp < 0)
    return TRUE;

  if (filter->m_DisplayQueue[filter->m_DisplayPos].picture_index >= 0) {
    filter->Display(&filter->m_DisplayQueue[filter->m_DisplayPos]);
    filter->m_DisplayQueue[filter->m_DisplayPos].picture_index = -1;
  }
  filter->m_DisplayQueue[filter->m_DisplayPos] = *cuviddisp;
  filter->m_DisplayPos = (filter->m_DisplayPos + 1) % filter->m_DisplayDelay;

  return TRUE;
}

STDMETHODIMP CDecCuvid::Display(CUVIDPARSERDISPINFO *cuviddisp)
{
  BOOL bTreatAsProgressive = m_pSettings->GetDeinterlacingMode() == DeintMode_Disable;

  if (bTreatAsProgressive) {
    cuviddisp->progressive_frame = TRUE;
    m_nSoftTelecine = FALSE;
  } else {
    if (m_VideoFormat.codec == cudaVideoCodec_MPEG2 || m_VideoFormat.codec == cudaVideoCodec_H264) {
      if (cuviddisp->repeat_first_field) {
        m_nSoftTelecine = 2;
      } else if (m_nSoftTelecine) {
        m_nSoftTelecine--;
      }
      if (!m_nSoftTelecine)
        m_bTFF = cuviddisp->top_field_first;
    }

    cuviddisp->progressive_frame = (cuviddisp->progressive_frame && !(m_bInterlaced && m_pSettings->GetDeinterlacingMode() == DeintMode_Aggressive && m_VideoFormat.codec != cudaVideoCodec_VC1 && !m_nSoftTelecine) && !(m_pSettings->GetDeinterlacingMode() == DeintMode_Force));
  }

  LAVDeintFieldOrder fo        = m_pSettings->GetDeintFieldOrder();
  cuviddisp->top_field_first   = (fo == DeintFieldOrder_Auto) ? (m_nSoftTelecine ? m_bTFF : cuviddisp->top_field_first) : (fo == DeintFieldOrder_TopFieldFirst);

  if (m_bDoubleRateDeint) {
    if (cuviddisp->progressive_frame || m_nSoftTelecine) {
      Deliver(cuviddisp, 2);
    } else {
      Deliver(cuviddisp, 0);
      Deliver(cuviddisp, 1);
    }
  } else {
    Deliver(cuviddisp);
  }
  return S_OK;
}

STDMETHODIMP CDecCuvid::Deliver(CUVIDPARSERDISPINFO *cuviddisp, int field)
{
  CUdeviceptr devPtr = 0;
  unsigned int pitch = 0;
  CUVIDPROCPARAMS vpp;
  CUresult cuStatus = CUDA_SUCCESS;

  memset(&vpp, 0, sizeof(vpp));
  vpp.progressive_frame = !m_nSoftTelecine && cuviddisp->progressive_frame;
  vpp.top_field_first = cuviddisp->top_field_first;
  vpp.second_field = (field == 1);

  cuda.cuvidCtxLock(m_cudaCtxLock, 0);
  cuStatus = cuda.cuvidMapVideoFrame(m_hDecoder, cuviddisp->picture_index, &devPtr, &pitch, &vpp);
  if (cuStatus != CUDA_SUCCESS) {
    DbgLog((LOG_CUSTOM1, 1, L"CDecCuvid::Deliver(): cuvidMapVideoFrame failed on index %d", cuviddisp->picture_index));
    goto cuda_fail;
  }

  int size = pitch * m_VideoDecoderInfo.ulTargetHeight * 3 / 2;
  if(!m_pbRawNV12 || size > m_cRawNV12) {
    if (m_pbRawNV12) {
      cuda.cuMemFreeHost(m_pbRawNV12);
      m_pbRawNV12 = nullptr;
      m_cRawNV12 = 0;
    }
    cuStatus = cuda.cuMemAllocHost((void **)&m_pbRawNV12, size);
    if (cuStatus != CUDA_SUCCESS) {
      DbgLog((LOG_CUSTOM1, 1, L"CDecCuvid::Deliver(): cuMemAllocHost failed to allocate %d bytes (%d)", size, cuStatus));
      goto cuda_fail;
    }
    m_cRawNV12 = size;
  }
  // Copy memory from the device into the staging area
  if (m_pbRawNV12) {
#if USE_ASYNC_COPY
    cuStatus = cuda.cuMemcpyDtoHAsync(m_pbRawNV12, devPtr, size, m_hStream);
    if (cuStatus != CUDA_SUCCESS) {
      DbgLog((LOG_ERROR, 10, L"Async Memory Transfer failed (%d)", cuStatus));
      goto cuda_fail;
    }
    while (CUDA_ERROR_NOT_READY == cuda.cuStreamQuery(m_hStream)) {
      Sleep(1);
    }
#else
    cuStatus = cuda.cuMemcpyDtoH(m_pbRawNV12, devPtr, size);
    if (cuStatus != CUDA_SUCCESS) {
      DbgLog((LOG_ERROR, 10, L"Memory Transfer failed (%d)", cuStatus));
      goto cuda_fail;
    }
#endif
  } else {
    // If we don't have our memory, this is bad.
    DbgLog((LOG_ERROR, 10, L"No Valid Staging Memory - failing"));
    goto cuda_fail;
  }
  cuda.cuvidUnmapVideoFrame(m_hDecoder, devPtr);
  cuda.cuvidCtxUnlock(m_cudaCtxLock, 0);


  // Setup the LAVFrame
  LAVFrame *pFrame = nullptr;
  AllocateFrame(&pFrame);

  if (m_rtAvgTimePerFrame != AV_NOPTS_VALUE) {
    pFrame->avgFrameDuration = m_rtAvgTimePerFrame;
    if (m_bDoubleRateDeint && field == 2)
      pFrame->avgFrameDuration *= 2;
  }

  REFERENCE_TIME rtStart = cuviddisp->timestamp, rtStop = AV_NOPTS_VALUE;
  if (rtStart != AV_NOPTS_VALUE) {
    CUVIDPARSERDISPINFO *next = GetNextFrame();
    if (next->picture_index != -1 && next->timestamp != AV_NOPTS_VALUE) {
      m_rtPrevDiff = next->timestamp - cuviddisp->timestamp;
    }

    if (m_rtPrevDiff != AV_NOPTS_VALUE) {
      REFERENCE_TIME rtHalfDiff = m_rtPrevDiff >> 1;
      if (field == 1)
        rtStart += rtHalfDiff;

      rtStop = rtStart + rtHalfDiff;

      if (field == 2 || !m_bDoubleRateDeint)
        rtStop += rtHalfDiff;
    }

    // Sanity check in case the duration is null
    if (rtStop <= rtStart)
      rtStop = AV_NOPTS_VALUE;
  }

  pFrame->format = LAVPixFmt_NV12;
  pFrame->width  = m_VideoFormat.display_area.right;
  pFrame->height = m_VideoFormat.display_area.bottom;
  pFrame->rtStart = rtStart;
  pFrame->rtStop = rtStop;
  pFrame->repeat = cuviddisp->repeat_first_field;
  {
    AVRational ar = { m_VideoFormat.display_aspect_ratio.x, m_VideoFormat.display_aspect_ratio.y };
    AVRational arDim = { pFrame->width, pFrame->height };
    if (m_bARPresent || av_cmp_q(ar, arDim) != 0) {
      pFrame->aspect_ratio = ar;
    }
  }
  pFrame->ext_format = m_DXVAExtendedFormat;
  pFrame->interlaced = !cuviddisp->progressive_frame && m_VideoDecoderInfo.DeinterlaceMode == cudaVideoDeinterlaceMode_Weave;
  pFrame->tff = cuviddisp->top_field_first;

  // TODO: This may be wrong for H264 where B-Frames can be references
  pFrame->frame_type = m_PicParams[cuviddisp->picture_index].intra_pic_flag ? 'I' : (m_PicParams[cuviddisp->picture_index].ref_pic_flag ? 'P' : 'B');

  // Assign the buffer to the LAV Frame bufers
  int Ysize = m_VideoDecoderInfo.ulTargetHeight * pitch;
  pFrame->data[0] = m_pbRawNV12;
  pFrame->data[1] = m_pbRawNV12+Ysize;
  pFrame->stride[0] = pFrame->stride[1] = pitch;
  pFrame->flags  |= LAV_FRAME_FLAG_BUFFER_MODIFY;

  if (m_bEndOfSequence)
    pFrame->flags |= LAV_FRAME_FLAG_END_OF_SEQUENCE;

  m_pCallback->Deliver(pFrame);

  return S_OK;

cuda_fail:
  cuda.cuvidUnmapVideoFrame(m_hDecoder, devPtr);
  cuda.cuvidCtxUnlock(m_cudaCtxLock, 0);
  return E_FAIL;
}

STDMETHODIMP CDecCuvid::CheckH264Sequence(const BYTE *buffer, int buflen)
{
  DbgLog((LOG_TRACE, 10, L"CDecCuvid::CheckH264Sequence(): Checking H264 frame for SPS"));
  CH264SequenceParser h264parser;
  h264parser.ParseNALs(buffer, buflen, 0);
  if (h264parser.sps.valid) {
    m_bInterlaced = h264parser.sps.interlaced;
    m_iFullRange = h264parser.sps.full_range;
    m_bARPresent = h264parser.sps.ar_present;
    DbgLog((LOG_TRACE, 10, L"-> SPS found"));
    if (h264parser.sps.profile > 100 || h264parser.sps.chroma != 1 || h264parser.sps.luma_bitdepth != 8 || h264parser.sps.chroma_bitdepth != 8) {
      DbgLog((LOG_TRACE, 10, L"  -> SPS indicates video incompatible with CUVID, aborting (profile: %d, chroma: %d, bitdepth: %d/%d)", h264parser.sps.profile, h264parser.sps.chroma, h264parser.sps.luma_bitdepth, h264parser.sps.chroma_bitdepth));
      return E_FAIL;
    }
    DbgLog((LOG_TRACE, 10, L"-> Video seems compatible with CUVID"));
    return S_OK;
  }
  return S_FALSE;
}

STDMETHODIMP CDecCuvid::CheckHEVCSequence(const BYTE *buffer, int buflen)
{
  DbgLog((LOG_TRACE, 10, L"CDecCuvid::CheckHEVCSequence(): Checking HEVC frame for SPS"));
  CHEVCSequenceParser hevcParser;
  hevcParser.ParseNALs(buffer, buflen, 0);
  if (hevcParser.sps.valid) {
    DbgLog((LOG_TRACE, 10, L"-> SPS found"));
    if (hevcParser.sps.profile > FF_PROFILE_HEVC_MAIN) {
      DbgLog((LOG_TRACE, 10, L"  -> SPS indicates video incompatible with CUVID, aborting (profile: %d)", hevcParser.sps.profile));
      return E_FAIL;
    }
    DbgLog((LOG_TRACE, 10, L"-> Video seems compatible with CUVID"));
    return S_OK;
  }
  return S_FALSE;
}

STDMETHODIMP CDecCuvid::Decode(const BYTE *buffer, int buflen, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop, BOOL bSyncPoint, BOOL bDiscontinuity)
{
  CUresult result;
  HRESULT hr = S_OK;

  CUVIDSOURCEDATAPACKET pCuvidPacket;
  ZeroMemory(&pCuvidPacket, sizeof(pCuvidPacket));

  BYTE *pBuffer = nullptr;
  if (m_AnnexBConverter) {
    int size = 0;
    hr = m_AnnexBConverter->Convert(&pBuffer, &size, buffer, buflen);
    if (SUCCEEDED(hr)) {
      pCuvidPacket.payload      = pBuffer;
      pCuvidPacket.payload_size = size;
    }
  } else {
    pCuvidPacket.payload      = buffer;
    pCuvidPacket.payload_size = buflen;

    if (m_VideoDecoderInfo.CodecType == cudaVideoCodec_MPEG2) {
      const uint8_t *eosmarker = CheckForEndOfSequence(AV_CODEC_ID_MPEG2VIDEO, buffer, buflen, &m_MpegParserState);
      const uint8_t *end = buffer+buflen;
      // If we found a EOS marker, but its not at the end of the packet, then split the packet
      // to be able to individually decode the frame before the EOS, and then decode the remainder
      if (eosmarker && eosmarker != end) {
        Decode(buffer, (eosmarker - buffer), rtStart, rtStop, bSyncPoint, bDiscontinuity);

        rtStart = rtStop = AV_NOPTS_VALUE;
        pCuvidPacket.payload      = eosmarker;
        pCuvidPacket.payload_size = end - eosmarker;
      } else if (eosmarker) {
        m_bEndOfSequence = TRUE;
      }
    }
  }

  if (m_bNeedSequenceCheck) {
    if (m_VideoDecoderInfo.CodecType == cudaVideoCodec_H264) {
      hr = CheckH264Sequence(pCuvidPacket.payload, pCuvidPacket.payload_size);
    } else if (m_VideoDecoderInfo.CodecType == cudaVideoCodec_HEVC) {
      hr = CheckHEVCSequence(pCuvidPacket.payload, pCuvidPacket.payload_size);
    }
    if (FAILED(hr)) {
      m_bFormatIncompatible = TRUE;
    } else if (hr == S_OK) {
      m_bNeedSequenceCheck = FALSE;
    }
  }

  if (rtStart != AV_NOPTS_VALUE) {
    pCuvidPacket.flags     |= CUVID_PKT_TIMESTAMP;
    pCuvidPacket.timestamp  = rtStart;
  }

  if (bDiscontinuity)
    pCuvidPacket.flags     |= CUVID_PKT_DISCONTINUITY;

  if (m_bUseTimestampQueue)
    m_timestampQueue.push(rtStart);

  cuda.cuvidCtxLock(m_cudaCtxLock, 0);
  __try {
    result = cuda.cuvidParseVideoData(m_hParser, &pCuvidPacket);
  } __except(1) {
    DbgLog((LOG_ERROR, 10, L"CDecCuvid::Decode(): cuvidParseVideoData threw an exception"));
  }
  cuda.cuvidCtxUnlock(m_cudaCtxLock, 0);

  av_freep(&pBuffer);

  if (m_bEndOfSequence) {
    EndOfStream();
    m_pCallback->Deliver(m_pCallback->GetFlushFrame());
    m_bEndOfSequence = FALSE;
  }

  if (m_bFormatIncompatible) {
    DbgLog((LOG_ERROR, 10, L"CDecCuvid::Decode(): Incompatible format detected, indicating failure..."));
    return E_FAIL;
  }

  return S_OK;
}

STDMETHODIMP CDecCuvid::Flush()
{
  DbgLog((LOG_TRACE, 10, L"CDecCuvid::Flush(): Flushing CUVID decoder"));
  m_bFlushing = TRUE;

  FlushParser();

  // Flush display queue
  for (int i=0; i<m_DisplayDelay; ++i) {
    if (m_DisplayQueue[m_DisplayPos].picture_index >= 0) {
      m_DisplayQueue[m_DisplayPos].picture_index = -1;
    }
    m_DisplayPos = (m_DisplayPos + 1) % m_DisplayDelay;
  }

  m_bFlushing = FALSE;
  m_bWaitForKeyframe = m_bUseTimestampQueue;

  // Re-init decoder after flush
  DecodeSequenceData();

  // Clear timestamp queue
  std::queue<REFERENCE_TIME>().swap(m_timestampQueue);

  m_nSoftTelecine = 0;

  return __super::Flush();
}

STDMETHODIMP CDecCuvid::EndOfStream()
{
  FlushParser();

  // Display all frames left in the queue
  for (int i=0; i<m_DisplayDelay; ++i) {
    if (m_DisplayQueue[m_DisplayPos].picture_index >= 0) {
      Display(&m_DisplayQueue[m_DisplayPos]);
      m_DisplayQueue[m_DisplayPos].picture_index = -1;
    }
    m_DisplayPos = (m_DisplayPos + 1) % m_DisplayDelay;
  }

  return S_OK;
}

STDMETHODIMP CDecCuvid::GetPixelFormat(LAVPixelFormat *pPix, int *pBpp)
{
  // Output is always NV12
  if (pPix)
    *pPix = LAVPixFmt_NV12;
  if (pBpp)
    *pBpp = 8;
  return S_OK;
}

STDMETHODIMP_(REFERENCE_TIME) CDecCuvid::GetFrameDuration()
{
  return 0;
}

STDMETHODIMP_(BOOL) CDecCuvid::IsInterlaced()
{
  return (m_bInterlaced || m_pSettings->GetDeinterlacingMode() == DeintMode_Force) && (m_VideoDecoderInfo.DeinterlaceMode == cudaVideoDeinterlaceMode_Weave);
}