forked from jeeb/avisynth
-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathavisynth.cpp
5798 lines (5032 loc) · 196 KB
/
avisynth.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
// Avisynth v2.6. Copyright 2002-2009 Ben Rudiak-Gould et al.
// http://avisynth.nl
// 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 .
//
// Linking Avisynth statically or dynamically with other modules is making a
// combined work based on Avisynth. Thus, the terms and conditions of the GNU
// General Public License cover the whole combination.
//
// As a special exception, the copyright holders of Avisynth give you
// permission to link Avisynth with independent modules that communicate with
// Avisynth solely through the interfaces defined in avisynth.h, regardless of the license
// terms of these independent modules, and to copy and distribute the
// resulting combined work under terms of your choice, provided that
// every copy of the combined work is accompanied by a complete copy of
// the source code of Avisynth (the version of Avisynth used to produce the
// combined work), being distributed under the terms of the GNU General
// Public License plus this exception. An independent module is a module
// which is not derived from or based on Avisynth, such as 3rd-party filters,
// import and export plugins, or graphical user interfaces.
#include <avisynth.h>
#include "../core/internal.h"
#include "InternalEnvironment.h"
#include "./parser/script.h"
#include <avs/minmax.h>
#include <avs/alignment.h>
#include "strings.h"
#include <avs/cpuid.h>
#include <unordered_set>
#include "bitblt.h"
#include "FilterConstructor.h"
#include "PluginManager.h"
#include "MappedList.h"
#include <chrono>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <exception>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#ifdef AVS_WINDOWS
#include <avs/win.h>
#include <objbase.h>
#else
#include "avisynth_conf.h"
#if defined(AVS_MACOS)
#include <mach/host_info.h>
#include <mach/mach_host.h>
#include <mach/mach_init.h>
#include <sys/sysctl.h>
#elif defined(AVS_BSD)
#include <sys/sysctl.h>
#else
#include <avs/filesystem.h>
#include <set>
#if defined(AVS_HAIKU)
#include <OS.h>
#else
#include <sys/sysinfo.h>
#endif
#endif
#include <avs/posix.h>
#endif
#include <string>
#include <cstdio>
#include <cstdarg>
#include <cassert>
#include "MTGuard.h"
#include "cache.h"
#include <clocale>
#include <cmath>
#include <limits>
#include "FilterGraph.h"
#include "DeviceManager.h"
#include "AVSMap.h"
#ifndef YieldProcessor // low power spin idle
#define YieldProcessor() __nop(void)
#endif
extern const AVSFunction Audio_filters[],
Combine_filters[],
Convert_filters[],
Convolution_filters[],
Edit_filters[],
Field_filters[],
Focus_filters[],
Fps_filters[],
Histogram_filters[],
Layer_filters[],
Levels_filters[],
Misc_filters[],
Plugin_functions[],
Resample_filters[],
Resize_filters[],
Script_functions[],
Source_filters[],
Text_filters[],
Transform_filters[],
Merge_filters[],
Color_filters[],
Debug_filters[],
Turn_filters[],
Conditional_filters[],
Conditional_funtions_filters[],
Cache_filters[],
Greyscale_filters[],
Swap_filters[],
Overlay_filters[],
Exprfilter_filters[],
FilterGraph_filters[],
Device_filters[]
;
const AVSFunction* const builtin_functions[] = {
Audio_filters,
Combine_filters,
Convert_filters,
Convolution_filters,
Edit_filters,
Field_filters,
Focus_filters,
Fps_filters,
Histogram_filters,
Layer_filters,
Levels_filters,
Misc_filters,
Resample_filters,
Resize_filters,
Script_functions,
Source_filters,
Text_filters,
Transform_filters,
Merge_filters,
Color_filters,
Debug_filters,
Turn_filters,
Conditional_filters,
Conditional_funtions_filters,
Plugin_functions,
Cache_filters,
Overlay_filters,
Greyscale_filters,
Swap_filters,
FilterGraph_filters,
Device_filters,
Exprfilter_filters
};
#if 0
// Global statistics counters
struct {
unsigned int CleanUps;
unsigned int Losses;
unsigned int PlanA1;
unsigned int PlanA2;
unsigned int PlanB;
unsigned int PlanC;
unsigned int PlanD;
char tag[36];
} g_Mem_stats = { 0, 0, 0, 0, 0, 0, 0, "CleanUps, Losses, Plan[A1,A2,B,C,D]" };
#endif
const _PixelClip PixelClip;
#ifdef MSVC
// Helper function to count set bits in the processor mask.
template<typename T>
static uint32_t CountSetBits(T bitMask)
{
uint32_t LSHIFT = sizeof(T) * 8 - 1;
uint32_t bitSetCount = 0;
T bitTest = (T)1 << LSHIFT;
uint32_t i;
for (i = 0; i <= LSHIFT; ++i)
{
bitSetCount += ((bitMask & bitTest) ? 1 : 0);
bitTest /= 2;
}
return bitSetCount;
}
#endif
static size_t GetNumPhysicalCPUs()
{
#if defined(AVS_WINDOWS)
#ifdef MSVC
typedef BOOL(WINAPI* LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);
LPFN_GLPI glpi;
BOOL done = FALSE;
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL;
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION ptr = NULL;
DWORD returnLength = 0;
[[maybe_unused]] DWORD logicalProcessorCount = 0;
[[maybe_unused]] DWORD numaNodeCount = 0;
[[maybe_unused]] DWORD processorCoreCount = 0;
[[maybe_unused]] DWORD processorL1CacheCount = 0;
[[maybe_unused]] DWORD processorL2CacheCount = 0;
[[maybe_unused]] DWORD processorL3CacheCount = 0;
[[maybe_unused]] DWORD processorPackageCount = 0;
DWORD byteOffset = 0;
PCACHE_DESCRIPTOR Cache;
glpi = (LPFN_GLPI)GetProcAddress(
GetModuleHandle(TEXT("kernel32")),
"GetLogicalProcessorInformation");
if (NULL == glpi)
{
// _tprintf(TEXT("\nGetLogicalProcessorInformation is not supported.\n"));
return (0);
}
while (!done)
{
BOOL rc = glpi(buffer, &returnLength);
if (FALSE == rc)
{
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
if (buffer)
free(buffer);
buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc(
returnLength);
if (NULL == buffer)
{
// _tprintf(TEXT("\nError: Allocation failure\n"));
return (0);
}
}
else
{
// _tprintf(TEXT("\nError %d\n"), GetLastError());
return (0);
}
}
else
{
done = TRUE;
}
}
ptr = buffer;
while (byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnLength)
{
switch (ptr->Relationship)
{
case RelationNumaNode:
// Non-NUMA systems report a single record of this type.
numaNodeCount++;
break;
case RelationProcessorCore:
processorCoreCount++;
// A hyperthreaded core supplies more than one logical processor.
logicalProcessorCount += CountSetBits<ULONG_PTR>(ptr->ProcessorMask);
break;
case RelationCache:
// Cache data is in ptr->Cache, one CACHE_DESCRIPTOR structure for each cache.
Cache = &ptr->Cache;
if (Cache->Level == 1)
{
processorL1CacheCount++;
}
else if (Cache->Level == 2)
{
processorL2CacheCount++;
}
else if (Cache->Level == 3)
{
processorL3CacheCount++;
}
break;
case RelationProcessorPackage:
// Logical processors share a physical package.
processorPackageCount++;
break;
default:
// _tprintf(TEXT("\nError: Unsupported LOGICAL_PROCESSOR_RELATIONSHIP value.\n"));
return (0);
}
byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
ptr++;
}
/*
_tprintf(TEXT("\nGetLogicalProcessorInformation results:\n"));
_tprintf(TEXT("Number of NUMA nodes: %d\n"),
numaNodeCount);
_tprintf(TEXT("Number of physical processor packages: %d\n"),
processorPackageCount);
_tprintf(TEXT("Number of processor cores: %d\n"),
processorCoreCount);
_tprintf(TEXT("Number of logical processors: %d\n"),
logicalProcessorCount);
_tprintf(TEXT("Number of processor L1/L2/L3 caches: %d/%d/%d\n"),
processorL1CacheCount,
processorL2CacheCount,
processorL3CacheCount);
*/
free(buffer);
return processorCoreCount;
#else
return 4; // TODO: GCC on Windows?
#endif
#elif defined(AVS_LINUX)
std::set<int> core_ids;
for (auto& p : fs::directory_iterator("/sys/devices/system/cpu")) {
if (!p.path().filename().string().rfind("cpu", 0)) {
std::ifstream ifs(p.path() / "topology/core_id");
int core_id;
if (ifs) {
ifs >> core_id;
if (ifs)
core_ids.insert(core_id);
}
}
}
return core_ids.size();
#elif defined(AVS_MACOS)
int cpu_cnt = 0;
size_t cpu_cnt_size = sizeof(cpu_cnt);
return sysctlbyname("hw.physicalcpu", &cpu_cnt, &cpu_cnt_size, NULL, 0) ? 0 : cpu_cnt;
#else
return 4; // AVS_BSD TODO
#endif
}
#ifdef MSVC
static std::string FormatString(const char* fmt, va_list args)
{
va_list args2;
va_copy(args2, args);
_locale_t locale = _create_locale(LC_NUMERIC, "C"); // decimal point: dot
int count = _vscprintf_l(fmt, locale, args2);
// don't use _vsnprintf_l(NULL, 0, fmt, locale, args) here,
// it returns -1 instead of the buffer size under Wine (February, 2017)
std::vector<char> buf(count + 1);
_vsnprintf_l(buf.data(), buf.size(), fmt, locale, args2);
_free_locale(locale);
va_end(args2);
return std::string(buf.data());
}
#else
static std::string FormatString(const char* fmt, va_list args)
{
va_list args2;
va_copy(args2, args);
// There is no locale specific version of vsnprintf under Linux/gcc.
// During program startup, the equivalent of setlocale(LC_ALL, "C")
// is executed before any user code is run. But Avisynth is just a dll/shared object.
// If the host program calls std::setlocale(LC_ALL, "") - typically in its 'main()'
// then it sets current locale by the environment variables.
// Unfortunately setlocale is not thread safe and modifies global state which
// affects execution of locale-dependent functions, it is undefined behavior to call
// it from one thread, while another thread is executing any of such functions (e.g. sprintf)
// It can happen that a plugin sets setlocale(LC_ALL, ""). The effect is global,
// other formatting functions in the same program will start using the new
// (environment) setting.
// One must set LC_NUMERIC part of the locale to "C" before the host executable,
// to be sure that after such unsafe setlocale(LC_ALL, "") then formatting to dot
// remains O.K.
#if 0
// Finally we don't do that. Not 100% safe.
std::string prev_loc = std::setlocale(LC_NUMERIC, nullptr);
setlocale(LC_NUMERIC, "C"); // Set C locale for '.' and no thousand sep
#endif
int count = vsnprintf(NULL, 0, fmt, args);
std::vector<char> buf(count + 1);
vsnprintf(buf.data(), buf.size(), fmt, args2);
va_end(args2);
#if 0
std::setlocale(LC_NUMERIC, prev_loc.c_str()); // Restore the previous locale.
#endif
return std::string(buf.data());
}
#endif
void* VideoFrame::operator new(size_t size) {
return ::operator new(size);
}
VideoFrame::VideoFrame(VideoFrameBuffer* _vfb, AVSMap* avsmap, int _offset, int _pitch, int _row_size, int _height, int _pixel_type)
: refcount(0), vfb(_vfb), offset(_offset), pitch(_pitch), row_size(_row_size), height(_height),
offsetU(_offset), offsetV(_offset), pitchUV(0), row_sizeUV(0), heightUV(0), // PitchUV=0 so this doesn't take up additional space
offsetA(0), pitchA(0), row_sizeA(0),
pixel_type(_pixel_type),
properties(avsmap)
{
InterlockedIncrement(&vfb->refcount);
}
VideoFrame::VideoFrame(VideoFrameBuffer* _vfb, AVSMap* avsmap, int _offset, int _pitch, int _row_size, int _height,
int _offsetU, int _offsetV, int _pitchUV, int _row_sizeUV, int _heightUV, int _pixel_type)
: refcount(0), vfb(_vfb), offset(_offset), pitch(_pitch), row_size(_row_size), height(_height),
offsetU(_offsetU), offsetV(_offsetV), pitchUV(_pitchUV), row_sizeUV(_row_sizeUV), heightUV(_heightUV),
offsetA(0), pitchA(0), row_sizeA(0),
pixel_type(_pixel_type),
properties(avsmap)
{
InterlockedIncrement(&vfb->refcount);
}
VideoFrame::VideoFrame(VideoFrameBuffer* _vfb, AVSMap* avsmap, int _offset, int _pitch, int _row_size, int _height,
int _offsetU, int _offsetV, int _pitchUV, int _row_sizeUV, int _heightUV, int _offsetA, int _pixel_type)
: refcount(0), vfb(_vfb), offset(_offset), pitch(_pitch), row_size(_row_size), height(_height),
offsetU(_offsetU), offsetV(_offsetV), pitchUV(_pitchUV), row_sizeUV(_row_sizeUV), heightUV(_heightUV),
offsetA(_offsetA), pitchA(_pitch), row_sizeA(_row_size),
pixel_type(_pixel_type),
properties(avsmap)
{
InterlockedIncrement(&vfb->refcount);
}
// Hack note: Use of Subframe will require an "InterlockedDecrement(&retval->refcount);" after
// assignment to a PVideoFrame, the same as for a "New VideoFrame" to keep the refcount consistant.
// P.F. ?? so far it works automatically
VideoFrame* VideoFrame::Subframe(int rel_offset, int new_pitch, int new_row_size, int new_height) const {
// Change planar color formats to Y-only, which is quasi-interleaved
int new_pixel_type;
if (pixel_type & VideoInfo::CS_PLANAR)
new_pixel_type = VideoInfo::CS_GENERIC_Y | (pixel_type & VideoInfo::CS_Sample_Bits_Mask);
else
new_pixel_type = pixel_type;
return new VideoFrame(vfb, new AVSMap(), offset + rel_offset, new_pitch, new_row_size, new_height,
new_pixel_type);
}
VideoFrame* VideoFrame::Subframe(int rel_offset, int new_pitch, int new_row_size, int new_height,
int rel_offsetU, int rel_offsetV, int new_pitchUV) const {
// Maintain plane size relationship
const int new_row_sizeUV = !row_size ? 0 : MulDiv(new_row_size, row_sizeUV, row_size);
const int new_heightUV = !height ? 0 : MulDiv(new_height, heightUV, height);
// Remove alpha from color format
int new_pixel_type;
if (pixel_type & VideoInfo::CS_YUVA)
new_pixel_type = (pixel_type & ~VideoInfo::CS_YUVA) | VideoInfo::CS_YUV;
else if (pixel_type & VideoInfo::CS_RGBA_TYPE)
new_pixel_type = (pixel_type & ~VideoInfo::CS_RGBA_TYPE) | VideoInfo::CS_RGB_TYPE;
else
new_pixel_type = pixel_type;
return new VideoFrame(vfb, new AVSMap(), offset + rel_offset, new_pitch, new_row_size, new_height,
rel_offsetU + offsetU, rel_offsetV + offsetV, new_pitchUV, new_row_sizeUV, new_heightUV,
new_pixel_type);
}
// alpha support
VideoFrame* VideoFrame::Subframe(int rel_offset, int new_pitch, int new_row_size, int new_height,
int rel_offsetU, int rel_offsetV, int new_pitchUV,
int rel_offsetA) const {
// Maintain plane size relationship
const int new_row_sizeUV = !row_size ? 0 : MulDiv(new_row_size, row_sizeUV, row_size);
const int new_heightUV = !height ? 0 : MulDiv(new_height, heightUV, height);
return new VideoFrame(vfb, new AVSMap(), offset + rel_offset, new_pitch, new_row_size, new_height,
offsetU + rel_offsetU, offsetV + rel_offsetV, new_pitchUV, new_row_sizeUV, new_heightUV,
offsetA + rel_offsetA,
pixel_type);
}
VideoFrameBuffer::VideoFrameBuffer() :
data(nullptr),
data_size(0),
sequence_number(0),
refcount(1),
device(nullptr)
{ }
VideoFrameBuffer::VideoFrameBuffer(int size, int margin, Device* device) :
data(device->Allocate(size, margin)),
data_size(size),
sequence_number(0),
refcount(0),
device(device)
{ }
VideoFrameBuffer::~VideoFrameBuffer() { DESTRUCTOR(); }
void VideoFrameBuffer::DESTRUCTOR() {
// _ASSERTE(refcount == 0);
InterlockedIncrement(&sequence_number); // HACK: Notify any children with a pointer, this buffer has changed!!!
if (data) device->Free(data);
data = nullptr; // and mark it invalid!!
data_size = 0; // and don't forget to set the size to 0 as well!
device = nullptr; // no longer related to a device
}
class AtExiter {
struct AtExitRec {
const IScriptEnvironment::ShutdownFunc func;
void* const user_data;
AtExitRec* const next;
AtExitRec(IScriptEnvironment::ShutdownFunc _func, void* _user_data, AtExitRec* _next)
: func(_func), user_data(_user_data), next(_next) {}
};
AtExitRec* atexit_list;
public:
AtExiter() {
atexit_list = 0;
}
void Add(IScriptEnvironment::ShutdownFunc f, void* d) {
atexit_list = new AtExitRec(f, d, atexit_list);
}
void Execute(IScriptEnvironment* env) {
while (atexit_list) {
AtExitRec* next = atexit_list->next;
atexit_list->func(atexit_list->user_data, env);
delete atexit_list;
atexit_list = next;
}
}
};
static std::string NormalizeString(const std::string& str)
{
// lowercase
std::string ret = str;
for (size_t i = 0; i < ret.size(); ++i)
ret[i] = tolower(ret[i]);
// trim trailing spaces
size_t endpos = ret.find_last_not_of(" \t");
if (std::string::npos != endpos)
ret = ret.substr(0, endpos + 1);
// trim leading spaces
size_t startpos = ret.find_first_not_of(" \t");
if (std::string::npos != startpos)
ret = ret.substr(startpos);
return ret;
}
typedef enum class _MtWeight
{
MT_WEIGHT_0_DEFAULT,
MT_WEIGHT_1_USERSPEC,
MT_WEIGHT_2_USERFORCE,
MT_WEIGHT_MAX
} MtWeight;
class ClipDataStore
{
public:
// The clip instance that we hold data for.
IClip* Clip = nullptr;
// Clip was created directly by an Invoke() call
bool CreatedByInvoke = false;
ClipDataStore(IClip* clip) : Clip(clip) {};
};
class MtModeEvaluator
{
public:
int NumChainedNice = 0;
int NumChainedMulti = 0;
int NumChainedSerial = 0;
MtMode GetFinalMode(MtMode topInvokeMode)
{
if (NumChainedSerial > 0)
{
return MT_SERIALIZED;
}
else if (NumChainedMulti > 0)
{
if (MT_SERIALIZED == topInvokeMode)
{
return MT_SERIALIZED;
}
else
{
return MT_MULTI_INSTANCE;
}
}
else
{
return topInvokeMode;
}
}
void Accumulate(const MtModeEvaluator& other)
{
NumChainedNice += other.NumChainedNice;
NumChainedMulti += other.NumChainedMulti;
NumChainedSerial += other.NumChainedSerial;
}
void Accumulate(MtMode mode)
{
switch (mode)
{
case MT_NICE_FILTER:
++NumChainedNice;
break;
case MT_MULTI_INSTANCE:
++NumChainedMulti;
break;
case MT_SERIALIZED:
++NumChainedSerial;
break;
default:
assert(0);
break;
}
}
static bool ClipSpecifiesMtMode(const PClip& clip)
{
int val = clip->SetCacheHints(CACHE_GET_MTMODE, 0);
return (clip->GetVersion() >= 5) && (val > MT_INVALID) && (val < MT_MODE_COUNT);
}
static MtMode GetInstanceMode(const PClip& clip, MtMode defaultMode)
{
return ClipSpecifiesMtMode(clip) ? (MtMode)clip->SetCacheHints(CACHE_GET_MTMODE, 0) : defaultMode;
}
static MtMode GetInstanceMode(const PClip& clip)
{
return (MtMode)clip->SetCacheHints(CACHE_GET_MTMODE, 0);
}
static MtMode GetMtMode(const PClip& clip, const Function* invokeCall, const InternalEnvironment* env)
{
bool invokeModeForced;
MtMode invokeMode = env->GetFilterMTMode(invokeCall, &invokeModeForced);
if (invokeModeForced) {
return invokeMode;
}
bool hasInstanceMode = ClipSpecifiesMtMode(clip);
if (hasInstanceMode) {
return GetInstanceMode(clip);
}
else {
return invokeMode;
}
}
static bool UsesDefaultMtMode(const PClip& clip, const Function* invokeCall, const InternalEnvironment* env)
{
return !ClipSpecifiesMtMode(clip) && !env->FilterHasMtMode(invokeCall);
}
void AddChainedFilter(const PClip& clip, MtMode defaultMode)
{
MtMode mode = GetInstanceMode(clip, defaultMode);
Accumulate(mode);
}
};
OneTimeLogTicket::OneTimeLogTicket(ELogTicketType type)
: _type(type)
{}
OneTimeLogTicket::OneTimeLogTicket(ELogTicketType type, const Function* func)
: _type(type), _function(func)
{}
OneTimeLogTicket::OneTimeLogTicket(ELogTicketType type, const std::string& str)
: _type(type), _string(str)
{}
bool OneTimeLogTicket::operator==(const OneTimeLogTicket& other) const
{
return (_type == other._type)
&& (_function == other._function)
&& (_string.compare(other._string) == 0);
}
namespace std
{
template <>
struct hash<OneTimeLogTicket>
{
std::size_t operator()(const OneTimeLogTicket& k) const
{
// TODO: This is a pretty poor combination function for hashes.
// Find something better than a simple XOR.
return hash<int>()(k._type)
^ hash<void*>()((void*)k._function)
^ hash<std::string>()((std::string)k._string);
}
};
}
#include "vartable.h"
#include "ThreadPool.h"
#include <map>
#include <unordered_set>
#include <atomic>
#include <stack>
#include "Prefetcher.h"
#include "BufferPool.h"
#include "ScriptEnvironmentTLS.h"
class ThreadScriptEnvironment;
// order is not important, unlike in IScriptEnvironment variants.
class ScriptEnvironment {
public:
ScriptEnvironment();
void CheckVersion(int version);
int GetCPUFlags();
void AddFunction(const char* name, const char* params, INeoEnv::ApplyFunc apply, void* user_data = 0);
void AddFunction25(const char* name, const char* params, INeoEnv::ApplyFunc apply, void* user_data = 0);
void AddFunctionPreV11C(const char* name, const char* params, INeoEnv::ApplyFunc apply, void* user_data = 0);
bool FunctionExists(const char* name);
PVideoFrame NewVideoFrameOnDevice(const VideoInfo& vi, int align, Device* device);
PVideoFrame NewVideoFrameOnDevice(int row_size, int height, int align, int pixel_type, Device* device);
PVideoFrame NewVideoFrame(const VideoInfo& vi, const PDevice& device);
// variant #3, with frame property source
PVideoFrame NewVideoFrameOnDevice(const VideoInfo& vi, int align, Device* device, const PVideoFrame *prop_src);
// variant #1, with frame property source
PVideoFrame NewVideoFrameOnDevice(int row_size, int height, int align, int pixel_type, Device* device, const PVideoFrame* prop_src);
// variant #2, with frame property source
PVideoFrame NewVideoFrame(const VideoInfo& vi, const PDevice& device, const PVideoFrame* prop_src);
PVideoFrame NewPlanarVideoFrame(int row_size, int height, int row_sizeUV, int heightUV, int align, bool U_first, int pixel_type, Device* device);
bool MakeWritable(PVideoFrame* pvf);
void BitBlt(BYTE* dstp, int dst_pitch, const BYTE* srcp, int src_pitch, int row_size, int height);
void AtExit(IScriptEnvironment::ShutdownFunc function, void* user_data);
PVideoFrame Subframe(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height);
int SetMemoryMax(int mem);
int SetWorkingDir(const char* newdir);
AVSC_CC ~ScriptEnvironment();
void* ManageCache(int key, void* data);
bool PlanarChromaAlignment(IScriptEnvironment::PlanarChromaAlignmentMode key);
PVideoFrame SubframePlanar(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int new_pitchUV);
void DeleteScriptEnvironment();
void ApplyMessage(PVideoFrame* frame, const VideoInfo& vi, const char* message, int size, int textcolor, int halocolor, int bgcolor);
const AVS_Linkage* GetAVSLinkage();
// alpha support
PVideoFrame NewPlanarVideoFrame(int row_size, int height, int row_sizeUV, int heightUV, int align, bool U_first, bool alpha, int pixel_type, Device* device);
PVideoFrame SubframePlanar(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int new_pitchUV, int rel_offsetA);
PVideoFrame SubframePlanarA(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int new_pitchUV, int rel_offsetA);
void copyFrameProps(const PVideoFrame& src, PVideoFrame& dst);
const AVSMap* getFramePropsRO(const PVideoFrame& frame) AVS_NOEXCEPT;
AVSMap* getFramePropsRW(PVideoFrame& frame) AVS_NOEXCEPT;
int propNumKeys(const AVSMap* map) AVS_NOEXCEPT;
const char* propGetKey(const AVSMap* map, int index) AVS_NOEXCEPT;
int propNumElements(const AVSMap* map, const char* key) AVS_NOEXCEPT;
char propGetType(const AVSMap* map, const char* key) AVS_NOEXCEPT;
int propDeleteKey(AVSMap* map, const char* key) AVS_NOEXCEPT;
int64_t propGetInt(const AVSMap* map, const char* key, int index, int* error) AVS_NOEXCEPT;
int propGetIntSaturated(const AVSMap* map, const char* key, int index, int* error) AVS_NOEXCEPT;
double propGetFloat(const AVSMap* map, const char* key, int index, int* error) AVS_NOEXCEPT;
float propGetFloatSaturated(const AVSMap* map, const char* key, int index, int* error) AVS_NOEXCEPT;
const char* propGetData(const AVSMap* map, const char* key, int index, int* error) AVS_NOEXCEPT;
int propGetDataSize(const AVSMap* map, const char* key, int index, int* error) AVS_NOEXCEPT;
int propGetDataTypeHint(const AVSMap* map, const char* key, int index, int* error) AVS_NOEXCEPT;
PClip propGetClip(const AVSMap* map, const char* key, int index, int* error) AVS_NOEXCEPT;
const PVideoFrame propGetFrame(const AVSMap* map, const char* key, int index, int* error) AVS_NOEXCEPT;
int propSetInt(AVSMap* map, const char* key, int64_t i, int append) AVS_NOEXCEPT;
int propSetFloat(AVSMap* map, const char* key, double d, int append) AVS_NOEXCEPT;
int propSetData(AVSMap* map, const char* key, const char* d, int length, int append) AVS_NOEXCEPT;
int propSetDataH(AVSMap* map, const char* key, const char* d, int length, int type, int append) AVS_NOEXCEPT;
int propSetClip(AVSMap* map, const char* key, PClip& clip, int append) AVS_NOEXCEPT;
int propSetFrame(AVSMap* map, const char* key, const PVideoFrame& frame, int append) AVS_NOEXCEPT;
const int64_t* propGetIntArray(const AVSMap* map, const char* key, int* error) AVS_NOEXCEPT;
const double* propGetFloatArray(const AVSMap* map, const char* key, int* error) AVS_NOEXCEPT;
int propSetIntArray(AVSMap* map, const char* key, const int64_t* i, int size) AVS_NOEXCEPT;
int propSetFloatArray(AVSMap* map, const char* key, const double* d, int size) AVS_NOEXCEPT;
AVSMap* createMap() AVS_NOEXCEPT;
void freeMap(AVSMap* map) AVS_NOEXCEPT;
void clearMap(AVSMap* map) AVS_NOEXCEPT;
PVideoFrame NewVideoFrame(const VideoInfo& vi, const PVideoFrame* prop_src, int align = FRAME_ALIGN);
bool MakePropertyWritable(PVideoFrame* pvf); // V9
/* IScriptEnvironment2 */
bool LoadPlugin(const char* filePath, bool throwOnError, AVSValue *result);
void AddAutoloadDir(const char* dirPath, bool toFront);
void ClearAutoloadDirs();
void AutoloadPlugins();
void AddFunction(const char* name, const char* params, INeoEnv::ApplyFunc apply, void* user_data, const char *exportVar);
bool InternalFunctionExists(const char* name);
void AdjustMemoryConsumption(size_t amount, bool minus);
void SetFilterMTMode(const char* filter, MtMode mode, bool force);
void SetFilterMTMode(const char* filter, MtMode mode, MtWeight weight);
MtMode GetFilterMTMode(const Function* filter, bool* is_forced) const;
void ParallelJob(ThreadWorkerFuncPtr jobFunc, void* jobData, IJobCompletion* completion);
IJobCompletion* NewCompletion(size_t capacity);
size_t GetEnvProperty(AvsEnvProperty prop);
ClipDataStore* ClipData(IClip* clip);
MtMode GetDefaultMtMode() const;
bool FilterHasMtMode(const Function* filter) const;
void SetLogParams(const char* target, int level);
void LogMsg(int level, const char* fmt, ...);
void LogMsg_valist(int level, const char* fmt, va_list va);
void LogMsgOnce(const OneTimeLogTicket& ticket, int level, const char* fmt, ...);
void LogMsgOnce_valist(const OneTimeLogTicket& ticket, int level, const char* fmt, va_list va);
void SetMaxCPU(const char *features); // fixme: why is here InternalEnvironment?
/* INeoEnv */
bool Invoke_(AVSValue *result, const AVSValue& implicit_last,
const char* name, const Function *f, const AVSValue& args, const char* const* arg_names,
InternalEnvironment* env_thread, bool is_runtime);
PDevice GetDevice(AvsDeviceType device_type, int device_index) const;
int SetMemoryMax(AvsDeviceType type, int index, int mem);
PVideoFrame GetOnDeviceFrame(const PVideoFrame& src, Device* device);
void ParallelJob(ThreadWorkerFuncPtr jobFunc, void* jobData, IJobCompletion* completion, InternalEnvironment *env);
ThreadPool* NewThreadPool(size_t nThreads);
void SetGraphAnalysis(bool enable) { graphAnalysisEnable = enable; }
char* ListAutoloadDirs();
void IncEnvCount() { InterlockedIncrement(&EnvCount); }
void DecEnvCount() { InterlockedDecrement(&EnvCount); }
ConcurrentVarStringFrame* GetTopFrame() { return &top_frame; }
void SetCacheMode(CacheMode mode) { cacheMode = mode; }
CacheMode GetCacheMode() { return cacheMode; }
void SetDeviceOpt(DeviceOpt opt, int val);
void UpdateFunctionExports(const char* funcName, const char* funcParams, const char* exportVar);
// public, AVSMap error should access
void ThrowError(const char* fmt, ...);
ThreadScriptEnvironment* GetMainThreadEnv() { return threadEnv.get(); }
private:
typedef IScriptEnvironment::NotFound NotFound;
typedef IScriptEnvironment::ApplyFunc ApplyFunc;
// Tritical May 2005
// Note order here!!
// AtExiter has functions which
// rely on StringDump elements.
ConcurrentVarStringFrame top_frame;
std::unique_ptr<ThreadScriptEnvironment> threadEnv;
std::mutex string_mutex;
AtExiter at_exit;
ThreadPool* thread_pool;
PluginManager* plugin_manager;
std::recursive_mutex plugin_mutex;
long EnvCount; // for ThreadScriptEnvironment leak detection
void VThrowError(const char* fmt, va_list va);
const Function* Lookup(const char* search_name, const AVSValue* args, size_t num_args,
bool &pstrict, size_t args_names_count, const char* const* arg_names, IScriptEnvironment2* env_thread);
bool CheckArguments(const Function* f, const AVSValue* args, size_t num_args,
bool &pstrict, size_t args_names_count, const char* const* arg_names);
std::unordered_map<IClip*, ClipDataStore> clip_data;
void ExportBuiltinFilters();
bool PlanarChromaAlignmentState;
long hrfromcoinit;
uint32_t coinitThreadId;
struct DebugTimestampedFrame
{
VideoFrame* frame;
#ifdef _DEBUG
std::chrono::time_point<std::chrono::high_resolution_clock> timestamp;
#endif
DebugTimestampedFrame(VideoFrame* _frame)
: frame(_frame)
#ifdef _DEBUG
, timestamp(std::chrono::high_resolution_clock::now())
#endif
{}
};
class VFBStorage : public VideoFrameBuffer {
public:
int free_count;
int margin;
PGraphMemoryNode memory_node;
VFBStorage()
: VideoFrameBuffer(),
free_count(0),
margin(0)
{ }
VFBStorage(int size, int margin, Device* device)
: VideoFrameBuffer(size, margin, device),
free_count(0),
margin(margin)
{ }
void Attach(FilterGraphNode* node) {
if (memory_node) {
memory_node->OnFree(data_size, device);
memory_node = nullptr;
}
if (node != nullptr) {
memory_node = node->GetMemoryNode();
memory_node->OnAllocate(data_size, device);
}
}
~VFBStorage() {
if (memory_node) {
memory_node->OnFree(data_size, device);
memory_node = nullptr;
}
#ifdef _DEBUG
if (data && device->device_type == DEV_TYPE_CPU) {
// check buffer overrun
int *pInt = (int *)(data + margin + data_size);
if (pInt[0] != 0xDEADBEEF ||
pInt[1] != 0xDEADBEEF ||
pInt[2] != 0xDEADBEEF ||
pInt[3] != 0xDEADBEEF)
{
printf("Buffer overrun!!!\n");
}
}
#endif
}
};
typedef std::vector<DebugTimestampedFrame> VideoFrameArrayType;
typedef std::map<VideoFrameBuffer *, VideoFrameArrayType> FrameBufferRegistryType;
typedef std::map<size_t, FrameBufferRegistryType> FrameRegistryType2; // post r1825 P.F.
typedef mapped_list<Cache*> CacheRegistryType;
FrameRegistryType2 FrameRegistry2; // P.F.
#ifdef _DEBUG
void ListFrameRegistry(size_t min_size, size_t max_size, bool someframes);
#endif
std::unique_ptr<DeviceManager> Devices;
CacheRegistryType CacheRegistry;