forked from pinterf/mvtools
/
MVAnalyse.cpp
1037 lines (892 loc) · 30 KB
/
MVAnalyse.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// MVTools
// 2004 Manao
// Copyright(c)2006-2009 A.G.Balakhnin aka Fizick - true motion, overlap, YUY2, pelclip, divide, super
// General classe for motion based filters
// See legal notice in Copying.txt for more information
// 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., 675 Mass Ave, Cambridge, MA 02139, USA, or visit
// http://www.gnu.org/copyleft/gpl.html .
#include "def.h"
#include "ClipFnc.h"
#include "commonfunctions.h"
#include "cpu.h"
#include "DCTFFTW.h"
#include "DCTINT.h"
#include "MVAnalyse.h"
#include "MVGroupOfFrames.h"
#include "MVSuper.h"
#include "profile.h"
#include "SuperParams64Bits.h"
#ifdef _WIN32
using namespace Microsoft::WRL;
#endif
#include <cmath>
#include <cstdio>
#include <algorithm>
MVAnalyse::MVAnalyse(
PClip _child, int _blksizex, int _blksizey, int lv, int st, int stp,
int _pelSearch, bool isb, int lambda, bool chroma, int df, sad_t _lsad,
int _plevel, bool _global, int _pnew, int _pzero, int _pglobal,
int _overlapx, int _overlapy, const char* _outfilename, int _dctmode,
int _divide, int _sadx264, sad_t _badSAD, int _badrange, bool _isse,
bool _meander, bool temporal_flag, bool _tryMany, bool multi_flag,
bool mt_flag, int _chromaSADScale, int _optSearchOption, int _optPredictorType, IScriptEnvironment* env
)
: ::GenericVideoFilter(_child)
, _srd_arr(1)
, _vectorfields_aptr()
, _multi_flag(multi_flag)
, _temporal_flag(temporal_flag)
, _mt_flag(mt_flag)
, _dct_factory_ptr()
, _dct_pool()
, _delta_max(0)
, optSearchOption(_optSearchOption)
, optPredictorType(_optPredictorType)
{
has_at_least_v8 = true;
try { env->CheckVersion(8); }
catch (const AvisynthError&) { has_at_least_v8 = false; }
static int id = 0; _instance_id = id++;
_RPT1(0, "MvAnalyse.Create id=%d\n", _instance_id);
if (multi_flag && df < 1)
{
env->ThrowError(
"MAnalyse: cannot use a fixed frame reference "
"(delta < 1) in multi mode."
);
}
_RPT1(0, "MAnalyze created, isb=%d\n", isb ? 1 : 0);
pixelsize = vi.ComponentSize();
bits_per_pixel = vi.BitsPerComponent();
MVAnalysisData & analysisData = _srd_arr[0]._analysis_data;
MVAnalysisData & analysisDataDivided = _srd_arr[0]._analysis_data_divided;
if (pixelsize == 4)
{
env->ThrowError("MAnalyse: Clip with float pixel type is not supported");
}
if (!vi.IsYUV() && !vi.IsYUY2()) // YUY2 is also YUV but let's see what is supported
{
env->ThrowError("MAnalyse: Clip must be YUV or YUY2");
}
if (_optPredictorType < 0 || _optPredictorType > 4)
{
env->ThrowError("MAnalyse: parameter 'optPredictorType' must be from 0 to 4");
}
#ifdef _WIN32
// large pages priv:
DWORD error;
HANDLE hToken = NULL;
TOKEN_PRIVILEGES tp;
BOOL result;
// Enable Lock pages in memory priveledge for the current process
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, &hToken))
{
tp.PrivilegeCount = 1;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (LookupPrivilegeValue(NULL, SE_LOCK_MEMORY_NAME, &tp.Privileges[0].Luid))
{
result = AdjustTokenPrivileges(hToken, FALSE, &tp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
error = GetLastError();
if (!result || (error != ERROR_SUCCESS))
{
// env->ThrowError("LargePages: AdjustTokenPrivileges failed.");
}
}
else
{
// env->ThrowError("LargePages: LookupPrivilegeValue failed.");
}
}
else
{
// env->ThrowError("LargePages: Can not open process token"); // do not bug user with stop processing errors ???
}
// Cleanup
if (hToken != 0) CloseHandle(hToken);
hToken = NULL;
#endif
if (vi.IsY())
chroma = false; // silent fallback
// get parameters of super clip - v2.0
SuperParams64Bits params;
memcpy(¶ms, &child->GetVideoInfo().num_audio_samples, 8);
const int nHeight = params.nHeight;
const int nSuperHPad = params.nHPad;
const int nSuperVPad = params.nVPad;
const int nSuperPel = params.nPel;
const int nSuperModeYUV = params.nModeYUV;
const int nSuperLevels = params.nLevels;
if (nHeight <= 0
|| nSuperHPad < 0
|| nSuperHPad >= vi.width / 2 // PF: intentional /2
|| nSuperVPad < 0
|| nSuperPel < 1
|| nSuperPel > 4
|| nSuperModeYUV < 0
|| nSuperModeYUV > YUVPLANES
|| nSuperLevels < 1)
{
env->ThrowError("MAnalyse: wrong super clip (pseudoaudio) parameters");
}
analysisData.nWidth = vi.width - nSuperHPad * 2;
analysisData.nHeight = nHeight;
analysisData.pixelType = vi.pixel_type;
if (!vi.IsY()) {
analysisData.yRatioUV = vi.IsYUY2() ? 1 : (1 << vi.GetPlaneHeightSubsampling(PLANAR_U));
analysisData.xRatioUV = vi.IsYUY2() ? 2 : (1 << vi.GetPlaneWidthSubsampling(PLANAR_U));
}
else {
analysisData.yRatioUV = 1; // n/a
analysisData.xRatioUV = 1; // n/a
}
analysisData.pixelsize = pixelsize;
analysisData.bits_per_pixel = bits_per_pixel;
#ifdef _WIN32
if (optSearchOption == 5) // DX12_ME
{
int iBlkSize;
if ((_blksizex == 8) && (_blksizey == 8))
iBlkSize = 8;
else
if ((_blksizex == 16) && (_blksizey == 16))
iBlkSize = 16;
else
{
env->ThrowError("MAnalyse: Unsupported block size for DX12_ME, only 8x8 and 16x16 allowed");
}
Init_DX12_ME(env, analysisData.nWidth, analysisData.nHeight, iBlkSize);
}
#endif
if (_chromaSADScale < -2 || _chromaSADScale>2)
env->ThrowError(
"MAnalyze: scaleCSAD must be -2..2"
);
analysisData.chromaSADScale = _chromaSADScale;
pSrcGOF = new MVGroupOfFrames(
nSuperLevels, analysisData.nWidth, analysisData.nHeight,
nSuperPel, nSuperHPad, nSuperVPad, nSuperModeYUV,
_isse, analysisData.xRatioUV, analysisData.yRatioUV, pixelsize, bits_per_pixel, mt_flag
);
pRefGOF = new MVGroupOfFrames(
nSuperLevels, analysisData.nWidth, analysisData.nHeight,
nSuperPel, nSuperHPad, nSuperVPad, nSuperModeYUV,
_isse, analysisData.xRatioUV, analysisData.yRatioUV, pixelsize, bits_per_pixel, mt_flag
);
analysisData.nBlkSizeX = _blksizex;
analysisData.nBlkSizeY = _blksizey;
// same blocksize check in MAnalyze and MRecalculate
// some blocksizes may not work in 4:2:0 (chroma subsampling division), but o.k. in 4:4:4
const std::vector< std::pair< int, int > > allowed_blksizes =
{
{ 64, 64 },{ 64,48 },{ 64,32 },{ 64,16 },
{ 48,64 },{ 48,48 },{ 48,24 },{ 48,12 },
{ 32,64 },{ 32,32 },{ 32,24 },{ 32,16 },{ 32,8 },
{ 24,48 },{ 24,32 },{ 24,24 },{ 24,12 },{ 24,6 },
{ 16,64 },{ 16,32 },{ 16,16 },{ 16,12 },{ 16,8 },{ 16,4 },{ 16,2 },
{ 12,48 },{ 12,24 },{ 12,16 },{ 12,12 },{ 12,6 },{ 12,3 },
{ 8,32 },{ 8,16 },{ 8,8 },{ 8,4 },{ 8,2 },{ 8,1 },
{ 6,24 },{ 6,12 },{ 6,6 },{ 6,3 },
{ 4,8 },{ 4,4 },{ 4,2 },
{ 3,6 },{ 3,3 },
{ 2,4 },{ 2,2 }
};
bool found = false;
for (int i = 0; i < (int)allowed_blksizes.size(); i++) {
if (analysisData.nBlkSizeX == allowed_blksizes[i].first && analysisData.nBlkSizeY == allowed_blksizes[i].second) {
found = true;
break;
}
}
if (!found) {
env->ThrowError(
"MAnalyse: Invalid block size: %d x %d", analysisData.nBlkSizeX, analysisData.nBlkSizeY);
}
analysisData.nPel = nSuperPel;
if (analysisData.nPel != 1
&& analysisData.nPel != 2
&& analysisData.nPel != 4)
{
env->ThrowError("MAnalyse: pel has to be 1 or 2 or 4");
}
analysisData.nDeltaFrame = df;
// if (analysisData.nDeltaFrame < 1)
// {
// analysisData.nDeltaFrame = 1;
// }
if (_overlapx < 0 || _overlapx > _blksizex/2
|| _overlapy < 0 || _overlapy > _blksizey/2)
{
env->ThrowError("MAnalyse: overlap must be less or equal than half block size");
}
if (_overlapx % analysisData.xRatioUV || _overlapy % analysisData.yRatioUV)
{
env->ThrowError("MAnalyse: wrong overlap for the colorspace subsampling");
}
if (_divide != 0 && (_blksizex < 8 || _blksizey < 8)) // || instead of && 2.5.11.22 green garbage issue
{
env->ThrowError(
"MAnalyse: Block sizes must be 8 or more for divide mode"
);
}
if (_divide != 0
&& ((_overlapx % (2 * analysisData.xRatioUV)) || (_overlapy % (2 * analysisData.yRatioUV))) // PF subsampling-aware
)
{
env->ThrowError("MAnalyse: wrong overlap for the colorspace subsampling for divide mode");
}
divideExtra = _divide;
// include itself, but usually equal to 256 :-)
headerSize = std::max(int(4 + sizeof(analysisData)), 256);
analysisData.nOverlapX = _overlapx;
analysisData.nOverlapY = _overlapy;
int nBlkX = (analysisData.nWidth - analysisData.nOverlapX)
/ (analysisData.nBlkSizeX - analysisData.nOverlapX);
int nBlkY = (analysisData.nHeight - analysisData.nOverlapY)
/ (analysisData.nBlkSizeY - analysisData.nOverlapY);
// 2.7.36: fallback to no overlap when either nBlk count is less that 2
if (nBlkX < 2 || nBlkY < 2) {
analysisData.nOverlapX = 0;
analysisData.nOverlapY = 0;
nBlkX = analysisData.nWidth / analysisData.nBlkSizeX;
nBlkY = analysisData.nHeight / analysisData.nBlkSizeY;
}
analysisData.nBlkX = nBlkX;
analysisData.nBlkY = nBlkY;
const int nWidth_B =
(analysisData.nBlkSizeX - analysisData.nOverlapX) * nBlkX
+ analysisData.nOverlapX; // covered by blocks
const int nHeight_B =
(analysisData.nBlkSizeY - analysisData.nOverlapY) * nBlkY
+ analysisData.nOverlapY;
// calculate valid levels
int nLevelsMax = 0;
// at last one block
while (((nWidth_B >> nLevelsMax) - analysisData.nOverlapX)
/ (analysisData.nBlkSizeX - analysisData.nOverlapX) > 0
&& ((nHeight_B >> nLevelsMax) - analysisData.nOverlapY)
/ (analysisData.nBlkSizeY - analysisData.nOverlapY) > 0)
{
++nLevelsMax;
}
analysisData.nLvCount = (lv > 0) ? lv : nLevelsMax + lv;
if (analysisData.nLvCount > nSuperLevels)
{
env->ThrowError(
"MAnalyse: it is not enough levels in super clip (%d), "
"while MAnalyse asks %d", nSuperLevels, analysisData.nLvCount
);
}
if (analysisData.nLvCount < 1
|| analysisData.nLvCount > nLevelsMax)
{
env->ThrowError(
"MAnalyse: non-valid number of levels (%d)", analysisData.nLvCount
);
}
analysisData.isBackward = isb;
nLambda = lambda;
// lambda is finally scaled in PlaneOfBlocks::WorkingArea::MotionDistorsion(int vx, int vy) const
// as return (nLambda * dist) >> (16 - bits_per_pixel)
// To have it 8x8 normalized, we would use
// nLambda = lambda * ((_blksizex * _blksizey) / (8 * 8)) << (bits_per_pixel-8); // normalize to 8x8 block size
// and use
// (nLambda * dist) >> 8 in PlaneOfBlocks::WorkingArea::MotionDistorsion
// and change default lambda generation in truemotion=true preset
// But doing this would kill compatibility, there are scripts which are using lambda properly scaled by the block size.
lsad = _lsad * (_blksizex * _blksizey) / 64 * (1 << (bits_per_pixel - 8));
pnew = _pnew;
plevel = _plevel;
global = _global;
pglobal = _pglobal;
pzero = _pzero;
badSAD = _badSAD * (_blksizex * _blksizey) / 64 * (1 << (bits_per_pixel - 8));
badrange = _badrange;
meander = _meander;
tryMany = _tryMany;
if (_dctmode != 0)
{
_dct_factory_ptr = std::unique_ptr <DCTFactory>(
new DCTFactory(_dctmode, _isse, _blksizex, _blksizey, pixelsize, bits_per_pixel, *env)
);
_dct_pool.set_factory(*_dct_factory_ptr);
}
switch (st)
{
case 0:
searchType = ONETIME;
nSearchParam = (stp < 1) ? 1 : stp;
break;
case 1:
searchType = NSTEP;
nSearchParam = (stp < 0) ? 0 : stp;
break;
case 3:
searchType = EXHAUSTIVE;
nSearchParam = (stp < 1) ? 1 : stp;
break;
case 4:
searchType = HEX2SEARCH;
nSearchParam = (stp < 1) ? 1 : stp;
break;
case 5:
searchType = UMHSEARCH;
nSearchParam = (stp < 1) ? 1 : stp; // really min is 4
break;
case 6:
searchType = HSEARCH;
nSearchParam = (stp < 1) ? 1 : stp;
break;
case 7:
searchType = VSEARCH;
nSearchParam = (stp < 1) ? 1 : stp;
break;
case 2:
default:
searchType = LOGARITHMIC;
nSearchParam = (stp < 1) ? 1 : stp;
}
// not below value of 0 at finest level
nPelSearch = (_pelSearch <= 0) ? analysisData.nPel : _pelSearch;
analysisData.nFlags = 0;
analysisData.nFlags |= (_isse) ? MOTION_USE_ISSE : 0;
analysisData.nFlags |= (analysisData.isBackward) ? MOTION_IS_BACKWARD : 0;
analysisData.nFlags |= (chroma) ? MOTION_USE_CHROMA_MOTION : 0;
analysisData.nFlags |= conv_cpuf_flags_to_cpu(env->GetCPUFlags());
// cpu flags has different layout that Avisynth's CPUF_xxx layout.
// Never mix CPU_xxxx and CPUF_xxxx constants!
nModeYUV = (chroma) ? YUVPLANES : YPLANE;
if ((nModeYUV & nSuperModeYUV) != nModeYUV)
{
env->ThrowError(
"MAnalyse: super clip does not contain needed color data"
);
}
_vectorfields_aptr = std::unique_ptr <GroupOfPlanes>(new GroupOfPlanes(
analysisData.nBlkSizeX,
analysisData.nBlkSizeY,
analysisData.nLvCount,
analysisData.nPel,
analysisData.nFlags,
analysisData.nOverlapX,
analysisData.nOverlapY,
analysisData.nBlkX,
analysisData.nBlkY,
analysisData.xRatioUV, // PF
analysisData.yRatioUV,
divideExtra,
analysisData.pixelsize, // PF
analysisData.bits_per_pixel,
(_dct_factory_ptr.get() != 0) ? &_dct_pool : 0,
_mt_flag,
analysisData.chromaSADScale,
optSearchOption,
env
));
analysisData.nMagicKey = MVAnalysisData::MOTION_MAGIC_KEY;
analysisData.nHPadding = nSuperHPad; // v2.0
analysisData.nVPadding = nSuperVPad;
// MVAnalysisData and outfile format version: last update v1.8.1
analysisData.nVersion = MVAnalysisData::VERSION;
// DebugPrintf(" MVAnalyseData size= %d",sizeof(analysisData));
outfilename = _outfilename;
if (lstrlen(outfilename) > 0)
{
outfile = fopen(outfilename, "wb");
if (outfile == NULL)
{
env->ThrowError("MAnalyse: out file can not be created!");
}
else
{
fwrite(&analysisData, sizeof(analysisData), 1, outfile);
// short vx, short vy, int SAD = 4 words = 8 bytes per block
outfilebuf = new short[nBlkX * nBlkY * 4];
}
}
else
{
outfile = NULL;
outfilebuf = NULL;
}
// Defines the format of the output vector clip
// count of 32 bit integers: 2_size_validity+(foreachblock(1_validity+blockCount*3))
const int width_bytes = headerSize + _vectorfields_aptr->GetArraySize() * 4;
ClipFnc::format_vector_clip(
vi, true, nBlkX, "rgb32", width_bytes, "MAnalyse", env
);
if (divideExtra) //v1.8.1
{
memcpy(&analysisDataDivided, &analysisData, sizeof(analysisData));
analysisDataDivided.nBlkX = analysisData.nBlkX * 2;
analysisDataDivided.nBlkY = analysisData.nBlkY * 2;
analysisDataDivided.nBlkSizeX = analysisData.nBlkSizeX / 2;
analysisDataDivided.nBlkSizeY = analysisData.nBlkSizeY / 2;
analysisDataDivided.nOverlapX = analysisData.nOverlapX / 2;
analysisDataDivided.nOverlapY = analysisData.nOverlapY / 2;
analysisDataDivided.nLvCount = analysisData.nLvCount + 1;
}
if (_temporal_flag)
{
_srd_arr[0]._vec_prev.resize(_vectorfields_aptr->GetArraySize()); // array for prev vectors
}
_srd_arr[0]._vec_prev_frame = -2;
// From this point, analysisData and analysisDataDivided references will
// become invalid, because of the _srd_arr.resize(). Don't use them any more.
if (_multi_flag)
{
_delta_max = df;
_srd_arr.resize(_delta_max * 2);
for (int delta_index = 0; delta_index < _delta_max; ++delta_index)
{
for (int dir_index = 0; dir_index < 2; ++dir_index)
{
const int index = delta_index * 2 + dir_index;
SrcRefData & srd = _srd_arr[index];
srd = _srd_arr[0];
srd._analysis_data.nDeltaFrame = delta_index + 1;
srd._analysis_data.isBackward = (dir_index == 0);
if (srd._analysis_data.isBackward)
{
srd._analysis_data.nFlags |= MOTION_IS_BACKWARD;
}
else
{
srd._analysis_data.nFlags &= ~MOTION_IS_BACKWARD;
}
srd._analysis_data_divided.nDeltaFrame = srd._analysis_data.nDeltaFrame;
srd._analysis_data_divided.isBackward = srd._analysis_data.isBackward;
srd._analysis_data_divided.nFlags = srd._analysis_data.nFlags;
}
}
vi.num_frames *= _delta_max * 2;
vi.MulDivFPS(_delta_max * 2, 1);
}
// we'll transmit to the processing filters a handle
// on the analyzing filter itself ( it's own pointer ), in order
// to activate the right parameters.
if (divideExtra) //v1.8.1
{
#if !defined(MV_64BIT)
vi.nchannels = reinterpret_cast <uintptr_t> (&_srd_arr[0]._analysis_data_divided);
#else
uintptr_t p = reinterpret_cast <uintptr_t> (&_srd_arr[0]._analysis_data_divided);
vi.nchannels = 0x80000000L | (int)(p >> 32);
vi.sample_type = (int)(p & 0xffffffffUL);
#endif
}
else
{
#if !defined(MV_64BIT)
vi.nchannels = reinterpret_cast <uintptr_t> (&_srd_arr[0]._analysis_data);
#else
uintptr_t p = reinterpret_cast <uintptr_t> (&_srd_arr[0]._analysis_data);
vi.nchannels = 0x80000000L | (int)(p >> 32);
vi.sample_type = (int)(p & 0xffffffffUL);
#endif
}
}
MVAnalyse::~MVAnalyse()
{
if (outfile != NULL)
{
fclose(outfile);
outfile = 0;
delete[] outfilebuf;
outfilebuf = 0;
}
delete pSrcGOF;
pSrcGOF = 0;
delete pRefGOF;
pRefGOF = 0;
_RPT1(0, "MAnalyze destroyed %d\n",_instance_id);
}
PVideoFrame __stdcall MVAnalyse::GetFrame(int n, IScriptEnvironment* env)
{
_RPT2(0, "MAnalyze GetFrame, frame=%d id=%d\n", n, _instance_id);
const int ndiv = (_multi_flag) ? _delta_max * 2 : 1;
const int nsrc = n / ndiv;
const int srd_index = n % ndiv;
SrcRefData & srd = _srd_arr[srd_index];
const int nbr_src_frames = child->GetVideoInfo().num_frames;
int minframe;
int maxframe;
int nref;
if (srd._analysis_data.nDeltaFrame > 0)
{
const int offset =
(srd._analysis_data.isBackward)
? srd._analysis_data.nDeltaFrame
: -srd._analysis_data.nDeltaFrame;
minframe = std::max(-offset, 0);
maxframe = nbr_src_frames + std::min(-offset, 0);
nref = nsrc + offset;
}
else // special static mode
{
nref = -srd._analysis_data.nDeltaFrame; // positive fixed frame number
minframe = 0;
maxframe = nbr_src_frames;
}
PVideoFrame dst = env->NewVideoFrame(vi); // frameprop inheritance later (if there is source)
unsigned char * pDst = dst->GetWritePtr();
// 0 headersize (max(4+sizeof(analysisData),256)
// 4: analysysData
// 256: data
// 256: 2_size_validity+(foreachblock(1_validity+blockCount*3))
// write analysis parameters as a header to frame
memcpy(pDst, &headerSize, sizeof(int));
if (divideExtra)
{
memcpy(
pDst + sizeof(int),
&srd._analysis_data_divided,
sizeof(srd._analysis_data_divided)
);
}
else
{
memcpy(
pDst + sizeof(int),
&srd._analysis_data,
sizeof(srd._analysis_data)
);
}
pDst += headerSize;
if (nsrc < minframe || nsrc >= maxframe)
{
// fill all vectors with invalid data
_vectorfields_aptr->WriteDefaultToArray(reinterpret_cast <int *> (pDst));
}
else
{
// DebugPrintf ("MVAnalyse: Get src frame %d",nsrc);
_RPT3(0, "MAnalyze GetFrame, frame_nsrc=%d nref=%d id=%d\n", nsrc, nref, _instance_id);
PVideoFrame src = child->GetFrame(nsrc, env); // v2.0
// if(has_at_least_v8) env->copyFrameProps(src, dst); // frame property support
// The result clip is a special MV clip. It does not need to inherit the frame props of source
load_src_frame(*pSrcGOF, src, srd._analysis_data);
// DebugPrintf ("MVAnalyse: Get ref frame %d", nref);
// DebugPrintf ("MVAnalyse frame %i backward=%i", nsrc, srd._analysis_data.isBackward);
::PVideoFrame ref = child->GetFrame(nref, env); // v2.0
load_src_frame(*pRefGOF, ref, srd._analysis_data);
const int fieldShift = ClipFnc::compute_fieldshift(
child,
vi.IsFieldBased(),
srd._analysis_data.nPel,
nsrc,
nref
);
if (outfile != NULL)
{
fwrite(&n, sizeof(int), 1, outfile); // write frame number
}
// temporal predictor dst if prev frame was really prev
int * pVecPrevOrNull = 0;
if (_temporal_flag && srd._vec_prev_frame == nsrc - 1)
{
pVecPrevOrNull = &srd._vec_prev[0];
}
_vectorfields_aptr->SearchMVs(
pSrcGOF, pRefGOF,
searchType, nSearchParam, nPelSearch, nLambda, lsad, pnew, plevel,
global, srd._analysis_data.nFlags, reinterpret_cast<int*>(pDst),
outfilebuf, fieldShift, pzero, pglobal, badSAD, badrange,
meander, pVecPrevOrNull, tryMany, optPredictorType
);
if (divideExtra)
{
// make extra level with divided sublocks with median (not estimated)
// motion
_vectorfields_aptr->ExtraDivide(
reinterpret_cast <int *> (pDst),
srd._analysis_data.nFlags
);
}
// PROFILE_CUMULATE ();
if (outfile != NULL)
{
fwrite(
outfilebuf,
sizeof(short) * 4 * srd._analysis_data.nBlkX
* srd._analysis_data.nBlkY,
1,
outfile
);
}
}
if (_temporal_flag)
{
// store previous vectors for use as predictor in next frame
memcpy(
&srd._vec_prev[0],
reinterpret_cast <int *> (pDst),
_vectorfields_aptr->GetArraySize()
);
srd._vec_prev_frame = nsrc;
}
_RPT3(0, "MAnalyze GetFrame END, frame_nsrc=%d nref=%d id=%d\n", nsrc, nref, _instance_id);
return dst;
}
void MVAnalyse::load_src_frame(MVGroupOfFrames &gof, ::PVideoFrame &src, const MVAnalysisData &ana_data)
{
PROFILE_START(MOTION_PROFILE_YUY2CONVERT);
const unsigned char * pSrcY;
const unsigned char * pSrcU;
const unsigned char * pSrcV;
int nSrcPitchY;
int nSrcPitchUV;
if ((ana_data.pixelType & VideoInfo::CS_YUY2) == VideoInfo::CS_YUY2)
{
// planar data packed to interleaved format (same as interleved2planar
// by kassandro) - v2.0.0.5
pSrcY = src->GetReadPtr();
pSrcU = pSrcY + src->GetRowSize() / 2;
pSrcV = pSrcU + src->GetRowSize() / 4;
nSrcPitchY = src->GetPitch();
nSrcPitchUV = nSrcPitchY;
}
else
{
pSrcY = src->GetReadPtr(PLANAR_Y);
pSrcU = src->GetReadPtr(PLANAR_U);
pSrcV = src->GetReadPtr(PLANAR_V);
nSrcPitchY = src->GetPitch(PLANAR_Y);
nSrcPitchUV = src->GetPitch(PLANAR_U);
}
PROFILE_STOP(MOTION_PROFILE_YUY2CONVERT);
gof.Update(
nModeYUV,
(BYTE*)pSrcY, nSrcPitchY,
(BYTE*)pSrcU, nSrcPitchUV,
(BYTE*)pSrcV, nSrcPitchUV
); // v2.0
}
#ifdef _WIN32
void MVAnalyse::GetHardwareAdapter(
IDXGIFactory1* pFactory,
IDXGIAdapter1** ppAdapter,
bool requestHighPerformanceAdapter)
{
*ppAdapter = nullptr;
ComPtr<IDXGIAdapter1> adapter;
ComPtr<IDXGIFactory6> factory6;
if (SUCCEEDED(pFactory->QueryInterface(IID_PPV_ARGS(&factory6))))
{
for (
UINT adapterIndex = 0;
SUCCEEDED(factory6->EnumAdapterByGpuPreference(
adapterIndex,
requestHighPerformanceAdapter == true ? DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE : DXGI_GPU_PREFERENCE_UNSPECIFIED,
IID_PPV_ARGS(&adapter)));
++adapterIndex)
{
DXGI_ADAPTER_DESC1 desc;
adapter->GetDesc1(&desc);
if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)
{
// Don't select the Basic Render Driver adapter.
// If you want a software adapter, pass in "/warp" on the command line.
continue;
}
// Check to see whether the adapter supports Direct3D 12, but don't create the
// actual device yet.
if (SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, _uuidof(ID3D12Device), nullptr)))
{
break;
}
}
}
if (adapter.Get() == nullptr)
{
for (UINT adapterIndex = 0; SUCCEEDED(pFactory->EnumAdapters1(adapterIndex, &adapter)); ++adapterIndex)
{
DXGI_ADAPTER_DESC1 desc;
adapter->GetDesc1(&desc);
if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)
{
// Don't select the Basic Render Driver adapter.
// If you want a software adapter, pass in "/warp" on the command line.
continue;
}
// Check to see whether the adapter supports Direct3D 12, but don't create the
// actual device yet.
if (SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, _uuidof(ID3D12Device), nullptr)))
{
break;
}
}
}
*ppAdapter = adapter.Detach();
}
void MVAnalyse::Init_DX12_ME(IScriptEnvironment* env, int nWidth, int nHeight, int iBlkSize)
{
// check for hardware D3D12 motion estimator support and init
UINT dxgiFactoryFlags = 0;
HRESULT hr;
hr = CreateDXGIFactory2(dxgiFactoryFlags, IID_PPV_ARGS(&factory));
if (hr != S_OK)
{
env->ThrowError(
"MAnalyse: Error CreateDXGIFactory2()"
);
}
GetHardwareAdapter(factory.Get(), &hardwareAdapter);
if (hardwareAdapter == NULL)
{
env->ThrowError(
"MAnalyse: Error GetHardwareAdapter return NULL"
);
}
hr = D3D12CreateDevice(
hardwareAdapter.Get(),
D3D_FEATURE_LEVEL_11_0,
IID_PPV_ARGS(&m_D3D12device)
);
if (hr != S_OK)
{
env->ThrowError(
"MAnalyse: Error D3D12CreateDevice()"
);
}
HRESULT query_device1_result = m_D3D12device->QueryInterface(IID_PPV_ARGS(&dev_D3D12VideoDevice));
D3D12_FEATURE_DATA_VIDEO_MOTION_ESTIMATOR MotionEstimatorSupport = { 0u, DXGI_FORMAT_NV12 };
HRESULT feature_support = dev_D3D12VideoDevice->CheckFeatureSupport(D3D12_FEATURE_VIDEO_MOTION_ESTIMATOR, &MotionEstimatorSupport, sizeof(MotionEstimatorSupport));
if (feature_support != S_OK)
{
env->ThrowError(
"MAnalyse: Error CheckFeatureSupport() D3D12_FEATURE_VIDEO_MOTION_ESTIMATOR"
);
}
// check if size supported
if (nWidth > MotionEstimatorSupport.SizeRange.MaxWidth)
{
env->ThrowError(
"MAnalyse: frame width not supported by DX12_ME, max supported width %d", MotionEstimatorSupport.SizeRange.MaxWidth
);
}
if (nHeight > MotionEstimatorSupport.SizeRange.MaxHeight)
{
env->ThrowError(
"MAnalyse: frame width not supported by DX12_ME, max supported width %d", MotionEstimatorSupport.SizeRange.MaxWidth
);
}
HRESULT query_vid_device1_result = dev_D3D12VideoDevice->QueryInterface(IID_PPV_ARGS(&dev_D3D12VideoDevice1));
if (query_device1_result != S_OK)
{
env->ThrowError(
"MAnalyse: Error QueryInterface -> dev_D3D12VideoDevice1"
);
}
D3D12_VIDEO_MOTION_ESTIMATOR_SEARCH_BLOCK_SIZE ME_BlockSize;
if (iBlkSize == 8)
{
ME_BlockSize = D3D12_VIDEO_MOTION_ESTIMATOR_SEARCH_BLOCK_SIZE_8X8;
}
else
if (iBlkSize == 16)
{
ME_BlockSize = D3D12_VIDEO_MOTION_ESTIMATOR_SEARCH_BLOCK_SIZE_16X16;
}
D3D12_VIDEO_MOTION_ESTIMATOR_DESC motionEstimatorDesc = {
0, //NodeIndex
DXGI_FORMAT_NV12,
ME_BlockSize,
D3D12_VIDEO_MOTION_ESTIMATOR_VECTOR_PRECISION_QUARTER_PEL,
{nWidth, nHeight, nWidth, nHeight} // D3D12_VIDEO_SIZE_RANGE
};
HRESULT vid_est_result = dev_D3D12VideoDevice1->CreateVideoMotionEstimator(
&motionEstimatorDesc,
nullptr,
IID_PPV_ARGS(&spVideoMotionEstimator));
if (vid_est_result != S_OK)
{
env->ThrowError(
"MAnalyse: Error CreateVideoMotionEstimator()"
);
}
D3D12_VIDEO_MOTION_VECTOR_HEAP_DESC MotionVectorHeapDesc = {
0, // NodeIndex
DXGI_FORMAT_NV12,
D3D12_VIDEO_MOTION_ESTIMATOR_SEARCH_BLOCK_SIZE_8X8,
D3D12_VIDEO_MOTION_ESTIMATOR_VECTOR_PRECISION_QUARTER_PEL,
{nWidth, nHeight, nWidth, nHeight} // D3D12_VIDEO_SIZE_RANGE
};
HRESULT vect_heap_result = dev_D3D12VideoDevice1->CreateVideoMotionVectorHeap(
&MotionVectorHeapDesc,
nullptr,
IID_PPV_ARGS(&spVideoMotionVectorHeap));
if (vect_heap_result != S_OK)
{
env->ThrowError(
"MAnalyse: Error CreateVideoMotionVectorHeap()"
);
}
HRESULT res_motion_vectors_texture = m_D3D12device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Tex2D(
DXGI_FORMAT_R16G16_SINT,
Align(nWidth, 8) / 8, // This example uses a 8x8 block size. Pixel width and height
Align(nHeight, 8) / 8, // are adjusted to store the vectors for those blocks.
1, // ArraySize
1 // MipLevels
),
D3D12_RESOURCE_STATE_COMMON,
nullptr,
IID_PPV_ARGS(&spResolvedMotionVectors));
if (res_motion_vectors_texture != S_OK)
{
env->ThrowError(
"MAnalyse: Error CreateCommittedResource -> spResolvedMotionVectors"
);
}
D3D12_RESOURCE_DESC textureDesc = {};
textureDesc.MipLevels = 1;
textureDesc.Format = DXGI_FORMAT_NV12;
textureDesc.Width = nWidth;
textureDesc.Height = nHeight;
textureDesc.Flags = D3D12_RESOURCE_FLAG_NONE;