-
Notifications
You must be signed in to change notification settings - Fork 117
/
ADM_edVideoCopy.cpp
1723 lines (1627 loc) · 62.6 KB
/
ADM_edVideoCopy.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
/***************************************************************************
\file ADM_edVideoCopy.cpp
\brief handle direct stream copy for video
\author mean (c) 2002/2009 fixounet@free.fr
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include "ADM_cpp.h"
#include <math.h>
#include <climits>
#include "ADM_default.h"
#include "ADM_edit.hxx"
#include "ADM_vidMisc.h"
#include "ADM_videoInfoExtractor.h"
#include "ADM_h264_tag.h"
#if 0
#define aprintf printf
#else
#define aprintf(...) {}// printf
#endif
static bool checkCodec(aviInfo *first,aviInfo *second)
{
bool match=false;
#define XCHECK(x) if(!match && x(first->fcc) && x(second->fcc)) { ADM_info("Codecs identified by %s() as matching\n",#x); match=true; }
XCHECK(isH264Compatible)
XCHECK(isH265Compatible)
XCHECK(isMpeg4Compatible)
XCHECK(isMpeg12Compatible)
XCHECK(isVC1Compatible)
XCHECK(isVP9Compatible)
XCHECK(isVP6Compatible)
XCHECK(isMSMpeg4Compatible)
XCHECK(isDVCompatible)
// catch fourcc values not covered by above
if(!match && first->fcc == second->fcc)
match=true;
return match;
}
static bool boundsCheck(vidHeader *hdr, ADMCompressedImage *img, uint32_t frame, uint32_t max)
{
img->dataLength=0;
if(!hdr->getFrameSize(frame,&(img->dataLength)) || !img->dataLength)
{
ADM_warning("Cannot get valid length for frame %u\n",frame);
return false;
}
if(img->dataLength > max)
{
ADM_warning("Length of frame %u out of bounds: %u vs %u\n", frame, img->dataLength, max);
return false;
}
return true;
}
static bool getH264SPSInfo(_VIDEOS *vid,ADM_SPSInfo *sps)
{
if(!vid)
return false;
vidHeader *demuxer=vid->_aviheader;
if(!demuxer)
return false;
if(!sps)
return false;
// Do we have a cached copy?
if(vid->infoCacheSize==sizeof(ADM_SPSInfo) && vid->infoCache)
{
memcpy(sps,vid->infoCache,sizeof(ADM_SPSInfo));
return true;
}
bool gotSps=false;
uint8_t *buffer=NULL;
uint8_t *extra;
uint32_t extraLen=0;
demuxer->getExtraHeaderData(&extraLen,&extra);
if(!extraLen) // AnnexB
{
// Allocate memory to hold compressed frame
ADMCompressedImage img;
#define MAX_FRAME_LENGTH (1920*1080*3) // ~7 MiB, should be enough even for 4K
if(!boundsCheck(demuxer,&img,0,MAX_FRAME_LENGTH))
{
ADM_warning("First frame of video has invalid length.\n");
goto _the_end;
}
buffer=new uint8_t[MAX_FRAME_LENGTH];
img.data=buffer;
if(!demuxer->getFrame(0,&img))
{
ADM_warning("Unable to get the first frame of video\n");
goto _the_end;
}
#define MAX_NALU_TO_CHECK 4
static NALU_descriptor desc[MAX_NALU_TO_CHECK];
int nbNalu=ADM_splitNalu(img.data, img.data+img.dataLength, MAX_NALU_TO_CHECK, desc);
int spsIndex=ADM_findNalu(NAL_SPS,nbNalu,desc);
NALU_descriptor *d=desc;
if(spsIndex<0)
goto _the_end;
d+=spsIndex;
if(extractSPSInfo(d->start, d->size, sps))
{ // Cache raw SPS data
if(vid->paramCache)
delete [] vid->paramCache;
vid->paramCacheSize=d->size+1;
vid->paramCache=new uint8_t[vid->paramCacheSize];
uint8_t *p=vid->paramCache;
p[0]=d->nalu;
memcpy(p+1, d->start, d->size);
gotSps=true;
}
}else
{
gotSps=extractSPSInfo(extra,extraLen,sps);
if(gotSps && extra[5] == 0xe1 /* We support only a single one SPS */ )
{ // Cache raw SPS data
vid->paramCacheSize=(extra[6] << 8) + extra[7];
if(vid->paramCacheSize && vid->paramCacheSize+8<=extraLen) // 8 bytes AVCC header + SPS
{
vid->paramCache=new uint8_t[vid->paramCacheSize];
memcpy(vid->paramCache, extra+8, vid->paramCacheSize);
}
}
}
if(!gotSps)
goto _the_end;
// Store the decoded SPS info in the cache
vid->infoCacheSize=sizeof(ADM_SPSInfo);
vid->infoCache=new uint8_t[vid->infoCacheSize]; // will be destroyed with the video
memcpy(vid->infoCache,sps,sizeof(ADM_SPSInfo));
_the_end:
if(buffer) delete [] buffer;
buffer=NULL;
return gotSps;
}
/**
\fn getH265SPSInfo
*/
static bool getH265SPSInfo(_VIDEOS *vid, ADM_SPSinfoH265 *sps)
{
if(!vid)
return false;
vidHeader *demuxer=vid->_aviheader;
if(!demuxer)
return false;
if(!sps)
return false;
// Do we have a cached copy?
uint32_t spsSize=sizeof(ADM_SPSinfoH265);
if(vid->infoCacheSize==spsSize && vid->infoCache)
{
memcpy(sps,vid->infoCache,spsSize);
return true;
}
// Nope, determine stream type
bool gotSps=false;
uint8_t *buffer=NULL;
uint8_t *extra;
uint32_t extraLen=0;
demuxer->getExtraHeaderData(&extraLen,&extra);
if(!extraLen) // AnnexB
{
// Allocate memory to hold compressed frame
ADMCompressedImage img;
if(!boundsCheck(demuxer,&img,0,MAX_FRAME_LENGTH))
{
ADM_warning("First frame of video has invalid length.\n");
goto _the_end_hevc;
}
buffer=new uint8_t[MAX_FRAME_LENGTH];
img.data=buffer;
if(!demuxer->getFrame(0,&img))
{
ADM_warning("Unable to get the first frame of video\n");
goto _the_end_hevc;
}
gotSps=extractSPSInfoH265(img.data,img.dataLength,sps);
}else
{
gotSps=extractSPSInfoH265(extra,extraLen,sps);
}
if(!gotSps)
goto _the_end_hevc;
// Store the decoded SPS info in the cache
vid->infoCacheSize=spsSize;
vid->infoCache=new uint8_t[vid->infoCacheSize]; // will be destroyed with the video
memcpy(vid->infoCache,sps,vid->infoCacheSize);
_the_end_hevc:
if(buffer) delete [] buffer;
buffer=NULL;
return gotSps;
}
/**
\fn findLastFrameBeforeSwitch
\brief Identify the last frame in stream order and last displayed frame before segment switch
*/
bool ADM_Composer::findLastFrameBeforeSwitch(uint32_t segNo, uint32_t *lastFrame, uint32_t *maxPtsFrame, uint64_t *maxPts)
{
if(segNo>=_segments.getNbSegments())
{
ADM_error("Requested segment number %d out of range!\n",segNo);
return false;
}
_SEGMENT *seg=_segments.getSegment(segNo);
ADM_assert(seg);
_VIDEOS *vid=_segments.getRefVideo(seg->_reference);
ADM_assert(vid);
vidHeader *demuxer=vid->_aviheader;
ADM_assert(demuxer);
// Identify the last frame before segment switch
int frame=0;
uint64_t tail = seg->_refStartTimeUs + seg->_durationUs;
if(false==getFrameNumFromPtsOrBefore(vid,tail-1,frame))
{
ADM_warning("Cannot identify the last frame in display order for segment %d\n",segNo);
return false;
}
// Check restrictions imposed by PTS delay and early B-frames in the next segment
uint64_t limitDts,limitPts;
limitDts=limitPts=tail;
if(segNo+1 < _segments.getNbSegments())
{
_SEGMENT *nextSeg=_segments.getSegment(segNo+1);
ADM_assert(nextSeg);
uint64_t delta=0;
if(nextSeg->_refStartTimeUs > nextSeg->_refStartDts)
delta = nextSeg->_refStartTimeUs - nextSeg->_refStartDts;
if(delta<limitDts)
limitDts-=delta;
uint32_t dlay=0;
if(getOpenGopDelayForSegment(segNo+1,0,&dlay) && (uint64_t)dlay < limitPts)
limitPts-=dlay;
}
int maxFrame=frame;
#define MAX_REF_FRAMES_FIELDS 32 // the highest possible nb of references in a field-encoded H.264 stream
// FIXME In theory, 32 may be not enough as we may encounter an unknown number of early B-frames
// while maxFrame may be far past the first frame of the next segment if it uses the same ref video.
frame = (frame > MAX_REF_FRAMES_FIELDS)? frame - MAX_REF_FRAMES_FIELDS : 0;
*lastFrame=frame;
// Now search the frame with max pts before segment switch
*maxPts=0;
*maxPtsFrame=-1;
uint64_t lastPts=0, lastDts=ADM_NO_PTS;
while(frame<=maxFrame)
{
uint64_t pts,dts;
if(!demuxer->getPtsDts(frame,&pts,&dts))
break;
if(pts!=ADM_NO_PTS && pts >= limitPts)
break;
if(dts!=ADM_NO_PTS)
{
if(lastDts!=ADM_NO_PTS && lastDts>=dts)
ADM_warning("Frame %d DTS delta %" PRId64" ms\n",frame,
((int64_t)lastDts-(int64_t)dts)/1000); // Should we rather bail out?
lastDts=dts;
}
else if(lastDts!=ADM_NO_PTS)
lastDts+=vid->timeIncrementInUs;
if(lastDts!=ADM_NO_PTS && lastDts >= limitDts)
break;
if(pts!=ADM_NO_PTS)
lastPts=pts;
if(lastPts>*maxPts)
{
*maxPts=lastPts;
*maxPtsFrame=frame;
}
*lastFrame=frame;
frame++;
}
return true;
}
/**
\fn checkSegmentStartsOnIntra
\brief In copy mode, if the cuts are not on intra we will run into trouble :
* We include skipped ref frames: we will have DTS going back error
* We skip them, we have borked video at cut points due to missing ref frames
*/
ADM_cutPointType ADM_Composer::checkSegmentStartsOnIntra(uint32_t segNo)
{
if(segNo>=_segments.getNbSegments())
{
ADM_error("Requested segment number %d out of range!\n",segNo);
return ADM_EDITOR_CUT_POINT_KEY;
}
_SEGMENT *seg=_segments.getSegment(segNo);
_VIDEOS *vid=_segments.getRefVideo(seg->_reference);
vidHeader *demuxer=vid->_aviheader;
uint32_t oldSeg=_currentSegment;
uint32_t oldFrame=vid->lastSentFrame;
uint32_t refNo=seg->_reference;
uint64_t refstart=(seg->_refStartTimeUs > vid->firstFramePts)? seg->_refStartTimeUs : vid->firstFramePts;
int frame=0;
uint8_t *buffer=NULL;
uint8_t *spsBuf1=NULL;
uint8_t *spsBuf2=NULL;
ADM_cutPointType cut=ADM_EDITOR_CUT_POINT_UNCHECKED;
#define BOWOUT if(buffer) { delete [] buffer; buffer=NULL; } \
if(spsBuf1) { delete [] spsBuf1; spsBuf1=NULL; } \
if(spsBuf2) { delete [] spsBuf2; spsBuf2=NULL; } \
_currentSegment=oldSeg; vid->lastSentFrame=oldFrame; \
return cut;
if(false==switchToSegment(segNo,true))
{
BOWOUT
}
if(false==getFrameNumFromPtsOrBefore(vid,refstart,frame))
{
BOWOUT
}
// Cursorily check that codec matches if the ref video is not the first one.
aviInfo info;
demuxer->getVideoInfo(&info);
if(refNo)
{
aviInfo inf0;
getVideoInfo(&inf0);
if(!checkCodec(&info,&inf0))
{
ADM_error("Codec doesn't match the one of the first ref video. This is currently unsupported.\n");
cut=ADM_EDITOR_CUT_POINT_MISMATCH;
BOWOUT
}
}
uint32_t flags=0;
uint64_t pts,dts;
demuxer->getPtsDts(frame,&pts,&dts);
// After a seg switch we are at the keyframe before or equal to where we want to go
// if the dts do not match, it means we went back too much
// When re-encoding, it's not a problem, it is when copying.
ADM_info("seg %d: ref %d, refDTS=%" PRIu64"\n",segNo,seg->_reference,seg->_refStartDts);
ADM_info("seg %d: ref %d, imgDTS=%" PRIu64"\n",segNo,seg->_reference,dts);
if(!seg->_refStartDts && !seg->_reference)
{
ADM_info("Ignoring first seg (unreliable DTS)\n");
}else if(dts!=ADM_NO_PTS && seg->_refStartDts!=ADM_NO_PTS && dts!=seg->_refStartDts)
{
ADM_warning("Segment %d does not start on a known DTS (%" PRIu64" us = %s)\n",segNo,dts,ADM_us2plain(dts));
ADM_warning("expected: %" PRIu64" us = %s\n",seg->_refStartDts,ADM_us2plain(seg->_refStartDts));
cut=ADM_EDITOR_CUT_POINT_NON_KEY; // ??
BOWOUT
}
// DTS check passed, now check flags
demuxer->getFlags(frame,&flags);
if(!(flags & AVI_KEY_FRAME))
{
ADM_warning("Segment %d does not start on a keyframe (time in ref %s)\n",segNo,ADM_us2plain(pts));
cut=ADM_EDITOR_CUT_POINT_NON_KEY;
BOWOUT
}
// The frame is marked as keyframe
if(!segNo) // Not a cut point
{
cut=ADM_EDITOR_CUT_POINT_KEY;
BOWOUT
}
// It is a cut, perform codec-specific checks
if(isH264Compatible(info.fcc))
{
int poc1,maxpoc1,poc2,minpoc2;
// It is H.264, check deeper. The keyframe may be a non-IDR random access point.
// If picture order count after a cut is going back, at least FFmpeg-based players
// like VLC and mpv may get stuck until POC is greater than before the cut point.
// Get SPS to be able to decode the slice header
ADM_SPSInfo sps;
if(!getH264SPSInfo(vid,&sps))
{
ADM_warning("Cannot retrieve SPS info.\n");
BOWOUT
}
// Determine stream type
bool AnnexB=false;
uint8_t *extra;
uint32_t extraLen=0;
uint32_t nalSize=0;
demuxer->getExtraHeaderData(&extraLen,&extra);
if(!extraLen)
AnnexB=true;
else
nalSize=ADM_getNalSizeH264(extra,extraLen);
// Allocate memory to hold compressed frame
ADMCompressedImage img;
#define CHECK_FRAME(x) if(!boundsCheck(demuxer,&img,x,MAX_FRAME_LENGTH)) \
{ \
ADM_warning("Length of frame %d in ref %d, segment %d out of bounds or invalid.\n",x,seg->_reference,segNo); \
BOWOUT \
}
CHECK_FRAME(frame)
buffer=new uint8_t[MAX_FRAME_LENGTH];
img.data=buffer;
// We have SPS, now get the frame we are interested in.
if(!demuxer->getFrame(frame,&img))
{
ADM_warning("Unable to get frame %d in ref %d, segment %d\n",frame,seg->_reference,segNo);
BOWOUT
}
// Do we have in-band SPS?
ADM_info("Checking for in-band SPS...\n");
bool match=true;
uint32_t spsLen1,spsLen2=0;
// Allocate memory to hold copy of raw SPS data
if(!spsBuf2)
spsBuf2=new uint8_t[MAX_H264_SPS_SIZE];
memset(spsBuf2,0,MAX_H264_SPS_SIZE);
if(AnnexB)
spsLen2=getRawH264SPS_startCode(img.data, img.dataLength, spsBuf2, MAX_H264_SPS_SIZE);
else
spsLen2=getRawH264SPS(img.data, img.dataLength, nalSize, spsBuf2, MAX_H264_SPS_SIZE);
// If we have in-band SPS, the global one doesn't matter. The check below is purely informative.
if(spsLen2)
{
//mixDump(vid->paramCache, vid->paramCacheSize);
//mixDump(spsBuf, spsLen);
if(memcmp(vid->paramCache, spsBuf2, (spsLen2 > vid->paramCacheSize)? vid->paramCacheSize : spsLen2))
{
ADM_warning("SPS mismatch? Checking deeper...\n");
ADM_SPSInfo tmpinfo;
if(extractSPSInfoFromData(spsBuf2, spsLen2, &tmpinfo))
{ // Update SPS info
#define MATCH(x) if(sps.x != tmpinfo.x) { ADM_warning("%s value does not match.\n",#x); sps.x = tmpinfo.x; match=false; }
MATCH(width)
MATCH(height)
MATCH(hasPocInfo)
MATCH(log2MaxFrameNum)
MATCH(log2MaxPocLsb)
MATCH(frameMbsOnlyFlag)
MATCH(refFrames)
if(!match)
ADM_warning("Codec parameters at frame %d don't match initial ones, expect problems.\n",frame);
}
}
}
poc2=-1; // POC of the first frame after the cut
#define NO_RECOVERY_INFO 0xFF
uint32_t recoveryDistance=NO_RECOVERY_INFO;
bool outcome=false;
if(AnnexB)
outcome=extractH264FrameType_startCode(img.data, img.dataLength, &(img.flags), &poc2, &sps, &recoveryDistance);
else
outcome=extractH264FrameType(img.data, img.dataLength, nalSize, &(img.flags), &poc2, &sps, &recoveryDistance);
if(!outcome)
{
ADM_warning("Cannot get H.264 frame type and Picture Order Count Least Significant Bits value.\n");
BOWOUT
}
/* Even if the frame is an IDR, we should check for SPS mismatch in case
adjacent segments reference different videos. If the result is OK, we
will skip POC check. */
bool gotIdr = (img.flags & AVI_KEY_FRAME) && (img.flags & AVI_IDR_FRAME);
/* Now we need to calculate the minimum POC among the early B-frames
following the first frame of the segment. While not relevant for
the effect of being "stuck", a POC smaller than the maximum POC
before the cut point at an non-IDR frame will result in considerable
artifacts, dropped frames, stutter, flicker and such. */
minpoc2=-1;
uint32_t delay;
int earliest;
if(getOpenGopDelayForSegment(segNo,0,&delay,&earliest) && earliest>0)
{
CHECK_FRAME(earliest)
if(demuxer->getFrame(earliest,&img))
{
outcome=false;
if(AnnexB)
outcome=extractH264FrameType_startCode(img.data, img.dataLength, &(img.flags), &minpoc2, &sps, NULL);
else
outcome=extractH264FrameType(img.data, img.dataLength, nalSize, &(img.flags), &minpoc2, &sps, NULL);
if(!outcome)
ADM_warning("Cannot get H.264 frame type and Picture Order Count Least Significant Bits value.\n");
}else
{
ADM_warning("Unable to get frame %d in ref %d, segment %d\n",earliest,seg->_reference,segNo);
}
}else
{
earliest=frame;
}
if(minpoc2!=-1)
ADM_info("Segment %u minimum POC LSB = %d at frame %d\n",segNo,minpoc2,earliest);
// We are done with this segment, restore the last sent frame
vid->lastSentFrame=oldFrame;
uint8_t *nextSegParamCache=vid->paramCache;
uint32_t nextSegParamCacheSize=vid->paramCacheSize;
// Check the preceding segment
ADM_info("Getting previous segment, current segment number: %d\n",segNo);
ADM_assert(segNo>0);
segNo--;
seg=_segments.getSegment(segNo);
vid=_segments.getRefVideo(seg->_reference);
demuxer=vid->_aviheader;
oldFrame=vid->lastSentFrame;
if(false==switchToSegment(segNo,true))
{
ADM_warning("Cannot check the previous segment %d\n",segNo);
BOWOUT
}
ADM_info("Switched to segment %d\n",segNo);
// Same ref video?
if(seg->_reference==refNo)
{
// Marked as IDR? Ignore recovery.
if((img.flags & AVI_KEY_FRAME) && (img.flags & AVI_IDR_FRAME))
{
ADM_info("IDR verified and same ref video, the cut point is fine.\n");
cut=ADM_EDITOR_CUT_POINT_KEY;
BOWOUT
}
// Recovery point and no POC? Don't bother to perform further checks.
if(!recoveryDistance && poc2==-1)
{
ADM_warning("No POC to compare with, only POC explicitely set in the slice header is supported.\n");
cut=ADM_EDITOR_CUT_POINT_KEY; // ??
BOWOUT
}
// Check for in-band SPS
// Identify the last keyframe of the segment. If in-band SPS is present, it will be there.
if(false==getFrameNumFromPtsOrBefore(vid, seg->_refStartTimeUs+seg->_durationUs-1, frame))
{
ADM_warning("Cannot identify the last frame in display order for segment %d\n",segNo);
BOWOUT
}
flags=0;
demuxer->getFlags(frame,&flags);
while(frame>0)
{
if(flags & AVI_KEY_FRAME) break;
demuxer->getFlags(--frame,&flags);
}
// Retrieve this keyframe
CHECK_FRAME(frame)
if(!demuxer->getFrame(frame,&img))
{
ADM_warning("Unable to get frame %d in ref %d, segment %d\n",frame,seg->_reference,segNo);
BOWOUT
}
spsLen1=0;
// Allocate another buffer to hold copy of raw SPS data
if(!spsBuf1)
spsBuf1=new uint8_t[MAX_H264_SPS_SIZE];
memset(spsBuf1,0,MAX_H264_SPS_SIZE);
if(AnnexB)
spsLen1=getRawH264SPS_startCode(img.data, img.dataLength, spsBuf1, MAX_H264_SPS_SIZE);
else
spsLen1=getRawH264SPS(img.data, img.dataLength, nalSize, spsBuf1, MAX_H264_SPS_SIZE);
if(spsLen1)
{ /* If the next segment doesn't have in-band SPS but this one does,
we are in trouble as we can't be sure that we parsed the slice header
using a valid SPS info. The least harmful thing to do is to check that
in-band SPS matches the global one and to bail out if it does not. */
uint8_t *sbuf=vid->paramCache;
uint32_t slen=vid->paramCacheSize;
if(spsLen2 && spsBuf2)
{
sbuf=spsBuf2;
slen=spsLen2;
}
if(memcmp(spsBuf1, sbuf, (spsLen1 > slen)? slen : spsLen1))
{
ADM_warning("In-band SPS does not match the global one? Checking deeper...\n");
ADM_SPSInfo tmpinfo;
if(extractSPSInfoFromData(spsBuf1, spsLen1, &tmpinfo))
{ // Update SPS info used to parse slice header later
match=true;
MATCH(width)
MATCH(height)
MATCH(hasPocInfo)
MATCH(log2MaxFrameNum)
MATCH(log2MaxPocLsb)
MATCH(frameMbsOnlyFlag)
MATCH(refFrames)
if(!match && !spsLen2)
{
ADM_warning("Appended incompatible streams possible, aborting check.\n");
BOWOUT
}
}
}
}
}else
{
// Not the same video. Does the codec match?
demuxer->getVideoInfo(&info);
if(!isH264Compatible(info.fcc))
{
ADM_error("Codec mismatch!\n");
cut=ADM_EDITOR_CUT_POINT_MISMATCH;
BOWOUT
}
// Check that stream types match
extraLen=0;
demuxer->getExtraHeaderData(&extraLen,&extra);
if(!extraLen != AnnexB) // FIXME stream filter setup should be per segment
{
ADM_warning("Combining AVCC and AnnexB type H.264 streams is currently not supported.\n");
cut=ADM_EDITOR_CUT_POINT_MISMATCH;
BOWOUT
}
// For AVCC, check that NALU length is coded on the same number of bytes
if(extraLen)
{
uint32_t nalSize2=ADM_getNalSizeH264(extra,extraLen);
if(nalSize2 != nalSize)
{
ADM_warning("NAL unit length size mismatch: %u vs %u\n",nalSize2,nalSize);
cut=ADM_EDITOR_CUT_POINT_MISMATCH;
BOWOUT
}
}
// Get SPS info
// Check for in-band SPS first
// Identify the last keyframe of the segment. If in-band SPS is present, it will be there.
if(false==getFrameNumFromPtsOrBefore(vid, seg->_refStartTimeUs+seg->_durationUs-1, frame))
{
ADM_warning("Cannot identify the last frame in display order for segment %d\n",segNo);
BOWOUT
}
flags=0;
demuxer->getFlags(frame,&flags);
while(frame>0)
{
if(flags & AVI_KEY_FRAME) break;
demuxer->getFlags(--frame,&flags);
}
// Retrieve this keyframe
CHECK_FRAME(frame)
if(!demuxer->getFrame(frame,&img))
{
ADM_warning("Unable to get frame %d in ref %d, segment %d\n",frame,seg->_reference,segNo);
BOWOUT
}
spsLen1=0;
// Allocate buffer to hold copy of raw SPS data
if(!spsBuf1)
spsBuf1=new uint8_t[MAX_H264_SPS_SIZE];
memset(spsBuf1,0,MAX_H264_SPS_SIZE);
if(AnnexB)
spsLen1=getRawH264SPS_startCode(img.data, img.dataLength, spsBuf1, MAX_H264_SPS_SIZE);
else
spsLen1=getRawH264SPS(img.data, img.dataLength, nalSize, spsBuf1, MAX_H264_SPS_SIZE);
if(spsLen1)
{ /* If the next segment's ref video doesn't have in-band SPS
but this one does, we must check that the SPS matches
the global header. */
if(memcmp(spsBuf1, nextSegParamCache, (spsLen1 > nextSegParamCacheSize)? nextSegParamCacheSize : spsLen1))
{
ADM_warning("In-band SPS before and after the cut point does not match? Checking deeper...\n");
ADM_SPSInfo tmpinfo;
if(!extractSPSInfoFromData(spsBuf1, spsLen1, &tmpinfo) || !getH264SPSInfo(vid,&tmpinfo))
{
ADM_warning("Cannot retrieve H.264 SPS info for segment %u\n",segNo);
BOWOUT
}
// Update SPS info used to parse slice header later
match=true;
MATCH(width)
MATCH(height)
MATCH(hasPocInfo)
MATCH(log2MaxFrameNum)
MATCH(log2MaxPocLsb)
MATCH(frameMbsOnlyFlag)
MATCH(refFrames)
if(!match && !spsLen2)
{
ADM_warning("SPS mismatch, saved video will be broken.\n");
cut=ADM_EDITOR_CUT_POINT_MISMATCH;
BOWOUT
}
#undef MATCH
}
}
if(gotIdr) // If the first frame after the cut is IDR, we can ignore POC.
{
ADM_info("IDR verified, ref videos are different but probably compatible.\n");
cut=ADM_EDITOR_CUT_POINT_KEY;
BOWOUT
}
}
ADM_info("Recovery distance: %u\n",recoveryDistance);
if(!recoveryDistance) // recovery point, check POC
{
if(poc2==-1)
{
ADM_warning("No POC to compare, only POC explicitely set in the slice header is supported.\n");
cut=ADM_EDITOR_CUT_POINT_KEY; // ??
BOWOUT
}
/* Get the POC of the last frame in stream order before the cut,
this is not necessarily the last displayed frame of the segment.
We need to start earlier and identify the cut point. */
uint32_t maxFrame,maxPtsFrame;
uint64_t maxPts;
if(false==findLastFrameBeforeSwitch(segNo,&maxFrame,&maxPtsFrame,&maxPts))
{
ADM_warning("Cannot identify the last frame before segment switch for segment %d\n",segNo);
BOWOUT
}
// maxFrame is now the last frame before segment switch.
// We need poc_lsb of this frame to get poc_msb right.
CHECK_FRAME(maxFrame)
if(!demuxer->getFrame(maxFrame,&img))
{
ADM_warning("Unable to get frame %d in ref %d, segment %d\n",maxFrame,seg->_reference,segNo);
BOWOUT
}
// Try to get POC, recovery distance doesn't matter here
poc1 = -1; // POC of the last frame before the cut
outcome=false;
if(AnnexB)
outcome=extractH264FrameType_startCode(img.data, img.dataLength, &(img.flags), &poc1, &sps, NULL);
else
outcome=extractH264FrameType(img.data, img.dataLength, nalSize, &(img.flags), &poc1, &sps, NULL);
if(!outcome)
{
ADM_warning("Cannot get H.264 frame type and Picture Order Count Least Significant Bits value.\n");
BOWOUT
}
if(poc1==-1)
{
ADM_warning("Cannot get POC, only POC explicitely set in the slice header is supported.\n");
BOWOUT
}
/* Calculate poc_msb, the discontinuity of poc_lsb at the cut point
may easily result in poc_msb incrementing or decrementing across the cut
due to poc_lsb wrapping around. */
const int maxPocLsb = 1 << sps.log2MaxPocLsb;
int pocMsb = 0;
if(poc1 > poc2 && poc1 - poc2 >= maxPocLsb/2)
pocMsb += maxPocLsb;
else if(poc2 > poc1 && poc2 - poc1 > maxPocLsb/2)
pocMsb -= maxPocLsb;
ADM_info("POC of the last frame %u in stream order of the previous seg: %d + %d = %d\n",
maxFrame, pocMsb, poc1, pocMsb + poc1);
int delta = poc1 - pocMsb - poc2;
/* If delta is positive, the cut is bad and we don't need to check POC of other frames.
If delta is negative (POC increasese across the cut), playback won't get stuck, but we
need to check whether POC ranges overlap which may result in pictures from both segments
displayed interleaved. */
if(delta>0)
{
ADM_warning("Saved video won't be smoothly playable in FFmpeg-based players (POC going back by %d)\n",delta);
cut=ADM_EDITOR_CUT_POINT_BAD_POC;
BOWOUT
}
cut=ADM_EDITOR_CUT_POINT_KEY;
if(!maxPts || maxPtsFrame==-1)
{
ADM_warning("Cannot identify the last frame in display order before the cut for segment %d\n",segNo);
BOWOUT
}
CHECK_FRAME(maxPtsFrame)
if(!demuxer->getFrame(maxPtsFrame,&img))
{
ADM_warning("Unable to get frame %d in ref %d, segment %d\n",maxPtsFrame,seg->_reference,segNo);
BOWOUT
}
// Got our frame, get poc_lsb of the slice
maxpoc1=-1;
outcome=false;
if(AnnexB)
outcome=extractH264FrameType_startCode(img.data, img.dataLength, &(img.flags), &maxpoc1, &sps, NULL);
else
outcome=extractH264FrameType(img.data, img.dataLength, nalSize, &(img.flags), &maxpoc1, &sps, NULL);
if(!outcome)
{
ADM_warning("Cannot get H.264 frame type and Picture Order Count Least Significant Bits value.\n");
BOWOUT
}
if(maxpoc1==-1)
{
ADM_warning("Cannot get POC, only POC explicitely set in the slice header is supported.\n");
BOWOUT // or should the check fail instead?
}
/* Check that POC doesn't go back, i.e. max POC before the cut is less
than min POC after segment switch. First check that poc_msb is still valid. */
int prevPocMsb=0;
if(maxpoc1 > poc1 && maxpoc1 - poc1 >= maxPocLsb/2)
prevPocMsb += maxPocLsb;
else if(poc1 > maxpoc1 && poc1 - maxpoc1 > maxPocLsb/2)
prevPocMsb -= maxPocLsb;
ADM_info("POC of the last frame %u in display order of the previous seg: %d + %d = %d\n",
maxPtsFrame, prevPocMsb, maxpoc1, prevPocMsb + maxpoc1);
poc1 += prevPocMsb;
if(poc2 > minpoc2 && poc2 - minpoc2 >= maxPocLsb/2)
pocMsb += maxPocLsb;
else if(minpoc2 > poc2 && minpoc2 - poc2 > maxPocLsb/2)
pocMsb -= maxPocLsb;
ADM_info("POC of the earliest frame %d in display order of the current seg: %d + %d = %d\n",
earliest, pocMsb, poc2, pocMsb + poc2);
poc2 += pocMsb;
delta=poc1-poc2;
if(delta>0)
{
ADM_warning("Saved video will exhibit flicker at cut point in FFmpeg-based players (POC overlap by %d)\n",delta);
cut=ADM_EDITOR_CUT_POINT_BAD_POC;
BOWOUT
}
}
}
if(isH265Compatible(info.fcc))
{
int poc1,maxpoc1,poc2,minpoc2;
// In HEVC, we check only for POC going back.
// Get SPS to be able to decode the slice header
ADM_SPSinfoH265 sps;
if(!getH265SPSInfo(vid,&sps))
{
ADM_warning("Cannot retrieve SPS info.\n");
BOWOUT
}
// Determine stream type
bool AnnexB=false;
uint8_t *extra;
uint32_t extraLen=0;
uint32_t nalSize=0;
demuxer->getExtraHeaderData(&extraLen,&extra);
if(!extraLen)
AnnexB=true;
else
nalSize=ADM_getNalSizeH265(extra,extraLen);
// Allocate memory to hold compressed frame
ADMCompressedImage img;
buffer=new uint8_t[MAX_FRAME_LENGTH];
img.data=buffer;
// With HEVC we need to check the preceding segment first
ADM_info("Getting previous segment, current segment number: %d\n",segNo);
ADM_assert(segNo>0);
segNo--;
seg=_segments.getSegment(segNo);
vid=_segments.getRefVideo(seg->_reference);
demuxer=vid->_aviheader;
oldFrame=vid->lastSentFrame;
uint32_t rememberCurrent=frame;
uint32_t rememberLastSent=oldFrame;
if(false==switchToSegment(segNo,true))
{
ADM_warning("Cannot check the previous segment %d\n",segNo);
BOWOUT
}
// Not the same ref video?
if(seg->_reference!=refNo)
{
// Does the codec match?
demuxer->getVideoInfo(&info);
if(!isH265Compatible(info.fcc))
{
ADM_error("Codec mismatch!\n");
cut=ADM_EDITOR_CUT_POINT_MISMATCH;
BOWOUT
}
// Check that stream types match
extraLen=0;
demuxer->getExtraHeaderData(&extraLen,&extra);
if(!extraLen != AnnexB) // FIXME stream filter setup should be per segment
{
ADM_warning("Combining AVCC and AnnexB type HEVC streams is currently not supported.\n");
cut=ADM_EDITOR_CUT_POINT_MISMATCH;
BOWOUT
}
// For HVCC, check that NALU length is coded on the same number of bytes
if(extraLen)
{
uint32_t nalSize2=ADM_getNalSizeH265(extra,extraLen);
if(nalSize2 != nalSize)
{
ADM_warning("NAL unit length size mismatch: %u vs %u\n",nalSize2,nalSize);
cut=ADM_EDITOR_CUT_POINT_MISMATCH;
BOWOUT
}
}
// Get SPS info
ADM_SPSinfoH265 sps2;
if(!getH265SPSInfo(vid,&sps2))
{
ADM_warning("Cannot retrieve SPS info for HEVC ref video in segment %d\n",segNo);
BOWOUT
}
// We have SPS, does it match the one from the next segment?
// Width and height match for sure, check remaining fields.
#define MATCH(x) if(sps.x != sps2.x) { ADM_warning("%s value does not match.\n",#x); match=false; }
bool match=true;
MATCH(fps1000)
MATCH(log2_max_poc_lsb)
MATCH(separate_colour_plane_flag)
MATCH(num_extra_slice_header_bits)
MATCH(dependent_slice_segments_enabled_flag)
MATCH(output_flag_present_flag)
MATCH(field_info_present)
MATCH(address_coding_length)
if(!match)
{
ADM_warning("SPS mismatch, saved video will be broken.\n");
cut=ADM_EDITOR_CUT_POINT_MISMATCH;
BOWOUT
}
}
// Get the POC of the last frame in stream order before the cut,
uint32_t maxFrame,maxPtsFrame;
uint64_t maxPts=0;
if(false==findLastFrameBeforeSwitch(segNo,&maxFrame,&maxPtsFrame,&maxPts) ||
(int)maxFrame==-1 || (int)maxPtsFrame==-1 || !maxPts)
{
ADM_warning("Cannot identify the last frame before segment switch for segment %d\n",segNo);
BOWOUT
}
// maxFrame is now the last frame before segment switch.
// If maxPts happens earlier, we must start there.
if(maxFrame>maxPtsFrame && maxFrame-maxPtsFrame>16)
maxPtsFrame=maxFrame; // invalidate maxPtsFrame
frame=(maxPtsFrame < maxFrame && maxFrame-maxPtsFrame < 16)? maxPtsFrame : maxFrame;
// Try to get POC, we start either at the last frame in display order
// or in stream order before the cut, whichever comes first.
poc1 = INT_MIN;
maxpoc1 = poc1;
bool outcome=false;
for(int i=frame; i<=maxFrame; i++)
{
CHECK_FRAME(i)
if(!demuxer->getFrame(i,&img))
{
ADM_warning("Unable to get frame %d in ref %d, segment %d\n",i,seg->_reference,segNo);
BOWOUT
}
if(AnnexB)
outcome=extractH265FrameType_startCode(img.data, img.dataLength, &sps, &(img.flags), &poc1);
else
outcome=extractH265FrameType(img.data, img.dataLength, nalSize, &sps, &(img.flags), &poc1);
if(!outcome)
{
ADM_warning("Cannot get HEVC frame type and Picture Order Count value.\n");
BOWOUT
}
if(poc1 > maxpoc1)
maxpoc1 = poc1;
}
// We are done with this segment, restore the last sent frame
vid->lastSentFrame=oldFrame;
// Switch back to the segment after the cutpoint
segNo++;
if(false==switchToSegment(segNo,true))
{
ADM_warning("Cannot return to the current segment %d\n",segNo);
BOWOUT
}
// Restore