-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodecmap.ps1
More file actions
1287 lines (1182 loc) · 53 KB
/
Copy pathcodecmap.ps1
File metadata and controls
1287 lines (1182 loc) · 53 KB
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
#Requires -Version 5.1
<#
codecmap - the hardware video codec map for this PC.
Two different Windows subsystems answer two different halves of the
question "can this machine encode or decode codec X in hardware", and
neither one is shown to a user anywhere.
Encoding is answered by Media Foundation: MFTEnumEx reports the hardware
transforms a driver registered, which is exactly the list OBS, Camtasia,
the Xbox Game Bar and every other capture app pick their encoder from.
Decoding is answered by Direct3D 11: each adapter publishes a list of
DXVA decoder profile GUIDs it can accelerate.
dxdiag prints the driver DLL file names and a wall of DirectShow filters.
It never says which codecs you can actually encode, it never names Quick
Sync even when Quick Sync is installed, and it happily mentions AV1 on a
machine with no AV1 hardware at all.
Read-only. Zero dependencies. Windows PowerShell 5.1.
codecmap never instantiates a codec and never touches a file you own.
#>
param(
[string]$Codec,
[switch]$Encoders,
[switch]$Decoders,
[switch]$Detail,
[switch]$Software,
[switch]$Adapters,
[switch]$Json,
[string]$Save,
[string]$FromJson,
[string]$FailIfMissing,
[switch]$Info,
[switch]$Quiet,
[switch]$NoColor,
[switch]$Version,
[switch]$Help
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
# ---------------------------------------------------------------------------
# constants
# ---------------------------------------------------------------------------
$script:ToolVersion = '1.0.0'
$script:ExitCode = 0
$script:Silent = $false
# exit codes
$script:ExitUsage = 2
$script:ExitMissing = 3
$script:ExitNoQuery = 4
$script:SchemaVersion = 1
# Media Foundation transform categories
$script:CatVideoEncoder = 'f79eac7d-e545-4387-bdee-d647d7bde42a'
$script:CatVideoDecoder = 'd6c02d4b-6833-45b4-971a-05a4b04bab91'
# MFT_ENUM_FLAG values
$script:MftSync = 0x01
$script:MftAsync = 0x02
$script:MftHardware = 0x04
$script:MftSortFilt = 0x40
# PCI vendor ids that ship video engines
$script:VendorNames = @{
'0x10de' = 'NVIDIA'
'0x8086' = 'Intel'
'0x1002' = 'AMD'
'0x1022' = 'AMD'
'0x1414' = 'Microsoft'
'0x5333' = 'S3'
'0x1106' = 'VIA'
'0x13b5' = 'Arm'
'0x14e4' = 'Broadcom'
'0x1af4' = 'Red Hat'
'0x15ad' = 'VMware'
}
# MFT_ENUM_HARDWARE_VENDOR_ID_Attribute strings, which are "VEN_xxxx"
$script:MftVendorNames = @{
'VEN_10DE' = 'NVIDIA'
'VEN_8086' = 'Intel'
'VEN_1002' = 'AMD'
'VEN_1022' = 'AMD'
'VEN_1414' = 'Microsoft'
}
# The codec table.
# Fourcc - MFVideoFormat subtype used to filter the encoder query.
# DecodeProfiles- D3D11 decoder profile GUIDs, mapped to the profile name.
# Every GUID below is from d3d11.h / dxva.h. Profiles that are not in this
# table are reported by GUID rather than guessed at.
$script:Codecs = @(
@{ Key = 'h264'; Label = 'H.264'; Aka = @('avc', 'h.264', 'avc1');
Fourcc = 'H264';
DecodeProfiles = [ordered]@{
'1b81be64-a0c7-11d3-b984-00c04f2e73c5' = 'MoComp NoFGT'
'1b81be65-a0c7-11d3-b984-00c04f2e73c5' = 'MoComp FGT'
'1b81be66-a0c7-11d3-b984-00c04f2e73c5' = 'IDCT NoFGT'
'1b81be67-a0c7-11d3-b984-00c04f2e73c5' = 'IDCT FGT'
'1b81be68-a0c7-11d3-b984-00c04f2e73c5' = 'VLD NoFGT'
'1b81be69-a0c7-11d3-b984-00c04f2e73c5' = 'VLD FGT'
'd5f04ff9-3418-45d8-9561-32a76aae2ddd' = 'VLD FMO/ASO'
'd79be8da-0cf1-4c81-b82a-69a4e236f43d' = 'VLD Stereo Progressive'
'f9aaccbb-c2b6-4cfc-8779-5707b1760552' = 'VLD Stereo'
'705b9d82-76cf-49d6-b7e6-ac8872db013c' = 'VLD Multiview'
} },
@{ Key = 'hevc'; Label = 'HEVC'; Aka = @('h265', 'h.265');
Fourcc = 'HEVC';
DecodeProfiles = [ordered]@{
'5b11d51b-2f4c-4452-bcc3-09f2a1160cc0' = 'Main'
'107af0e0-ef1a-4d19-aba8-67a163073d13' = 'Main10'
} },
@{ Key = 'av1'; Label = 'AV1'; Aka = @('av01');
Fourcc = 'AV01';
DecodeProfiles = [ordered]@{
'b8be4ccb-cf53-46ba-8d59-d6b8a6da5d2a' = 'Profile 0'
'6936ff0f-45b1-4163-9cc1-646ef6946108' = 'Profile 1'
'0c5f2aa1-e541-4089-bb7b-98110a19d7c8' = 'Profile 2'
'17127009-a00f-4ce1-994e-bf4081f6f3f0' = '12-bit Profile 2'
'2d80bed6-9cac-4835-9e91-327bbc4f9ee8' = '12-bit Profile 2 4:2:0'
} },
@{ Key = 'vp9'; Label = 'VP9'; Aka = @('vp90');
Fourcc = 'VP90';
DecodeProfiles = [ordered]@{
'463707f8-a1d0-4585-876d-83aa6d60b89e' = 'Profile 0'
'a4c749ef-6ecf-48aa-8448-50a7a1165ff7' = '10-bit Profile 2'
} },
@{ Key = 'vp8'; Label = 'VP8'; Aka = @('vp80');
Fourcc = 'VP80';
DecodeProfiles = [ordered]@{
'90b899ea-3a62-4705-88b3-8df04b2744e7' = 'VLD'
} },
@{ Key = 'mpeg2'; Label = 'MPEG-2'; Aka = @('mpeg-2', 'm2v');
Fourcc = $null;
DecodeProfiles = [ordered]@{
'e6a9f44b-61b0-4563-9ea4-63d2a3c6fe66' = 'MoComp'
'bf22ad00-03ea-4690-8077-473346209b7e' = 'IDCT'
'ee27417f-5e28-4e65-beea-1d26b508adc9' = 'VLD'
'86695f12-340e-4f04-9fd3-9253dd327460' = 'VLD (with MPEG-1)'
} },
@{ Key = 'mpeg4'; Label = 'MPEG-4 p2'; Aka = @('mpeg4', 'divx', 'xvid');
Fourcc = $null;
DecodeProfiles = [ordered]@{
'efd64d74-c9e8-41d7-a5e9-e9b0e39fa319' = 'Simple'
'ed418a9f-010d-4eda-9ae3-9a65358d8d2e' = 'Advanced Simple NoGMC'
'ab998b5b-4258-44a9-9feb-94e597a6baae' = 'Advanced Simple GMC'
} },
@{ Key = 'vc1'; Label = 'VC-1'; Aka = @('wmv3', 'wvc1');
Fourcc = $null;
DecodeProfiles = [ordered]@{
'1b81bea0-a0c7-11d3-b984-00c04f2e73c5' = 'PostProc'
'1b81bea1-a0c7-11d3-b984-00c04f2e73c5' = 'MoComp'
'1b81bea2-a0c7-11d3-b984-00c04f2e73c5' = 'IDCT'
'1b81bea3-a0c7-11d3-b984-00c04f2e73c5' = 'VLD'
'1b81bea4-a0c7-11d3-b984-00c04f2e73c5' = 'D2010'
} },
@{ Key = 'wmv9'; Label = 'WMV9'; Aka = @('wmv');
Fourcc = $null;
DecodeProfiles = [ordered]@{
'1b81be90-a0c7-11d3-b984-00c04f2e73c5' = 'PostProc'
'1b81be91-a0c7-11d3-b984-00c04f2e73c5' = 'MoComp'
'1b81be94-a0c7-11d3-b984-00c04f2e73c5' = 'IDCT'
} },
@{ Key = 'mjpeg'; Label = 'MJPEG'; Aka = @('mjpg', 'motion jpeg');
Fourcc = 'MJPG';
DecodeProfiles = [ordered]@{} }
)
# ---------------------------------------------------------------------------
# small helpers
# ---------------------------------------------------------------------------
# @(...).Count throws under StrictMode 2.0 when the list holds hashtables.
# A hashtable is itself an ICollection whose Count is its KEY count, which is
# never what a caller asking "how many items" wants, so it counts as one.
function Count-Of($x) {
if ($null -eq $x) { return 0 }
if ($x -is [string]) { return 1 }
if ($x -is [System.Collections.IDictionary]) { return 1 }
if ($x -is [System.Collections.ICollection]) { return $x.Count }
return 1
}
# PowerShell unrolls a returned array, so a one-element list comes back as a
# bare scalar and $list[0] then indexes the first CHARACTER of a string. Every
# array return below is comma-wrapped to stop that.
# A hashtable enumerates as DictionaryEntry objects, so it must be caught
# before the IEnumerable branch or one record silently becomes N fields.
function As-List($x) {
if ($null -eq $x) { return ,@() }
if ($x -is [string]) { return ,@($x) }
if ($x -is [System.Collections.IDictionary]) { return ,@($x) }
if ($x -is [System.Collections.IEnumerable]) {
$out = New-Object System.Collections.ArrayList
foreach ($i in $x) { [void]$out.Add($i) }
return ,$out.ToArray()
}
return ,@($x)
}
# Driver friendly names carry registered-trademark and other non-ASCII marks.
# Everything codecmap prints, saves and compares is plain 7-bit ASCII so that
# output survives redirection, code pages and diffing.
function To-Ascii([string]$s) {
if ([string]::IsNullOrEmpty($s)) { return '' }
$sb = New-Object System.Text.StringBuilder
foreach ($ch in $s.ToCharArray()) {
$c = [int]$ch
if ($c -eq 0x00AE) { [void]$sb.Append('(R)'); continue } # (R)
if ($c -eq 0x2122) { [void]$sb.Append('(TM)'); continue } # (TM)
if ($c -eq 0x00A9) { [void]$sb.Append('(C)'); continue } # (C)
if ($c -eq 0x2013 -or $c -eq 0x2014) { [void]$sb.Append('-'); continue }
if ($c -eq 0x2018 -or $c -eq 0x2019) { [void]$sb.Append("'"); continue }
if ($c -eq 0x201C -or $c -eq 0x201D) { [void]$sb.Append('"'); continue }
if ($c -ge 32 -and $c -le 126) { [void]$sb.Append($ch); continue }
if ($c -eq 9) { [void]$sb.Append(' '); continue }
[void]$sb.Append('?')
}
# collapse the runs of spaces a substitution can leave behind
return ($sb.ToString() -replace ' {2,}', ' ').Trim()
}
function Out-Line([string]$s) {
if ($script:Silent) { return }
Write-Output $s
}
function Fail-Usage([string]$msg) {
# Write-Error under ErrorActionPreference=Stop throws a terminating error,
# so the exit statement below it never runs and the process reports 1
# instead of the documented usage code. Write straight to stderr instead.
[Console]::Error.WriteLine("codecmap: $msg")
exit $script:ExitUsage
}
function Format-Mb([long]$bytes) {
if ($bytes -le 0) { return '0 MB' }
$mb = [Math]::Round($bytes / 1048576.0, 0)
if ($mb -ge 1024) { return ('{0:0.0} GB' -f ($bytes / 1073741824.0)) }
# a real but sub-megabyte allocation must not be printed as a flat zero
if ($mb -le 0) { return '<1 MB' }
return ("$mb MB")
}
function Vendor-FromId([string]$vid) {
$key = $vid.ToLowerInvariant()
if ($script:VendorNames.ContainsKey($key)) { return $script:VendorNames[$key] }
return "PCI $vid"
}
function Vendor-FromMft([string]$ven) {
if ([string]::IsNullOrEmpty($ven)) { return '' }
$key = $ven.ToUpperInvariant()
if ($script:MftVendorNames.ContainsKey($key)) { return $script:MftVendorNames[$key] }
return $key
}
function Codec-ByName([string]$name) {
if ([string]::IsNullOrEmpty($name)) { return $null }
$n = $name.Trim().ToLowerInvariant()
foreach ($c in $script:Codecs) {
if ($c.Key -eq $n) { return $c }
foreach ($a in $c.Aka) { if ($a -eq $n) { return $c } }
if ($c.Label.ToLowerInvariant() -eq $n) { return $c }
}
return $null
}
function Codec-Names() {
return ((Codec-KeyList) -join ', ')
}
# Codec-Names is the human readable form used in help and error text. Callers
# that need to iterate want the keys themselves, not one joined string.
function Codec-KeyList() {
$names = New-Object System.Collections.ArrayList
foreach ($c in $script:Codecs) { [void]$names.Add($c.Key) }
return ,$names.ToArray()
}
# ConvertFrom-Json hands back PSCustomObject trees. Everything downstream of
# the model expects hashtables, so normalise once at the boundary.
function To-Hash($o) {
if ($null -eq $o) { return $null }
if ($o -is [System.Management.Automation.PSCustomObject]) {
$h = @{}
foreach ($p in $o.PSObject.Properties) { $h[$p.Name] = To-Hash $p.Value }
return $h
}
if ($o -is [System.Collections.IDictionary]) {
$h = @{}
foreach ($k in $o.Keys) { $h["$k"] = To-Hash $o[$k] }
return $h
}
if ($o -isnot [string] -and $o -is [System.Collections.IEnumerable]) {
$l = New-Object System.Collections.ArrayList
foreach ($i in $o) { [void]$l.Add((To-Hash $i)) }
return ,$l.ToArray()
}
return $o
}
function Hash-Get($h, [string]$key, $default) {
if ($null -eq $h) { return $default }
if ($h -is [System.Collections.IDictionary]) {
if ($h.Contains($key)) {
$v = $h[$key]
if ($null -eq $v) { return $default }
return $v
}
return $default
}
return $default
}
# [IO.File] and [IO.Path] know nothing about PowerShell's current location, so
# a relative path has to be joined by hand. Joining an already-rooted path to
# the cwd produces "C:\here\C:\there" and GetFullPath then throws
# "The given path's format is not supported", so check first.
function Resolve-OutPath([string]$p) {
if ([IO.Path]::IsPathRooted($p)) { return [IO.Path]::GetFullPath($p) }
return [IO.Path]::GetFullPath((Join-Path (Get-Location).Path $p))
}
# ---------------------------------------------------------------------------
# native probe
#
# Both halves of the query live in C#. PowerShell cannot late-bind a method
# on a ComImport interface: casting the object it gets back from
# GetObjectForIUnknown fails with "cannot convert System.__ComObject", so the
# entire COM walk has to finish on the C# side and hand back flat strings.
# ---------------------------------------------------------------------------
function Initialize-Native {
if ('CodecMapNative' -as [type]) { return }
Add-Type -TypeDefinition @'
using System;
using System.Text;
using System.Collections.Generic;
using System.Runtime.InteropServices;
[ComImport, Guid("2cd2d921-c447-44a7-a13c-4adabfc247e3"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ICodecMapAttributes
{
[PreserveSig] int GetItem(ref Guid key, IntPtr pValue);
[PreserveSig] int GetItemType(ref Guid key, out int pType);
[PreserveSig] int CompareItem(ref Guid key, IntPtr value, out bool pbResult);
[PreserveSig] int Compare(IntPtr theirs, int matchType, out bool pbResult);
[PreserveSig] int GetUINT32(ref Guid key, out uint punValue);
[PreserveSig] int GetUINT64(ref Guid key, out ulong punValue);
[PreserveSig] int GetDouble(ref Guid key, out double pfValue);
[PreserveSig] int GetGUID(ref Guid key, out Guid pguidValue);
[PreserveSig] int GetStringLength(ref Guid key, out uint pcchLength);
[PreserveSig] int GetString(ref Guid key, StringBuilder pwszValue, uint cchBufSize, IntPtr pcchLength);
[PreserveSig] int GetAllocatedString(ref Guid key, out IntPtr ppwszValue, out uint pcchLength);
[PreserveSig] int GetBlobSize(ref Guid key, out uint pcbBlobSize);
[PreserveSig] int GetBlob(ref Guid key, IntPtr pBuf, uint cbBufSize, IntPtr pcbBlobSize);
[PreserveSig] int GetAllocatedBlob(ref Guid key, out IntPtr ppBuf, out uint pcbSize);
[PreserveSig] int GetUnknown(ref Guid key, ref Guid riid, out IntPtr ppv);
[PreserveSig] int SetItem(ref Guid key, IntPtr Value);
}
public static class CodecMapNative
{
[DllImport("mfplat.dll", ExactSpelling = true)]
static extern int MFStartup(uint version, uint flags);
[DllImport("mfplat.dll", ExactSpelling = true)]
static extern int MFShutdown();
[DllImport("mfplat.dll", ExactSpelling = true)]
static extern int MFTEnumEx(Guid guidCategory, uint flags,
IntPtr pInputType, IntPtr pOutputType, out IntPtr pppMFTActivate, out uint pnum);
[DllImport("ole32.dll")]
static extern void CoTaskMemFree(IntPtr p);
[DllImport("dxgi.dll")]
static extern int CreateDXGIFactory1(ref Guid riid, out IntPtr ppFactory);
[DllImport("d3d11.dll")]
static extern int D3D11CreateDevice(IntPtr pAdapter, int DriverType, IntPtr Software,
uint Flags, IntPtr pFeatureLevels, uint FeatureLevels, uint SDKVersion,
out IntPtr ppDevice, out int pFeatureLevel, out IntPtr ppContext);
static Guid K_FRIENDLY = new Guid("314ffbae-5b41-4c95-9c19-4e7d586face3");
static Guid K_CLSID = new Guid("6821c42b-65a4-4e82-99bc-9a88205ecd0c");
static Guid K_VENDOR = new Guid("3aecb0cc-035b-4bcc-8185-2b8d551ef3af");
static Guid K_INTYPES = new Guid("4276c9b1-759d-4bf3-9cd0-0d723d138f96");
static Guid MAJOR_VIDEO = new Guid("73646976-0000-0010-8000-00AA00389B71");
static readonly byte[] FmtTail = new byte[] {0,0,0x10,0,0x80,0,0,0xAA,0,0x38,0x9B,0x71};
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
delegate int EnumAdapters1Del(IntPtr self, uint index, out IntPtr ppAdapter);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
delegate int GetDesc1Del(IntPtr self, IntPtr pDesc);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
delegate uint GetProfileCountDel(IntPtr self);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
delegate int GetProfileDel(IntPtr self, uint index, out Guid pGuid);
static T Slot<T>(IntPtr obj, int index)
{
IntPtr vtbl = Marshal.ReadIntPtr(obj);
IntPtr fn = Marshal.ReadIntPtr(vtbl, index * IntPtr.Size);
return (T)(object)Marshal.GetDelegateForFunctionPointer(fn, typeof(T));
}
static void Rel(IntPtr p) { if (p != IntPtr.Zero) Marshal.Release(p); }
static Guid FourccGuid(string cc)
{
byte[] b = new byte[16];
byte[] a = Encoding.ASCII.GetBytes(cc);
for (int i = 0; i < 4; i++) b[i] = a[i];
for (int i = 0; i < 12; i++) b[i + 4] = FmtTail[i];
return new Guid(b);
}
static string FourccOrGuid(Guid g)
{
byte[] b = g.ToByteArray();
bool isFmt = true;
for (int i = 0; i < 12; i++) { if (b[i + 4] != FmtTail[i]) { isFmt = false; break; } }
if (isFmt)
{
bool printable = true;
for (int i = 0; i < 4; i++) { if (b[i] < 32 || b[i] > 126) { printable = false; break; } }
if (printable) return Encoding.ASCII.GetString(b, 0, 4);
}
return "{" + g.ToString() + "}";
}
static string GetStr(ICodecMapAttributes a, Guid key)
{
IntPtr p; uint len; Guid k = key;
if (a.GetAllocatedString(ref k, out p, out len) != 0) return "";
string s = Marshal.PtrToStringUni(p);
CoTaskMemFree(p);
return s == null ? "" : s;
}
static string GetTypes(ICodecMapAttributes a, Guid key)
{
IntPtr pb; uint cb; Guid k = key;
if (a.GetAllocatedBlob(ref k, out pb, out cb) != 0) return "";
List<string> outp = new List<string>();
int n = (int)(cb / 32);
for (int j = 0; j < n; j++)
{
byte[] sub = new byte[16];
Marshal.Copy(IntPtr.Add(pb, j * 32 + 16), sub, 0, 16);
string s = FourccOrGuid(new Guid(sub));
if (!outp.Contains(s)) outp.Add(s);
}
CoTaskMemFree(pb);
return string.Join(" ", outp.ToArray());
}
// Rows are "mft|name|clsid|vendor|inputtypes". The first row is always
// "hr=0x........|count=N" so a caller can tell an empty result from a
// failed one. filterSide picks which half of the transform the subtype
// filter applies to: "out" for encoders, "in" for decoders.
public static string[] EnumTransforms(string categoryGuid, uint flags, string fourcc, string filterSide)
{
List<string> rows = new List<string>();
IntPtr pInfo = IntPtr.Zero;
try
{
MFStartup(0x00020070, 0);
if (fourcc != null && fourcc.Length == 4)
{
byte[] buf = new byte[32];
MAJOR_VIDEO.ToByteArray().CopyTo(buf, 0);
FourccGuid(fourcc).ToByteArray().CopyTo(buf, 16);
pInfo = Marshal.AllocCoTaskMem(32);
Marshal.Copy(buf, 0, pInfo, 32);
}
IntPtr pIn = (filterSide == "in") ? pInfo : IntPtr.Zero;
IntPtr pOut = (filterSide == "in") ? IntPtr.Zero : pInfo;
IntPtr pp; uint n;
int hr = MFTEnumEx(new Guid(categoryGuid), flags, pIn, pOut, out pp, out n);
rows.Add("hr=0x" + hr.ToString("x8") + "|count=" + n);
if (hr == 0 && n > 0)
{
for (int i = 0; i < n; i++)
{
IntPtr p = Marshal.ReadIntPtr(pp, i * IntPtr.Size);
object o = Marshal.GetObjectForIUnknown(p);
ICodecMapAttributes a = (ICodecMapAttributes)o;
Guid clsid; Guid kc = K_CLSID;
a.GetGUID(ref kc, out clsid);
rows.Add("mft|" + GetStr(a, K_FRIENDLY)
+ "|" + clsid.ToString()
+ "|" + GetStr(a, K_VENDOR)
+ "|" + GetTypes(a, K_INTYPES));
Marshal.ReleaseComObject(o);
Marshal.Release(p);
}
CoTaskMemFree(pp);
}
MFShutdown();
}
catch (Exception ex) { rows.Add("error|" + ex.Message); }
finally { if (pInfo != IntPtr.Zero) Marshal.FreeCoTaskMem(pInfo); }
return rows.ToArray();
}
// Rows are "adapter|index|name|vid|did|vram|videoengine" then one
// "prof|index|guid" per decoder profile on that adapter.
public static string[] EnumAdapters()
{
List<string> rows = new List<string>();
Guid iidFactory1 = new Guid("770aae78-f26f-4dba-a829-253c83d1b387");
Guid iidVideoDevice = new Guid("10EC4D5B-975A-4689-B9E4-D0AAC30FE333");
IntPtr fac = IntPtr.Zero;
try
{
int hr = CreateDXGIFactory1(ref iidFactory1, out fac);
rows.Add("dxgi|0x" + hr.ToString("x8"));
if (hr != 0) return rows.ToArray();
var enumAd = Slot<EnumAdapters1Del>(fac, 12);
for (uint i = 0; ; i++)
{
IntPtr ad;
if (enumAd(fac, i, out ad) != 0) break;
try
{
string name = ""; uint vendor = 0, device = 0; long vram = 0;
IntPtr buf = Marshal.AllocHGlobal(1024);
try
{
if (Slot<GetDesc1Del>(ad, 10)(ad, buf) == 0)
{
name = Marshal.PtrToStringUni(buf, 128);
int z = name.IndexOf('\0');
if (z >= 0) name = name.Substring(0, z);
vendor = (uint)Marshal.ReadInt32(buf, 256);
device = (uint)Marshal.ReadInt32(buf, 260);
vram = Marshal.ReadInt64(buf, 272);
}
}
finally { Marshal.FreeHGlobal(buf); }
IntPtr dev, ctx; int fl;
bool engine = false;
List<string> profs = new List<string>();
if (D3D11CreateDevice(ad, 0, IntPtr.Zero, 0, IntPtr.Zero, 0, 7,
out dev, out fl, out ctx) == 0)
{
IntPtr vd;
if (Marshal.QueryInterface(dev, ref iidVideoDevice, out vd) == 0)
{
engine = true;
uint n = Slot<GetProfileCountDel>(vd, 11)(vd);
var gp = Slot<GetProfileDel>(vd, 12);
for (uint j = 0; j < n; j++)
{
Guid g;
if (gp(vd, j, out g) == 0) profs.Add("prof|" + i + "|" + g.ToString());
}
Rel(vd);
}
Rel(ctx); Rel(dev);
}
rows.Add("adapter|" + i + "|" + name
+ "|0x" + vendor.ToString("x4")
+ "|0x" + device.ToString("x4")
+ "|" + vram
+ "|" + (engine ? "1" : "0"));
rows.AddRange(profs);
}
finally { Rel(ad); }
}
}
catch (Exception ex) { rows.Add("error|" + ex.Message); }
finally { Rel(fac); }
return rows.ToArray();
}
}
'@
}
# ---------------------------------------------------------------------------
# model building
# ---------------------------------------------------------------------------
function Parse-MftRows($rows) {
$result = @{ Ok = $false; Hr = ''; Items = @() }
$list = As-List $rows
if ((Count-Of $list) -eq 0) { return $result }
$first = [string]$list[0]
if ($first.StartsWith('error|')) {
$result.Hr = $first.Substring(6)
return $result
}
$parts = $first.Split('|')
if ((Count-Of $parts) -lt 2 -or -not $parts[0].StartsWith('hr=')) { return $result }
$result.Hr = $parts[0].Substring(3)
$result.Ok = ($result.Hr -eq '0x00000000')
$items = New-Object System.Collections.ArrayList
for ($i = 1; $i -lt (Count-Of $list); $i++) {
$f = ([string]$list[$i]).Split('|')
if ((Count-Of $f) -lt 5 -or $f[0] -ne 'mft') { continue }
# Store-packaged media extensions (the HEVC and VP9 video extensions)
# are activated by package identity and carry no CLSID attribute at
# all, so Media Foundation hands back an all-zero guid. Reporting that
# as if it were a registration would be a lie.
$clsid = $f[2].ToLowerInvariant()
if ($clsid -eq '00000000-0000-0000-0000-000000000000') { $clsid = '' }
[void]$items.Add(@{
Name = To-Ascii $f[1]
Clsid = $clsid
VendorId = $f[3].ToUpperInvariant()
Vendor = Vendor-FromMft $f[3]
Formats = @(($f[4] -split ' ') | Where-Object { $_ -ne '' })
})
}
$result.Items = $items.ToArray()
return $result
}
function Parse-AdapterRows($rows) {
$result = @{ Ok = $false; Hr = ''; Adapters = @() }
$list = As-List $rows
if ((Count-Of $list) -eq 0) { return $result }
$first = [string]$list[0]
if ($first.StartsWith('error|')) { $result.Hr = $first.Substring(6); return $result }
if (-not $first.StartsWith('dxgi|')) { return $result }
$result.Hr = $first.Substring(5)
$result.Ok = ($result.Hr -eq '0x00000000')
$ads = New-Object System.Collections.ArrayList
$byIndex = @{}
for ($i = 1; $i -lt (Count-Of $list); $i++) {
$f = ([string]$list[$i]).Split('|')
if ($f[0] -eq 'adapter' -and (Count-Of $f) -ge 7) {
$a = @{
Index = [int]$f[1]
Name = To-Ascii $f[2]
VendorId = $f[3].ToLowerInvariant()
Vendor = Vendor-FromId $f[3]
DeviceId = $f[4].ToLowerInvariant()
VideoMemory = [long]$f[5]
VideoEngine = ($f[6] -eq '1')
Profiles = @()
}
$byIndex["$($a.Index)"] = $a
[void]$ads.Add($a)
}
elseif ($f[0] -eq 'prof' -and (Count-Of $f) -ge 3) {
$k = $f[1]
if ($byIndex.ContainsKey($k)) {
$byIndex[$k].Profiles = @($byIndex[$k].Profiles) + @($f[2].ToLowerInvariant())
}
}
}
$result.Adapters = $ads.ToArray()
return $result
}
function Get-EncoderSupport($codec, [bool]$hardware) {
# A codec with no MFVideoFormat subtype cannot be queried as an encoder.
if ($null -eq $codec.Fourcc) {
return @{ Queried = $false; Ok = $true; Hr = ''; Items = @() }
}
$flags = $script:MftSortFilt
if ($hardware) { $flags = $flags -bor $script:MftHardware }
else { $flags = $flags -bor $script:MftSync -bor $script:MftAsync }
$rows = [CodecMapNative]::EnumTransforms($script:CatVideoEncoder, [uint32]$flags, $codec.Fourcc, 'out')
$p = Parse-MftRows $rows
$p['Queried'] = $true
return $p
}
# Some codecs are accelerated by a registered hardware decoder transform and
# have no DXVA profile at all. MJPEG is the usual one: both vendors ship a
# hardware M-JPEG decoder MFT, and no D3D11 decoder profile GUID exists for
# it. Counting only profiles would report "no hardware decode" on a machine
# that decodes it in hardware every time a webcam opens.
function Get-DecoderSupport($codec) {
if ($null -eq $codec.Fourcc) {
return @{ Queried = $false; Ok = $true; Hr = ''; Items = @() }
}
$flags = $script:MftSortFilt -bor $script:MftHardware
$rows = [CodecMapNative]::EnumTransforms($script:CatVideoDecoder, [uint32]$flags, $codec.Fourcc, 'in')
$p = Parse-MftRows $rows
$p['Queried'] = $true
return $p
}
# Two registrations of the same CLSID are the same physical engine surfaced
# twice, which is normal on hybrid-graphics laptops. Collapse for counting,
# keep the duplicate count so -Detail can show it.
function Group-ByClsid($items) {
$order = New-Object System.Collections.ArrayList
$seen = @{}
foreach ($it in (As-List $items)) {
# Packaged extensions have no CLSID at all, so an empty key would
# collapse two different extensions into one. Fall back to the name.
$k = $it.Clsid
if ($k -eq '') { $k = 'name:' + $it.Name }
if ($seen.ContainsKey($k)) {
$seen[$k].Registrations = $seen[$k].Registrations + 1
continue
}
$copy = @{
Name = $it.Name; Clsid = $it.Clsid; VendorId = $it.VendorId
Vendor = $it.Vendor; Formats = @($it.Formats); Registrations = 1
}
$seen[$k] = $copy
[void]$order.Add($copy)
}
return ,$order.ToArray()
}
function Build-Model {
Initialize-Native
$model = @{
Schema = $script:SchemaVersion
Tool = 'codecmap'
ToolVersion = $script:ToolVersion
Machine = $env:COMPUTERNAME
Os = [string][Environment]::OSVersion.Version
Captured = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')
Adapters = @()
Codecs = @()
Errors = @()
}
$ad = Parse-AdapterRows ([CodecMapNative]::EnumAdapters())
if (-not $ad.Ok) { $model.Errors = @($model.Errors) + @("direct3d query failed ($($ad.Hr))") }
$model.Adapters = $ad.Adapters
# Which adapter can decode which profile, indexed by profile guid.
$profOwners = @{}
foreach ($a in (As-List $model.Adapters)) {
foreach ($g in (As-List $a.Profiles)) {
if (-not $profOwners.ContainsKey($g)) { $profOwners[$g] = @() }
$profOwners[$g] = @($profOwners[$g]) + @($a.Index)
}
}
$model['ProfileOwners'] = $profOwners
$mfBroken = $false
$codecs = New-Object System.Collections.ArrayList
foreach ($c in $script:Codecs) {
$hw = Get-EncoderSupport $c $true
$sw = Get-EncoderSupport $c $false
if ($hw.Queried -and -not $hw.Ok) { $mfBroken = $true }
$hwItems = Group-ByClsid $hw.Items
# The software query returns hardware transforms too; keep only the
# ones the hardware query did not already claim.
$hwClsids = @{}
foreach ($i in (As-List $hwItems)) { $hwClsids[$i.Clsid] = $true }
$swItems = @()
foreach ($i in (As-List (Group-ByClsid $sw.Items))) {
if (-not $hwClsids.ContainsKey($i.Clsid)) { $swItems = @($swItems) + @($i) }
}
$decode = New-Object System.Collections.ArrayList
foreach ($g in $c.DecodeProfiles.Keys) {
if ($profOwners.ContainsKey($g)) {
[void]$decode.Add(@{
Guid = $g
Profile = $c.DecodeProfiles[$g]
Owners = @($profOwners[$g])
})
}
}
[void]$codecs.Add(@{
Key = $c.Key
Label = $c.Label
Fourcc = $c.Fourcc
EncodeQueried= $hw.Queried
HwEncoders = $hwItems
SwEncoders = $swItems
HwDecoders = Group-ByClsid (Get-DecoderSupport $c).Items
DecodeProfiles = $decode.ToArray()
})
}
$model.Codecs = $codecs.ToArray()
if ($mfBroken) { $model.Errors = @($model.Errors) + @('media foundation encoder query failed') }
return $model
}
# ---------------------------------------------------------------------------
# rendering
# ---------------------------------------------------------------------------
function Encoder-VendorList($codec) {
$names = New-Object System.Collections.ArrayList
foreach ($e in (As-List (Hash-Get $codec 'HwEncoders' @()))) {
$v = Hash-Get $e 'Vendor' ''
if ($v -ne '' -and -not $names.Contains($v)) { [void]$names.Add($v) }
}
return ,$names.ToArray()
}
function Decoder-VendorList($codec, $model) {
$names = New-Object System.Collections.ArrayList
$ads = As-List (Hash-Get $model 'Adapters' @())
foreach ($d in (As-List (Hash-Get $codec 'DecodeProfiles' @()))) {
foreach ($ix in (As-List (Hash-Get $d 'Owners' @()))) {
foreach ($a in $ads) {
if ([int](Hash-Get $a 'Index' -1) -eq [int]$ix) {
$v = Hash-Get $a 'Vendor' ''
if ($v -ne '' -and -not $names.Contains($v)) { [void]$names.Add($v) }
}
}
}
}
foreach ($e in (As-List (Hash-Get $codec 'HwDecoders' @()))) {
$v = Hash-Get $e 'Vendor' ''
if ($v -ne '' -and -not $names.Contains($v)) { [void]$names.Add($v) }
}
return ,$names.ToArray()
}
# How the decode answer was reached, so the summary can say which subsystem
# actually backs it rather than implying both always agree.
function Decode-Route($codec) {
$prof = Count-Of (As-List (Hash-Get $codec 'DecodeProfiles' @()))
$mft = Count-Of (As-List (Hash-Get $codec 'HwDecoders' @()))
if ($prof -gt 0 -and $mft -gt 0) { return 'both' }
if ($prof -gt 0) { return 'dxva' }
if ($mft -gt 0) { return 'transform' }
return 'none'
}
# A packaged media extension has no CLSID registration, so say so instead of
# printing an empty column or a fake all-zero guid.
# Notes are full sentences and the longest run past 150 characters, which a
# console then wraps at whatever width it happens to be, breaking mid-word and
# losing the bullet indent. Wrap them here instead, at a fixed width, so the
# report looks the same redirected to a file as it does on screen.
function Wrap-Text([string]$text, [int]$width, [string]$first, [string]$cont) {
$lines = New-Object System.Collections.ArrayList
$cur = $first
$empty = $true
foreach ($w in $text.Split(' ')) {
if ($w -eq '') { continue }
if ($empty) { $cur = $cur + $w; $empty = $false; continue }
if (($cur.Length + 1 + $w.Length) -gt $width) {
[void]$lines.Add($cur)
$cur = $cont + $w
} else {
$cur = $cur + ' ' + $w
}
}
if (-not $empty) { [void]$lines.Add($cur) }
return ,$lines.ToArray()
}
function Clsid-Text($mft) {
$c = [string](Hash-Get $mft 'Clsid' '')
if ($c -eq '') { return 'none (packaged media extension)' }
return $c
}
function Profile-NameList($codec) {
$names = New-Object System.Collections.ArrayList
foreach ($d in (As-List (Hash-Get $codec 'DecodeProfiles' @()))) {
$p = Hash-Get $d 'Profile' ''
if ($p -ne '' -and -not $names.Contains($p)) { [void]$names.Add($p) }
}
return ,$names.ToArray()
}
function Ten-BitCapable($codec) {
foreach ($e in (As-List (Hash-Get $codec 'HwEncoders' @()))) {
foreach ($f in (As-List (Hash-Get $e 'Formats' @()))) {
if ($f -eq 'P010' -or $f -eq 'P016' -or $f -eq 'Y410' -or $f -eq 'Y416') { return $true }
}
}
return $false
}
function Render-Adapters($model) {
$ads = As-List (Hash-Get $model 'Adapters' @())
Out-Line 'GRAPHICS ADAPTERS'
if ((Count-Of $ads) -eq 0) {
Out-Line ' none reported by DXGI'
return
}
foreach ($a in $ads) {
$mem = Format-Mb ([long](Hash-Get $a 'VideoMemory' 0))
$eng = 'video engine'
if (-not [bool](Hash-Get $a 'VideoEngine' $false)) { $eng = 'NO video engine' }
Out-Line (' [{0}] {1}' -f (Hash-Get $a 'Index' 0), (Hash-Get $a 'Name' '?'))
Out-Line (' {0} {1} {2} pci {3}/{4}' -f `
(Hash-Get $a 'Vendor' '?'), $mem, $eng,
(Hash-Get $a 'VendorId' '?'), (Hash-Get $a 'DeviceId' '?'))
}
}
function Render-Summary($model, $only) {
$ads = As-List (Hash-Get $model 'Adapters' @())
$engines = 0
foreach ($a in $ads) { if ([bool](Hash-Get $a 'VideoEngine' $false)) { $engines++ } }
Out-Line ('codecmap {0} - {1}' -f $script:ToolVersion, (Hash-Get $model 'Machine' '?'))
Out-Line ('{0} adapter(s), {1} with a video engine' -f (Count-Of $ads), $engines)
Out-Line ''
Render-Adapters $model
Out-Line ''
$codecs = As-List (Hash-Get $model 'Codecs' @())
$showEnc = -not $Decoders
$showDec = -not $Encoders
if ($showEnc) {
Out-Line 'HARDWARE ENCODE (what a capture app can pick)'
$any = $false
foreach ($c in $codecs) {
if ($null -ne $only -and (Hash-Get $c 'Key' '') -ne $only.Key) { continue }
if (-not [bool](Hash-Get $c 'EncodeQueried' $false)) { continue }
$v = Encoder-VendorList $c
$label = (Hash-Get $c 'Label' '?').PadRight(10)
if ((Count-Of $v) -gt 0) {
$any = $true
$extra = ''
if (Ten-BitCapable $c) { $extra = ' 10-bit ready' }
Out-Line (' {0} yes {1}{2}' -f $label, ($v -join ', '), $extra)
}
else {
Out-Line (' {0} no' -f $label)
}
}
if (-not $any) { Out-Line ' this PC has no hardware video encoder at all' }
Out-Line ''
}
if ($showDec) {
Out-Line 'HARDWARE DECODE (Direct3D 11 accelerated playback)'
foreach ($c in $codecs) {
if ($null -ne $only -and (Hash-Get $c 'Key' '') -ne $only.Key) { continue }
$v = Decoder-VendorList $c $model
$label = (Hash-Get $c 'Label' '?').PadRight(10)
if ((Count-Of $v) -gt 0) {
$profs = Profile-NameList $c
$ptxt = ''
if ((Count-Of $profs) -gt 0) { $ptxt = ' ' + ($profs -join ', ') }
elseif ((Decode-Route $c) -eq 'transform') { $ptxt = ' via decoder transform, no DXVA profile' }
Out-Line (' {0} yes {1}{2}' -f $label, ($v -join ', '), $ptxt)
}
else {
Out-Line (' {0} no' -f $label)
}
}
Out-Line ''
}
Render-Notes $model $only
}
function Render-Notes($model, $only) {
$notes = New-Object System.Collections.ArrayList
$codecs = As-List (Hash-Get $model 'Codecs' @())
$dupNames = New-Object System.Collections.ArrayList
$dupMax = 0
$playOnly = New-Object System.Collections.ArrayList
$recOnly = New-Object System.Collections.ArrayList
foreach ($c in $codecs) {
if ($null -ne $only -and (Hash-Get $c 'Key' '') -ne $only.Key) { continue }
$enc = Count-Of (Encoder-VendorList $c)
$dec = Count-Of (Decoder-VendorList $c $model)
$lab = Hash-Get $c 'Label' '?'
if ($enc -eq 0 -and $dec -gt 0) { [void]$playOnly.Add($lab) }
if ($enc -gt 0 -and $dec -eq 0) { [void]$recOnly.Add($lab) }
foreach ($e in (As-List (Hash-Get $c 'HwEncoders' @()))) {
$reg = [int](Hash-Get $e 'Registrations' 1)
if ($reg -gt 1) {
$n = Hash-Get $e 'Name' '?'
if (-not $dupNames.Contains($n)) { [void]$dupNames.Add($n) }
if ($reg -gt $dupMax) { $dupMax = $reg }
}
}
}
# One line per category. Emitting the same sentence once per codec buried
# the notes that actually differ.
if ((Count-Of $playOnly) -gt 0) {
[void]$notes.Add(('Play-only: {0}. These decode in hardware but this PC has no hardware encoder for them, so recording them uses the CPU.' -f ($playOnly -join ', ')))
}
if ((Count-Of $recOnly) -gt 0) {
[void]$notes.Add(('Record-only: {0}. These encode in hardware but this PC has no hardware decoder for them, so scrubbing your own recordings uses the CPU.' -f ($recOnly -join ', ')))
}
if ((Count-Of $dupNames) -gt 0) {
[void]$notes.Add(("{0} encoder transform(s) are registered up to {1} times: {2}. That is one physical engine listed once per adapter, not several encoders." -f `
(Count-Of $dupNames), $dupMax, (($dupNames | ForEach-Object { "'" + $_ + "'" }) -join ', ')))