This repository was archived by the owner on May 16, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVideoSource2.cpp
More file actions
2339 lines (2060 loc) · 67.1 KB
/
VideoSource2.cpp
File metadata and controls
2339 lines (2060 loc) · 67.1 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
#include "InputFile2.h"
#include "VideoSource2.h"
#include "cineform.h"
#include "export.h"
extern "C" {
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <libavutil/imgutils.h>
}
const int line_align = 16; // should be ok with any usable filter down the pipeline
extern bool config_force_thread;
extern float config_cache_size;
uint8_t* align_buf(uint8_t* p)
{
return (uint8_t*)(ptrdiff_t(p+line_align-1) & ~(line_align-1));
}
VDFFVideoSource::VDFFVideoSource(const VDXInputDriverContext& context)
:mContext(context)
{
m_pFormatCtx = 0;
m_pStreamCtx = 0;
m_pCodecCtx = 0;
m_pSwsCtx = 0;
direct_format = 0;
direct_format_len = 0;
frame = 0;
memset(©_pkt,0,sizeof(copy_pkt));
errorMode = kErrorModeReportAll; // still not supported by host anyway
m_pixmap_data = 0;
m_pixmap_frame = -1;
last_request = -1;
next_frame = -1;
last_seek_frame = -1;
buffer = 0;
buffer_count = 0;
small_buffer_count = 0;
buffer_reserve = 0;
frame_array = 0;
frame_type = 0;
flip_image = false;
direct_buffer = false;
direct_cfhd = false;
is_image_list = false;
avi_drop_index = false;
copy_mode = false;
decode_mode = true;
small_cache_mode = false;
enable_prefetch = false;
decoded_count = 0;
buffer = 0;
mem = 0;
/*
kPixFormat_XRGB64 = 0;
IFilterModPixmap* fmpixmap = (IFilterModPixmap*)context.mpCallbacks->GetExtendedAPI("IFilterModPixmap");
if(fmpixmap){
kPixFormat_XRGB64 = fmpixmap->GetFormat_XRGB64();
}
*/
}
VDFFVideoSource::~VDFFVideoSource()
{
av_packet_unref(©_pkt);
free(direct_format);
if(frame) av_frame_free(&frame);
if(m_pCodecCtx) avcodec_free_context(&m_pCodecCtx);
if(m_pSwsCtx) sws_freeContext(m_pSwsCtx);
if(buffer) {for(int i=0; i<buffer_count; i++){
BufferPage& p = buffer[i];
dealloc_page(&p);
}}
if(mem) CloseHandle(mem);
free(buffer);
free(frame_array);
free(frame_type);
free(m_pixmap_data);
}
int VDFFVideoSource::AddRef() {
return vdxunknown<IVDXStreamSource>::AddRef();
}
int VDFFVideoSource::Release() {
return vdxunknown<IVDXStreamSource>::Release();
}
void *VDXAPIENTRY VDFFVideoSource::AsInterface(uint32_t iid)
{
if (iid == IVDXVideoSource::kIID)
return static_cast<IVDXVideoSource *>(this);
if (iid == IVDXVideoDecoder::kIID)
return static_cast<IVDXVideoDecoder *>(this);
if (iid == IFilterModVideoDecoder::kIID)
return static_cast<IFilterModVideoDecoder *>(this);
if (iid == IVDXStreamSourceV3::kIID)
return static_cast<IVDXStreamSourceV3 *>(this);
if (iid == IVDXStreamSourceV5::kIID)
return static_cast<IVDXStreamSourceV5 *>(this);
return vdxunknown<IVDXStreamSource>::AsInterface(iid);
}
int VDFFVideoSource::init_duration(const AVRational fr)
{
AVRational tb = m_pStreamCtx->time_base;
av_reduce(&time_base.num, &time_base.den, int64_t(fr.num)*tb.num, int64_t(fr.den)*tb.den, INT_MAX);
int sample_count_error = 2;
if(m_pSource->is_image_list){
sample_count = (int)m_pStreamCtx->nb_frames;
sample_count_error = 0;
} else {
int64_t duration = m_pStreamCtx->duration;
if(m_pStreamCtx->duration == AV_NOPTS_VALUE){
if(m_pFormatCtx->duration != AV_NOPTS_VALUE){
duration = av_rescale_q_rnd(m_pFormatCtx->duration, av_make_q(1,AV_TIME_BASE), m_pStreamCtx->time_base, AV_ROUND_NEAR_INF);
}
}
if(duration != AV_NOPTS_VALUE){
int rndd = time_base.den/2;
//! stream duration really means last timestamp
// found on "10 bit.mp4"
// also works with mkv (derived from file duration)
int64_t start_pts = m_pStreamCtx->start_time;
if(start_pts==AV_NOPTS_VALUE) start_pts = 0;
duration -= start_pts;
//! above idea fails on Hilary.0000.ts
bool mts = false;
AVInputFormat* mts_format = av_find_input_format("mpegts");
if(m_pFormatCtx->iformat==mts_format) mts = true;
if(mts || duration<=0){
// undo previous step
duration += start_pts;
start_pts = 0; // ignore count_error
}
sample_count = (int)((duration * time_base.num + rndd) / time_base.den);
int e = (int)((start_pts * time_base.num + rndd) / time_base.den);
e = abs(e);
if(e>sample_count_error) sample_count_error = e;
// found in some mp4 produced with GPAC 0.5.1
if(m_pStreamCtx->nb_index_entries>0 && (m_pStreamCtx->index_entries[0].flags & AVINDEX_DISCARD_FRAME)!=0) sample_count_error++;
} else {
if(m_pSource->is_image){
sample_count = 1;
} else {
mContext.mpCallbacks->SetError("FFMPEG: Cannot figure stream duration. Unsupported.");
return -1;
}
}
}
if(sample_count==0){
// found in 1-frame nut
AVInputFormat* nut_format = av_find_input_format("nut");
if(m_pFormatCtx->iformat==nut_format) sample_count = 1;
}
m_streamInfo.mInfo.mSampleRate.mNumerator = fr.num;
m_streamInfo.mInfo.mSampleRate.mDenominator = fr.den;
return sample_count_error;
}
int VDFFVideoSource::initStream( VDFFInputFile* pSource, int streamIndex )
{
m_pSource = pSource;
m_streamIndex = streamIndex;
m_pFormatCtx = pSource->getContext();
m_pStreamCtx = m_pFormatCtx->streams[m_streamIndex];
has_vfr = false;
average_fr = false;
if(m_pStreamCtx->codecpar->codec_tag==CFHD_TAG && !pSource->cfg_skip_cfhd){
// use our native thunk instead of internal decoder
if(avcodec_find_decoder(CFHD_ID)){
m_pStreamCtx->codecpar->codec_id = CFHD_ID;
direct_cfhd = true;
}
}
AVCodec* pDecoder = avcodec_find_decoder(m_pStreamCtx->codecpar->codec_id);
if(m_pStreamCtx->codecpar->codec_id==AV_CODEC_ID_VP8){
// on2 vp8 does not extract alpha
AVCodec* pDecoder2 = avcodec_find_decoder_by_name("libvpx");
if(pDecoder2) pDecoder = pDecoder2;
}
if(m_pStreamCtx->codecpar->codec_id==AV_CODEC_ID_VP9){
// on2 vp9 does not extract alpha
AVCodec* pDecoder2 = avcodec_find_decoder_by_name("libvpx-vp9");
if(pDecoder2) pDecoder = pDecoder2;
}
if(!pDecoder){
char buf[AV_FOURCC_MAX_STRING_SIZE];
av_fourcc_make_string(buf,m_pStreamCtx->codecpar->codec_tag);
mContext.mpCallbacks->SetError("FFMPEG: Unsupported codec (%s)", buf);
return -1;
}
m_pCodecCtx = avcodec_alloc_context3(pDecoder);
if(!m_pCodecCtx){
return -1;
}
m_pCodecCtx->flags2 = AV_CODEC_FLAG2_SHOW_ALL;
avcodec_parameters_to_context(m_pCodecCtx,m_pStreamCtx->codecpar);
AVRational r_fr = av_stream_get_r_frame_rate(m_pStreamCtx);
if(m_pStreamCtx->codecpar->field_order>AV_FIELD_PROGRESSIVE){
// interlaced seems to double r_framerate
// example: 00005.MTS
// however other samples do not show this
// example: amanda_excerpt.m2t
// idea of this: r_fr cannot be lower than average
AVRational avg_fr = m_pStreamCtx->avg_frame_rate;
if(int64_t(r_fr.num)*avg_fr.den>=int64_t(avg_fr.num)*r_fr.den*2) r_fr.den *= 2;
}
int sample_count_error = init_duration(r_fr);
if(sample_count_error==-1) return -1;
if(pSource->is_image){
is_image_list = true;
trust_index = false;
sparse_index = false;
keyframe_gap = 1;
fw_seek_threshold = 1;
} else {
if(m_pStreamCtx->nb_index_entries<2){
// try to force loading index
// works for 2017-04-07 08-53-48.flv
int64_t pos = m_pStreamCtx->duration;
if(pos==AV_NOPTS_VALUE) pos = int64_t(sample_count)*time_base.den / time_base.num;
seek_frame(m_pFormatCtx,m_streamIndex,pos,AVSEEK_FLAG_BACKWARD);
seek_frame(m_pFormatCtx,m_streamIndex,AV_SEEK_START,AVSEEK_FLAG_BACKWARD);
}
trust_index = false;
sparse_index = false;
if(m_pStreamCtx->nb_index_entries>2){
// when avi has dropped frames ffmpeg removes these entries from index - find way to avoid this?
AVInputFormat* avi_format = av_find_input_format("avi");
if(m_pFormatCtx->iformat==avi_format){
//sample_count = m_pStreamCtx->nb_index_entries;
//trust_index = true;
trust_index = (sample_count==m_pStreamCtx->nb_index_entries);
} else if(abs(m_pStreamCtx->nb_index_entries - sample_count)<=sample_count_error){
sample_count = m_pStreamCtx->nb_index_entries;
trust_index = true;
} else {
// maybe vfr
// works for 30.mov
// works for device-2017-02-13-115329.mp4
AVRational avg_fr = m_pStreamCtx->avg_frame_rate;
// 0 found in some wmv
if(avg_fr.num!=0){
sample_count_error = init_duration(avg_fr);
if(abs(m_pStreamCtx->nb_index_entries - sample_count)<=sample_count_error){
sample_count = m_pStreamCtx->nb_index_entries;
trust_index = true;
average_fr = true;
} else {
// becomes worse, step back (guess, no sample)
sample_count_error = init_duration(r_fr);
}
}
}
}
if(trust_index){
int64_t exp_dt = time_base.den/time_base.num;
int64_t min_dt = exp_dt;
{for(int i=1; i<m_pStreamCtx->nb_index_entries; i++){
AVIndexEntry& i0 = m_pStreamCtx->index_entries[i-1];
AVIndexEntry& i1 = m_pStreamCtx->index_entries[i];
if(i0.flags & AVINDEX_DISCARD_FRAME) continue;
if(i1.flags & AVINDEX_DISCARD_FRAME) continue;
int64_t dt = i1.timestamp - i0.timestamp;
if(dt<(exp_dt-1) || dt>(exp_dt+1)){
has_vfr = true;
}
if(dt<min_dt){
min_dt = dt;
}
}}
/*
increasing framerate could work but has huge memory impact
if(has_vfr){
trust_index = false;
AVRational tb = m_pStreamCtx->time_base;
AVRational fr;
av_reduce(&fr.num, &fr.den, tb.den, int64_t(tb.num)*min_dt, INT_MAX);
init_duration(fr);
}
*/
}
keyframe_gap = 0;
if(trust_index){
int d = 1;
{for(int i=0; i<m_pStreamCtx->nb_index_entries; i++){
if(m_pStreamCtx->index_entries[i].flags & AVINDEX_KEYFRAME){
if(d>keyframe_gap) keyframe_gap = d;
d = 1;
} else d++;
}}
if(d>keyframe_gap) keyframe_gap = d;
} else if(m_pStreamCtx->nb_index_entries>1){
sparse_index = true;
int p0 = 0;
{for(int i=0; i<m_pStreamCtx->nb_index_entries; i++){
if(m_pStreamCtx->index_entries[i].flags & AVINDEX_KEYFRAME){
int64_t ts = m_pStreamCtx->index_entries[i].timestamp;
ts -= m_pStreamCtx->start_time;
int rndd = time_base.den/2;
int pos = int((ts*time_base.num + rndd) / time_base.den);
int d = pos-p0;
p0 = pos;
if(d>keyframe_gap) keyframe_gap = d;
}
}}
int d = sample_count-p0;
if(d>keyframe_gap) keyframe_gap = d;
}
}
// threading has big negative impact on random access within all-keyframe files
if(allow_copy()){
//m_pCodecCtx->thread_count = 1;
m_pCodecCtx->thread_count = 0;
m_pCodecCtx->thread_type = FF_THREAD_SLICE;
if(config_force_thread)
m_pCodecCtx->thread_type = FF_THREAD_SLICE|FF_THREAD_FRAME;
} else {
m_pCodecCtx->thread_count = 0;
m_pCodecCtx->thread_type = FF_THREAD_SLICE|FF_THREAD_FRAME;
}
fw_seek_threshold = 10;
if(keyframe_gap==1) fw_seek_threshold = 0; // assume seek is free with all-keyframe
m_pCodecCtx->refcounted_frames = 1;
if(avcodec_open2(m_pCodecCtx, pDecoder, 0)<0){
mContext.mpCallbacks->SetError("FFMPEG: Decoder error.");
return -1;
}
if(direct_cfhd){
flip_image = true;
if(trust_index) direct_buffer = true;
cfhd_set_use_am(m_pCodecCtx, !pSource->cfg_skip_cfhd_am);
}
frame = av_frame_alloc();
dead_range_start = -1;
dead_range_end = -1;
first_frame = 0;
last_frame = 0;
used_frames = 0;
if(keyframe_gap>1)
buffer_reserve = keyframe_gap*2;
else
buffer_reserve = 1;
if(buffer_reserve<pSource->cfg_frame_buffers) buffer_reserve = pSource->cfg_frame_buffers;
if(buffer_reserve>sample_count) buffer_reserve = sample_count;
int fa_size = sample_count*sizeof(void*);
frame_array = (BufferPage**)malloc(fa_size);
memset(frame_array,0,fa_size);
int ft_size = sample_count;
frame_type = (char*)malloc(ft_size);
memset(frame_type,' ',ft_size);
init_format();
next_frame = 0;
if(frame_fmt==-1){
//! unable to reserve buffers for unknown format
mContext.mpCallbacks->SetError("FFMPEG: Unknown picture format.");
return -1;
}
MEMORYSTATUSEX ms = {sizeof(MEMORYSTATUSEX)};
GlobalMemoryStatusEx(&ms);
uint64_t max_virtual = ms.ullTotalPhys;
uint64_t gb1 = 0x40000000;
if(max_virtual<2*gb1) max_virtual = 0; else max_virtual -= 2*gb1;
uint64_t max2 = (uint64_t)(config_cache_size*gb1);
if(max2<max_virtual) max_virtual = max2;
uint64_t mem_other = 0;
if(m_pSource->head_segment){
VDFFInputFile* f1 = m_pSource->head_segment;
while(1){
if(!f1->video_source) break;
mem_other += uint64_t(frame_size)*f1->video_source->buffer_reserve;
f1 = f1->next_segment;
if(!f1) break;
}
}
uint64_t mem_size = uint64_t(frame_size)*buffer_reserve;
if(mem_size+mem_other>max_virtual || pSource->cfg_disable_cache){
buffer_reserve = int((max_virtual-mem_other)/frame_size);
if(buffer_reserve<pSource->cfg_frame_buffers || pSource->cfg_disable_cache) buffer_reserve = pSource->cfg_frame_buffers;
mem_size = uint64_t(frame_size)*buffer_reserve;
}
#ifndef _WIN64
uint64_t max_heap = 0x20000000;
if(mem_size+mem_other>max_heap){
mem_size = (mem_size + 0xFFFF) & ~0xFFFF;
mem = CreateFileMapping(INVALID_HANDLE_VALUE,0,PAGE_READWRITE,mem_size>>32,(DWORD)mem_size,0);
if(!mem){
if(buffer_reserve>pSource->cfg_frame_buffers){
buffer_reserve = pSource->cfg_frame_buffers;
mem_size = uint64_t(frame_size)*buffer_reserve;
mem_size = (mem_size + 0xFFFF) & ~0xFFFF;
mem = CreateFileMapping(INVALID_HANDLE_VALUE,0,PAGE_READWRITE,mem_size>>32,(DWORD)mem_size,0);
}
}
if(!mem){
mContext.mpCallbacks->SetErrorOutOfMemory();
return -1;
}
}
#endif
buffer = (BufferPage*)malloc(sizeof(BufferPage)*buffer_reserve);
memset(buffer,0,sizeof(BufferPage)*buffer_reserve);
buffer_count = buffer_reserve;
m_streamInfo.mFlags = 0;
m_streamInfo.mfccHandler = export_avi_fcc(m_pStreamCtx);
m_streamInfo.mInfo.mSampleCount = sample_count;
AVRational ar = av_make_q(1,1);
if(m_pCodecCtx->sample_aspect_ratio.num) ar = m_pCodecCtx->sample_aspect_ratio;
if(m_pStreamCtx->sample_aspect_ratio.num) ar = m_pStreamCtx->sample_aspect_ratio;
AVRational ar1;
av_reduce(&ar1.num, &ar1.den, ar.num, ar.den, INT_MAX);
m_streamInfo.mInfo.mPixelAspectRatio.mNumerator = ar1.num;
m_streamInfo.mInfo.mPixelAspectRatio.mDenominator = ar1.den;
if(allow_copy()){
direct_format_len = sizeof(BITMAPINFOHEADER);
direct_format_len += (m_pCodecCtx->extradata_size+1) & ~1;
direct_format = malloc(direct_format_len);
memset(direct_format, 0, direct_format_len);
BITMAPINFOHEADER* outhdr = (BITMAPINFOHEADER*)direct_format;
outhdr->biSize = sizeof(BITMAPINFOHEADER) + m_pCodecCtx->extradata_size;
outhdr->biWidth = m_pCodecCtx->width;
outhdr->biHeight = m_pCodecCtx->height;
outhdr->biCompression = m_streamInfo.mfccHandler;
memcpy(((uint8*)direct_format)+sizeof(BITMAPINFOHEADER),m_pCodecCtx->extradata,m_pCodecCtx->extradata_size);
}
AVInputFormat* avi_format = av_find_input_format("avi");
if(m_pFormatCtx->iformat==avi_format){
avi_drop_index = true;
memset(frame_type,'D',ft_size);
{for(int i=0; i<m_pStreamCtx->nb_index_entries; i++){
int64_t ts = m_pStreamCtx->index_entries[i].timestamp;
ts -= m_pStreamCtx->start_time;
int rndd = time_base.den/2;
int pos = int((ts*time_base.num + rndd) / time_base.den);
if(pos>=0 && pos<sample_count) frame_type[pos] = ' ';
}}
}
// start_time rarely known before actually decoding, init from here
read_frame(0,true);
// workaround for unspecified delay
// found in MVI_4722.MP4
if(sample_count>1 && !m_pCodecCtx->has_b_frames && possible_delay()){
read_frame(1,false);
if(m_pCodecCtx->has_b_frames){
free_buffers();
avcodec_flush_buffers(m_pCodecCtx);
seek_frame(m_pFormatCtx, m_streamIndex, AV_SEEK_START, AVSEEK_FLAG_BACKWARD);
read_frame(0,true);
}
}
if(frame_fmt!=m_pCodecCtx->pix_fmt){
init_format();
}
return 0;
}
bool VDFFVideoSource::possible_delay()
{
if(is_intra()) return false;
AVCodecID codec_id = m_pStreamCtx->codecpar->codec_id;
const AVCodecDescriptor* desc = avcodec_descriptor_get(codec_id);
if(desc && (desc->props & AV_CODEC_PROP_REORDER)) return true;
return false;
}
bool VDFFVideoSource::is_intra()
{
if(is_image_list) return false;
if(trust_index && keyframe_gap==1) return true;
AVCodecID codec_id = m_pStreamCtx->codecpar->codec_id;
// various intra codecs
switch(codec_id){
case AV_CODEC_ID_CLLC:
case AV_CODEC_ID_DNXHD:
case AV_CODEC_ID_DVVIDEO:
case AV_CODEC_ID_MJPEG:
case AV_CODEC_ID_RAWVIDEO:
case AV_CODEC_ID_HUFFYUV:
case AV_CODEC_ID_FFV1:
case AV_CODEC_ID_PNG:
case AV_CODEC_ID_FFVHUFF:
case AV_CODEC_ID_FRAPS:
case AV_CODEC_ID_JPEG2000:
case AV_CODEC_ID_DIRAC:
case AV_CODEC_ID_V210:
case AV_CODEC_ID_R210:
case AV_CODEC_ID_R10K:
case AV_CODEC_ID_LAGARITH:
case AV_CODEC_ID_PRORES:
case AV_CODEC_ID_UTVIDEO:
case AV_CODEC_ID_V410:
case AV_CODEC_ID_HQ_HQA:
case AV_CODEC_ID_HQX:
case AV_CODEC_ID_SNOW:
case AV_CODEC_ID_CFHD:
case AV_CODEC_ID_MAGICYUV:
case AV_CODEC_ID_SHEERVIDEO:
return true;
}
if(codec_id==CFHD_ID) return true;
const AVCodecDescriptor* desc = avcodec_descriptor_get(codec_id);
if(desc && (desc->props & AV_CODEC_PROP_INTRA_ONLY)) return true;
return false;
}
bool VDFFVideoSource::allow_copy()
{
if(is_intra()) return true;
return false;
}
void VDFFVideoSource::init_format()
{
if(direct_cfhd){
cfhd_set_format(m_pCodecCtx,convertInfo.ext_format);
}
frame_fmt = m_pCodecCtx->pix_fmt;
frame_width = m_pCodecCtx->width;
frame_height = m_pCodecCtx->height;
frame_size = av_image_get_buffer_size(frame_fmt, frame_width, frame_height, line_align);
if(frame_fmt==-1) frame_size = 0;
if(direct_buffer){
// 6 px per 16 bytes, 128 byte aligned
int row = (frame_width+47)/48*128;
int frame_size2 = row*frame_height;
if(frame_size2>frame_size) frame_size = frame_size2;
}
free_buffers();
{for(int i=0; i<buffer_count; i++) dealloc_page(&buffer[i]); }
}
void VDXAPIENTRY VDFFVideoSource::GetStreamSourceInfo(VDXStreamSourceInfo& srcInfo)
{
srcInfo = m_streamInfo.mInfo;
}
void VDXAPIENTRY VDFFVideoSource::GetStreamSourceInfoV3(VDXStreamSourceInfoV3& srcInfo)
{
srcInfo = m_streamInfo;
}
void VDXAPIENTRY VDFFVideoSource::ApplyStreamMode(uint32 flags)
{
if((flags & kStreamModeDirectCopy)!=0 && !QueryStreamMode(kStreamModeDirectCopy)) return;
bool copy_mode = false;
bool decode_mode = false;
bool cache_mode = true;
if(flags & kStreamModeDirectCopy) copy_mode = true;
if(flags & kStreamModeUncompress) decode_mode = true;
if(flags & kStreamModePlayForward) cache_mode = false;
setCopyMode(copy_mode);
setDecodeMode(decode_mode);
setCacheMode(cache_mode);
if(m_pSource->next_segment) m_pSource->next_segment->video_source->ApplyStreamMode(flags);
}
bool VDXAPIENTRY VDFFVideoSource::QueryStreamMode(uint32 flags)
{
if(flags==kStreamModeDirectCopy){
if(direct_format_len==0) return false;
if(m_pSource->head_segment){
VDFFVideoSource* head = m_pSource->head_segment->video_source;
if(direct_format_len!=head->direct_format_len) return false;
if(memcmp(direct_format,head->direct_format,direct_format_len)!=0) return false;
}
if(m_pSource->next_segment && !m_pSource->next_segment->video_source->QueryStreamMode(flags)) return false;
return true;
}
return false;
}
const void *VDFFVideoSource::GetDirectFormat()
{
return copy_mode ? direct_format : 0;
}
int VDFFVideoSource::GetDirectFormatLen()
{
return copy_mode ? direct_format_len: 0;
}
void VDFFVideoSource::setCopyMode(bool v)
{
if(copy_mode==v) return;
copy_mode = v;
if(v){
free_buffers();
next_frame = -1;
last_seek_frame = -1;
enable_prefetch = false;
}
av_packet_unref(©_pkt);
}
void VDFFVideoSource::setDecodeMode(bool v)
{
if(decode_mode==v) return;
decode_mode = v;
if(v){
// must begin from IDR
next_frame = -1;
last_seek_frame = -1;
enable_prefetch = false;
}
}
void VDFFVideoSource::setCacheMode(bool v)
{
small_cache_mode = !v;
if(!v){
enable_prefetch = false;
int buffer_max = m_pSource->cfg_frame_buffers;
// 1 required +1 to handle dups
// and somewhere 10 to soften display triple-buffering, filter process-ahead or whatever
// (not strictly required but helps to recover from mode switching)
if(buffer_max<16) buffer_max = 16;
if(buffer_max>buffer_count) buffer_max = buffer_count;
small_buffer_count = buffer_max;
if(mem && used_frames>buffer_max){
free_buffers();
CloseHandle(mem);
int64_t mem_size = uint64_t(frame_size)*buffer_reserve;
mem_size = (mem_size + 0xFFFF) & ~0xFFFF;
mem = CreateFileMapping(INVALID_HANDLE_VALUE,0,PAGE_READWRITE,mem_size>>32,(DWORD)mem_size,0);
} else {
int anchor = next_frame-1;
while(1){
BufferPage* p = remove_page(anchor,false,true);
if(!p) break;
if(used_frames>buffer_max) dealloc_page(p);
}
while(used_frames>buffer_max){
BufferPage* p = remove_page(anchor);
dealloc_page(p);
}
}
}
}
IVDXStreamSource::ErrorMode VDFFVideoSource::GetDecodeErrorMode()
{
return errorMode;
}
void VDFFVideoSource::SetDecodeErrorMode(IVDXStreamSource::ErrorMode mode)
{
errorMode = mode;
}
bool VDFFVideoSource::IsDecodeErrorModeSupported(IVDXStreamSource::ErrorMode mode)
{
return mode == kErrorModeReportAll || mode == kErrorModeDecodeAnyway;
}
void VDFFVideoSource::GetVideoSourceInfo(VDXVideoSourceInfo& info)
{
info.mFlags = VDXVideoSourceInfo::kFlagSyncDecode;
info.mWidth = m_pCodecCtx->width;
info.mHeight = m_pCodecCtx->height;
info.mDecoderModel = VDXVideoSourceInfo::kDecoderModelCustom;
}
bool VDFFVideoSource::CreateVideoDecoder(IVDXVideoDecoder **ppDecoder)
{
this->AddRef();
*ppDecoder = this;
return true;
}
bool VDFFVideoSource::CreateVideoDecoderModel(IVDXVideoDecoderModel **ppModel)
{
this->AddRef();
*ppModel = this;
return true;
}
void VDFFVideoSource::GetSampleInfo(sint64 sample, VDXVideoFrameInfo& frameInfo)
{
if(sample>=sample_count){
VDFFVideoSource* v1 = 0;
if(m_pSource->next_segment) v1 = m_pSource->next_segment->video_source;
v1->GetSampleInfo(sample-sample_count,frameInfo);
return;
}
frameInfo.mBytePosition = -1;
frameInfo.mFrameType = kVDXVFT_Independent;
if(keyframe_gap==1)
frameInfo.mTypeChar = 'K';
else if(IsKey(sample))
frameInfo.mTypeChar = 'K';
else
frameInfo.mTypeChar = frame_type[sample];
}
bool VDFFVideoSource::IsKey(int64_t sample)
{
if(sample>=sample_count){
VDFFVideoSource* v1 = 0;
if(m_pSource->next_segment) v1 = m_pSource->next_segment->video_source;
return v1->IsKey(sample-sample_count);
}
if(is_image_list) return true;
if(trust_index){
return (m_pStreamCtx->index_entries[sample].flags & AVINDEX_KEYFRAME)!=0;
}
if(sparse_index){
int64_t pos;
int x = calc_sparse_key(sample,pos);
return x==sample;
}
return false;
}
int64_t VDFFVideoSource::GetFrameNumberForSample(int64_t sample_num)
{
return sample_num;
}
int64_t VDFFVideoSource::GetSampleNumberForFrame(int64_t display_num)
{
return display_num;
}
int64_t VDFFVideoSource::GetRealFrame(int64_t display_num)
{
return display_num;
}
int64_t VDFFVideoSource::GetSampleBytePosition(int64_t sample_num)
{
return -1;
}
void VDFFVideoSource::Reset()
{
}
void VDFFVideoSource::SetDesiredFrame(int64_t frame_num)
{
desired_frame = frame_num;
required_count = 1;
}
int64_t VDFFVideoSource::GetNextRequiredSample(bool& is_preroll)
{
is_preroll = false;
return required_count ? desired_frame : -1;
}
int VDFFVideoSource::GetRequiredCount()
{
return required_count;
}
//////////////////////////////////////////////////////////////////////////
//Decoder
//////////////////////////////////////////////////////////////////////////\
const void* VDFFVideoSource::DecodeFrame(const void* inputBuffer, uint32_t data_len, bool is_preroll, int64_t streamFrame, int64_t targetFrame)
{
m_pixmap_frame = int(targetFrame);
m_pixmap_info.frame_num = -1;
if(targetFrame>=sample_count){
VDFFVideoSource* v1 = 0;
if(m_pSource->next_segment) v1 = m_pSource->next_segment->video_source;
if(!v1) return 0;
return v1->DecodeFrame(inputBuffer,data_len,is_preroll,streamFrame,targetFrame-sample_count);
}
if(is_preroll) return 0;
if(convertInfo.out_garbage){
mContext.mpCallbacks->SetError("Segment has incompatible format: try changing decode format to RGBA");
return 0;
}
BufferPage* page = frame_array[targetFrame];
if(!page){
// this now must be impossible with help of kFlagSyncDecode
mContext.mpCallbacks->SetError("Cache overflow: set \"Performance \\ Video buffering\" to 32 or less");
return 0;
}
if(page->error==BufferPage::err_badformat){
mContext.mpCallbacks->SetError("Frame format is incompatible");
return 0;
}
m_pixmap_info.frame_num = targetFrame;
open_read(page);
uint8_t* src = align_buf(page->p);
if(convertInfo.direct_copy){
set_pixmap_layout(src);
return src;
} else {
int w = m_pixmap.w;
int h = m_pixmap.h;
AVFrame pic = {0};
av_image_fill_arrays(pic.data, pic.linesize, src, frame_fmt, w, h, line_align);
if(flip_image){
pic.data[0] = pic.data[0] + pic.linesize[0]*(h-1);
pic.linesize[0] = -pic.linesize[0];
}
AVFrame pic2 = {0};
pic2.data[0] = (uint8_t*)m_pixmap.data;
pic2.data[1] = (uint8_t*)m_pixmap.data2;
pic2.data[2] = (uint8_t*)m_pixmap.data3;
pic2.data[3] = (uint8_t*)m_pixmap.data4;
pic2.linesize[0] = int(m_pixmap.pitch);
pic2.linesize[1] = int(m_pixmap.pitch2);
pic2.linesize[2] = int(m_pixmap.pitch3);
pic2.linesize[3] = int(m_pixmap.pitch4);
sws_scale(m_pSwsCtx, pic.data, pic.linesize, 0, h, pic2.data, pic2.linesize);
return align_buf(m_pixmap_data);
}
}
uint32_t VDFFVideoSource::GetDecodePadding()
{
return 0;
}
bool VDFFVideoSource::IsFrameBufferValid()
{
if(m_pixmap_data) return true;
if(m_pixmap_frame==-1) return false;
if(m_pixmap_frame>=sample_count){
VDFFVideoSource* v1 = 0;
if(m_pSource->next_segment) v1 = m_pSource->next_segment->video_source;
if(!v1) return 0;
return v1->IsFrameBufferValid();
}
if(frame_array[m_pixmap_frame]) return true;
return false;
}
const VDXPixmap& VDFFVideoSource::GetFrameBuffer()
{
if(m_pixmap_frame>=sample_count){
VDFFVideoSource* v1 = 0;
if(m_pSource->next_segment) v1 = m_pSource->next_segment->video_source;
return v1->GetFrameBuffer();
}
return m_pixmap;
}
const FilterModPixmapInfo& VDFFVideoSource::GetFrameBufferInfo()
{
if(m_pixmap_frame>=sample_count){
VDFFVideoSource* v1 = 0;
if(m_pSource->next_segment) v1 = m_pSource->next_segment->video_source;
return v1->GetFrameBufferInfo();
}
return m_pixmap_info;
}
const void* VDFFVideoSource::GetFrameBufferBase()
{
if(m_pixmap_data) return align_buf(m_pixmap_data);
if(m_pixmap_frame==-1) return 0;
if(m_pixmap_frame>=sample_count){
VDFFVideoSource* v1 = 0;
if(m_pSource->next_segment) v1 = m_pSource->next_segment->video_source;
if(!v1) return 0;
return v1->GetFrameBufferBase();
}
return align_buf(frame_array[m_pixmap_frame]->p);
}
bool VDFFVideoSource::SetTargetFormat(int format, bool useDIBAlignment)
{
nsVDXPixmap::VDXPixmapFormat opt_format = (nsVDXPixmap::VDXPixmapFormat)format;
bool r = SetTargetFormat(opt_format,useDIBAlignment,0);
if(!r && opt_format!=0) r = SetTargetFormat(nsVDXPixmap::kPixFormat_Null,useDIBAlignment,0);
// note: compatibility between segments is enforced in SetTargetFormat
VDFFInputFile* f1 = m_pSource;
while(1){
f1 = f1->next_segment;
if(!f1) break;
if(f1->video_source){
bool r1 = f1->video_source->SetTargetFormat(opt_format,useDIBAlignment,this);
if(!r1 && opt_format!=0) f1->video_source->SetTargetFormat(nsVDXPixmap::kPixFormat_Null,useDIBAlignment,this);
}
}
return r;
}
bool VDFFVideoSource::SetTargetFormat(nsVDXPixmap::VDXPixmapFormat opt_format, bool useDIBAlignment,VDFFVideoSource* head)
{
// this function will select one of the modes:
// 1) XRGB - works slow
// 2) convert to arbitrary rgb
// 3) direct decoded format - usually some sort of yuv
// 4) upsample arbitrary yuv to 444
// yuv->rgb has chance to apply correct source color space matrix, range etc
// but! currently I notice huge color upsampling error
// which is best default? rgb afraid to use; sws can do either fast-bad or slow-good, but vd can do good-fast-enough
using namespace nsVDXPixmap;
bool default_rgb = false;
bool fast_rgb = false;
if(convertInfo.ext_format && opt_format==kPixFormat_Null){
convertInfo.ext_format = kPixFormat_Null;
init_format();
}
VDXPixmapFormat base_format = kPixFormat_Null;
VDXPixmapFormat ext_format = kPixFormat_Null;
VDXPixmapFormat trigger = kPixFormat_Null;
VDXPixmapFormat perfect_format = kPixFormat_Null;
AVPixelFormat perfect_av_fmt = frame_fmt;
AVPixelFormat src_fmt = frame_fmt;
bool perfect_bitexact = false;
bool skip_colorspace = false;
convertInfo.req_format = opt_format;
convertInfo.req_dib = useDIBAlignment;
convertInfo.direct_copy = false;