forked from id-Software/DOOM-3-BFG
-
Notifications
You must be signed in to change notification settings - Fork 251
/
Cinematic.cpp
3352 lines (3008 loc) · 82.9 KB
/
Cinematic.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
/*
===========================================================================
Doom 3 BFG Edition GPL Source Code
Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company.
Copyright (C) 2013-2014 Robert Beckebans
Copyright (C) 2014 Carl Kenner
This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").
Doom 3 BFG Edition Source Code 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 3 of the License, or
(at your option) any later version.
Doom 3 BFG Edition Source Code 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 Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "precompiled.h"
#pragma hdrstop
#if defined(_MSC_VER) && !defined(USE_OPENAL)
#include <sound/XAudio2/XA2_CinematicAudio.h>
#else
#include <sound/OpenAL/AL_CinematicAudio.h>
#endif
// SRS - Add cvar to control whether cinematic audio is played: default is ON
idCVar s_playCinematicAudio( "s_playCinematicAudio", "1", CVAR_BOOL, "Play audio if available in cinematic video files" );
//extern "C" {
#include <jpeglib.h>
//}
#include "RenderCommon.h"
#define CIN_system 1
#define CIN_loop 2
#define CIN_hold 4
#define CIN_silent 8
#define CIN_shader 16
#if defined(USE_FFMPEG)
// Carl: ffmpg for bink video files
extern "C"
{
//#ifdef WIN32
#ifndef INT64_C
#define INT64_C(c) (c ## LL)
#define UINT64_C(c) (c ## ULL)
#endif
//#include <inttypes.h>
//#endif
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <libswresample/swresample.h>
#include <libavutil/imgutils.h>
}
#include <queue>
#define NUM_LAG_FRAMES 15 // SRS - Lag audio by 15 frames (~1/2 sec at 30 fps) for ffmpeg bik decoder AV sync
#endif
#ifdef USE_BINKDEC
// DG: not sure how to use FFMPEG and BINKDEC at the same time.. it might be useful if someone wants to
// use binkdec for bink and FFMPEG for other formats in custom code so I didn't just rip FFMPEG out
// But right now it's unsupported, if you need this adjust the video loading code etc yourself
#ifdef USE_FFMPEG
#error "Currently, only one of FFMPEG and BINKDEC is supported at a time!"
#endif
#include <BinkDecoder.h>
#endif // USE_BINKDEC
class idCinematicLocal : public idCinematic
{
public:
idCinematicLocal();
virtual ~idCinematicLocal();
virtual bool InitFromFile( const char* qpath, bool looping, nvrhi::ICommandList* commandList );
virtual cinData_t ImageForTime( int milliseconds, nvrhi::ICommandList* commandList );
virtual int AnimationLength();
// RB begin
bool IsPlaying() const;
// RB end
virtual void Close();
// SRS begin
virtual int GetStartTime();
// SRS end
virtual void ResetTime( int time );
private:
#if defined(USE_FFMPEG)
int video_stream_index;
int audio_stream_index; //GK: Make extra indexer for audio
AVFormatContext* fmt_ctx;
AVFrame* frame;
AVFrame* frame2;
AVFrame* frame3; //GK: make extra frame for audio
#if LIBAVCODEC_VERSION_MAJOR > 58
const AVCodec* dec;
const AVCodec* dec2; // SRS - Separate decoder for audio
#else
AVCodec* dec;
AVCodec* dec2; // SRS - Separate decoder for audio
#endif
AVCodecContext* dec_ctx;
AVCodecContext* dec_ctx2;
SwsContext* img_convert_ctx;
bool hasFrame;
long framePos;
AVSampleFormat dst_smp;
bool hasplanar;
SwrContext* swr_ctx;
cinData_t ImageForTimeFFMPEG( int milliseconds, nvrhi::ICommandList* commandList );
bool InitFromFFMPEGFile( const char* qpath, bool looping, nvrhi::ICommandList* commandList );
void FFMPEGReset();
std::queue<uint8_t*> lagBuffer;
std::queue<int> lagBufSize;
bool skipLag;
#endif
#ifdef USE_BINKDEC
BinkHandle binkHandle;
cinData_t ImageForTimeBinkDec( int milliseconds, nvrhi::ICommandList* commandList );
bool InitFromBinkDecFile( const char* qpath, bool looping, nvrhi::ICommandList* commandList );
void BinkDecReset();
YUVbuffer yuvBuffer;
bool hasFrame;
int framePos;
int numFrames;
idImage* imgY;
idImage* imgCr;
idImage* imgCb;
uint32_t audioTracks;
uint32_t trackIndex;
AudioInfo binkInfo;
#endif
idImage* img;
bool isRoQ;
// RB: 64 bit fixes, changed long to int
size_t mcomp[256];
// RB end
byte** qStatus[2];
idStr fileName;
int CIN_WIDTH, CIN_HEIGHT;
idFile* iFile;
cinStatus_t status;
// RB: 64 bit fixes, changed long to int
int tfps;
int RoQPlayed;
int ROQSize;
unsigned int RoQFrameSize;
int onQuad;
int numQuads;
int samplesPerLine;
unsigned int roq_id;
int screenDelta;
byte* buf;
int samplesPerPixel; // defaults to 2
unsigned int xsize, ysize, maxsize, minsize;
int normalBuffer0;
int roq_flags;
int roqF0;
int roqF1;
int t[2];
int roqFPS;
int drawX, drawY;
// RB end
int animationLength;
int startTime;
float frameRate;
byte* image;
bool looping;
bool dirty;
bool half;
bool smootheddouble;
bool inMemory;
void RoQ_init();
void blitVQQuad32fs( byte** status, unsigned char* data );
void RoQShutdown();
void RoQInterrupt();
void move8_32( byte* src, byte* dst, int spl );
void move4_32( byte* src, byte* dst, int spl );
void blit8_32( byte* src, byte* dst, int spl );
void blit4_32( byte* src, byte* dst, int spl );
void blit2_32( byte* src, byte* dst, int spl );
// RB: 64 bit fixes, changed long to int
unsigned short yuv_to_rgb( int y, int u, int v );
unsigned int yuv_to_rgb24( int y, int u, int v );
void decodeCodeBook( byte* input, unsigned short roq_flags );
void recurseQuad( int startX, int startY, int quadSize, int xOff, int yOff );
void setupQuad( int xOff, int yOff );
void readQuadInfo( byte* qData );
void RoQPrepMcomp( int xoff, int yoff );
void RoQReset();
// RB end
//GK:Also init variables for XAudio2 or OpenAL (SRS - this must be an instance variable)
CinematicAudio* cinematicAudio = NULL;
};
// Carl: ROQ files from original Doom 3
const int DEFAULT_CIN_WIDTH = 512;
const int DEFAULT_CIN_HEIGHT = 512;
const int MAXSIZE = 8;
const int MINSIZE = 4;
const int ROQ_FILE = 0x1084;
const int ROQ_QUAD = 0x1000;
const int ROQ_QUAD_INFO = 0x1001;
const int ROQ_CODEBOOK = 0x1002;
const int ROQ_QUAD_VQ = 0x1011;
const int ROQ_QUAD_JPEG = 0x1012;
const int ROQ_QUAD_HANG = 0x1013;
const int ROQ_PACKET = 0x1030;
const int ZA_SOUND_MONO = 0x1020;
const int ZA_SOUND_STEREO = 0x1021;
// temporary buffers used by all cinematics
// RB: 64 bit fixes, changed long to int
static int ROQ_YY_tab[256];
static int ROQ_UB_tab[256];
static int ROQ_UG_tab[256];
static int ROQ_VG_tab[256];
static int ROQ_VR_tab[256];
// RB end
static byte* file = NULL;
static unsigned short* vq2 = NULL;
static unsigned short* vq4 = NULL;
static unsigned short* vq8 = NULL;
//===========================================
/*
==============
idCinematic::InitCinematic
==============
*/
// RB: 64 bit fixes, changed long to int
void idCinematic::InitCinematic()
{
// Carl: Doom 3 ROQ:
float t_ub, t_vr, t_ug, t_vg;
int i;
// generate YUV tables
t_ub = ( 1.77200f / 2.0f ) * ( float )( 1 << 6 ) + 0.5f;
t_vr = ( 1.40200f / 2.0f ) * ( float )( 1 << 6 ) + 0.5f;
t_ug = ( 0.34414f / 2.0f ) * ( float )( 1 << 6 ) + 0.5f;
t_vg = ( 0.71414f / 2.0f ) * ( float )( 1 << 6 ) + 0.5f;
for( i = 0; i < 256; i++ )
{
float x = ( float )( 2 * i - 255 );
ROQ_UB_tab[i] = ( int )( ( t_ub * x ) + ( 1 << 5 ) );
ROQ_VR_tab[i] = ( int )( ( t_vr * x ) + ( 1 << 5 ) );
ROQ_UG_tab[i] = ( int )( ( -t_ug * x ) );
ROQ_VG_tab[i] = ( int )( ( -t_vg * x ) + ( 1 << 5 ) );
ROQ_YY_tab[i] = ( int )( ( i << 6 ) | ( i >> 2 ) );
}
file = ( byte* )Mem_Alloc( 65536, TAG_CINEMATIC );
vq2 = ( word* )Mem_Alloc( 256 * 16 * 4 * sizeof( word ), TAG_CINEMATIC );
vq4 = ( word* )Mem_Alloc( 256 * 64 * 4 * sizeof( word ), TAG_CINEMATIC );
vq8 = ( word* )Mem_Alloc( 256 * 256 * 4 * sizeof( word ), TAG_CINEMATIC );
}
/*
==============
idCinematic::ShutdownCinematic
==============
*/
void idCinematic::ShutdownCinematic()
{
// Carl: Original Doom 3 RoQ files:
Mem_Free( file );
file = NULL;
Mem_Free( vq2 );
vq2 = NULL;
Mem_Free( vq4 );
vq4 = NULL;
Mem_Free( vq8 );
vq8 = NULL;
}
/*
==============
idCinematic::Alloc
==============
*/
idCinematic* idCinematic::Alloc()
{
return new idCinematicLocal; //Carl: Use the proper class like in Doom 3, not just the unimplemented abstract one.
}
/*
==============
idCinematic::~idCinematic
==============
*/
idCinematic::~idCinematic()
{
Close();
}
/*
==============
idCinematic::InitFromFile
==============
*/
bool idCinematic::InitFromFile( const char* qpath, bool looping, nvrhi::ICommandList* commandList )
{
return false; //Carl: this is just the abstract virtual method
}
/*
==============
idCinematic::AnimationLength
==============
*/
int idCinematic::AnimationLength()
{
return 0;
}
/*
==============
idCinematic::GetStartTime
==============
*/
int idCinematic::GetStartTime()
{
return -1; // SRS - this is just the abstract virtual method
}
/*
==============
idCinematic::ResetTime
==============
*/
void idCinematic::ResetTime( int milliseconds )
{
}
/*
==============
idCinematic::ImageForTime
==============
*/
cinData_t idCinematic::ImageForTime( int milliseconds, nvrhi::ICommandList* commandList )
{
cinData_t c;
memset( &c, 0, sizeof( c ) );
declManager->FindMaterial( "doom64.tga" );
c.image = globalImages->GetImage( "doom64.tga" );
return c;
}
/*
==============
idCinematic::ExportToTGA
==============
*/
void idCinematic::ExportToTGA( bool skipExisting )
{
}
/*
==============
idCinematic::GetFrameRate
==============
*/
float idCinematic::GetFrameRate() const
{
return 30.0f;
}
/*
==============
idCinematic::Close
==============
*/
void idCinematic::Close()
{
}
// RB begin
/*
==============
idCinematic::IsPlaying
==============
*/
bool idCinematic::IsPlaying() const
{
return false;
}
// RB end
// SRS begin
/*
==============
CinematicAudio::~CinematicAudio
==============
*/
CinematicAudio::~CinematicAudio()
{
}
// SRS end
//===========================================
/*
==============
idCinematicLocal::idCinematicLocal
==============
*/
idCinematicLocal::idCinematicLocal()
{
qStatus[0] = ( byte** )Mem_Alloc( 32768 * sizeof( byte* ), TAG_CINEMATIC );
qStatus[1] = ( byte** )Mem_Alloc( 32768 * sizeof( byte* ), TAG_CINEMATIC );
isRoQ = false; // SRS - Initialize isRoQ for all cases, not just FFMPEG
#if defined(USE_FFMPEG)
// Carl: ffmpeg stuff, for bink and normal video files:
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55,28,1)
frame = av_frame_alloc();
frame2 = av_frame_alloc();
frame3 = av_frame_alloc();
#else
frame = avcodec_alloc_frame();
frame2 = avcodec_alloc_frame();
frame3 = avcodec_alloc_frame();
#endif // LIBAVCODEC_VERSION_INT
dec_ctx = NULL;
dec_ctx2 = NULL;
fmt_ctx = NULL;
video_stream_index = -1;
audio_stream_index = -1;
hasplanar = false;
swr_ctx = NULL;
img_convert_ctx = NULL;
hasFrame = false;
framePos = -1;
skipLag = false;
#endif
#ifdef USE_BINKDEC
binkHandle.isValid = false;
binkHandle.instanceIndex = -1; // whatever this is, it now has a deterministic value
hasFrame = false;
framePos = -1;
numFrames = 0;
audioTracks = 0;
trackIndex = -1;
binkInfo = {};
imgY = globalImages->AllocStandaloneImage( "_cinematicY" );
imgCr = globalImages->AllocStandaloneImage( "_cinematicCr" );
imgCb = globalImages->AllocStandaloneImage( "_cinematicCb" );
{
idImageOpts opts;
opts.format = FMT_LUM8;
opts.colorFormat = CFM_DEFAULT;
opts.width = 32;
opts.height = 32;
opts.numLevels = 1;
if( imgY != NULL )
{
imgY->AllocImage( opts, TF_LINEAR, TR_REPEAT );
}
if( imgCr != NULL )
{
imgCr->AllocImage( opts, TF_LINEAR, TR_REPEAT );
}
if( imgCb != NULL )
{
imgCb->AllocImage( opts, TF_LINEAR, TR_REPEAT );
}
}
#endif
// Carl: Original Doom 3 RoQ files:
image = NULL;
status = FMV_EOF;
buf = NULL;
iFile = NULL;
img = globalImages->AllocStandaloneImage( "_cinematic" );
if( img != NULL )
{
idImageOpts opts;
opts.format = FMT_RGBA8;
opts.colorFormat = CFM_DEFAULT;
opts.width = 32;
opts.height = 32;
opts.numLevels = 1;
img->AllocImage( opts, TF_LINEAR, TR_REPEAT );
}
}
/*
==============
idCinematicLocal::~idCinematicLocal
==============
*/
idCinematicLocal::~idCinematicLocal()
{
Close();
// Carl: Original Doom 3 RoQ files:
Mem_Free( qStatus[0] );
qStatus[0] = NULL;
Mem_Free( qStatus[1] );
qStatus[1] = NULL;
#if defined(USE_FFMPEG)
// Carl: ffmpeg for bink and other video files:
// RB: TODO double check this. It seems we have different versions of ffmpeg on Kubuntu 13.10 and the win32 development files
//#if defined(_WIN32) || defined(_WIN64)
// SRS - Should use the same version criteria as when the frames are allocated in idCinematicLocal() above
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55,28,1)
av_frame_free( &frame );
av_frame_free( &frame2 );
av_frame_free( &frame3 );
#else
av_freep( &frame );
av_freep( &frame2 );
av_freep( &frame3 );
#endif
#endif
#ifdef USE_BINKDEC
delete imgY;
imgY = NULL;
delete imgCr;
imgCr = NULL;
delete imgCb;
imgCb = NULL;
#endif
delete img;
img = NULL;
// GK/SRS - Properly close and delete XAudio2 or OpenAL voice if instantiated
if( cinematicAudio )
{
cinematicAudio->ShutdownAudio();
delete cinematicAudio;
cinematicAudio = NULL;
}
}
#if defined(USE_FFMPEG)
/*
==============
GetSampleFormat
==============
*/
const char* GetSampleFormat( AVSampleFormat sample_fmt )
{
switch( sample_fmt )
{
case AV_SAMPLE_FMT_U8:
case AV_SAMPLE_FMT_U8P:
{
return "8-bit";
}
case AV_SAMPLE_FMT_S16:
case AV_SAMPLE_FMT_S16P:
{
return "16-bit";
}
case AV_SAMPLE_FMT_S32:
case AV_SAMPLE_FMT_S32P:
{
return "32-bit";
}
case AV_SAMPLE_FMT_FLT:
case AV_SAMPLE_FMT_FLTP:
{
return "Float";
}
case AV_SAMPLE_FMT_DBL:
case AV_SAMPLE_FMT_DBLP:
{
return "Double";
}
default:
{
return "Unknown";
}
}
}
/*
==============
idCinematicLocal::InitFromFFMPEGFile
==============
*/
bool idCinematicLocal::InitFromFFMPEGFile( const char* qpath, bool amilooping, nvrhi::ICommandList* commandList )
{
int ret;
int ret2;
int file_size;
char error[64];
looping = amilooping;
startTime = 0;
isRoQ = false;
CIN_HEIGHT = DEFAULT_CIN_HEIGHT;
CIN_WIDTH = DEFAULT_CIN_WIDTH;
idStr fullpath;
idFile* testFile = fileSystem->OpenFileRead( qpath );
if( testFile )
{
fullpath = testFile->GetFullPath();
file_size = testFile->Length();
fileSystem->CloseFile( testFile );
}
// RB: case sensitivity HACK for Linux
else if( idStr::Cmpn( qpath, "sound/vo", 8 ) == 0 )
{
idStr newPath( qpath );
newPath.Replace( "sound/vo", "sound/VO" );
testFile = fileSystem->OpenFileRead( newPath );
if( testFile )
{
fullpath = testFile->GetFullPath();
file_size = testFile->Length();
fileSystem->CloseFile( testFile );
}
else
{
common->Warning( "idCinematic: Cannot open FFMPEG video file: '%s', %d\n", qpath, looping );
return false;
}
}
//idStr fullpath = fileSystem->RelativePathToOSPath( qpath, "fs_basepath" );
if( ( ret = avformat_open_input( &fmt_ctx, fullpath, NULL, NULL ) ) < 0 )
{
// SRS - another case sensitivity HACK for Linux, this time for ffmpeg and RoQ files
idStr ext;
fullpath.ExtractFileExtension( ext );
if( idStr::Cmp( ext.c_str(), "roq" ) == 0 )
{
// SRS - If ffmpeg can't open .roq file, then try again with .RoQ extension instead
fullpath.Replace( ".roq", ".RoQ" );
ret = avformat_open_input( &fmt_ctx, fullpath, NULL, NULL );
}
if( ret < 0 )
{
common->Warning( "idCinematic: Cannot open FFMPEG video file: '%s', %d\n", qpath, looping );
return false;
}
}
if( ( ret = avformat_find_stream_info( fmt_ctx, NULL ) ) < 0 )
{
common->Warning( "idCinematic: Cannot find stream info: '%s', %d\n", qpath, looping );
return false;
}
/* select the video stream */
ret = av_find_best_stream( fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0 );
if( ret < 0 )
{
common->Warning( "idCinematic: Cannot find a video stream in: '%s', %d\n", qpath, looping );
return false;
}
video_stream_index = ret;
dec_ctx = avcodec_alloc_context3( dec );
if( ( ret = avcodec_parameters_to_context( dec_ctx, fmt_ctx->streams[video_stream_index]->codecpar ) ) < 0 )
{
av_strerror( ret, error, sizeof( error ) );
common->Warning( "idCinematic: Failed to create video codec context from codec parameters with error: %s\n", error );
}
//dec_ctx->time_base = fmt_ctx->streams[video_stream_index]->time_base; // SRS - decoder timebase is set by avcodec_open2()
dec_ctx->framerate = fmt_ctx->streams[video_stream_index]->avg_frame_rate;
dec_ctx->pkt_timebase = fmt_ctx->streams[video_stream_index]->time_base; // SRS - packet timebase for frame->pts timestamps
/* init the video decoder */
if( ( ret = avcodec_open2( dec_ctx, dec, NULL ) ) < 0 )
{
av_strerror( ret, error, sizeof( error ) );
common->Warning( "idCinematic: Cannot open video decoder for: '%s', %d, with error: %s\n", qpath, looping, error );
return false;
}
//GK:Begin
//After the video decoder is open then try to open audio decoder
ret2 = av_find_best_stream( fmt_ctx, AVMEDIA_TYPE_AUDIO, -1, -1, &dec2, 0 );
if( ret2 >= 0 && s_playCinematicAudio.GetBool() ) //Make audio optional (only intro video has audio no other)
{
audio_stream_index = ret2;
dec_ctx2 = avcodec_alloc_context3( dec2 );
if( ( ret2 = avcodec_parameters_to_context( dec_ctx2, fmt_ctx->streams[audio_stream_index]->codecpar ) ) < 0 )
{
av_strerror( ret2, error, sizeof( error ) );
common->Warning( "idCinematic: Failed to create audio codec context from codec parameters with error: %s\n", error );
}
//dec_ctx2->time_base = fmt_ctx->streams[audio_stream_index]->time_base; // SRS - decoder timebase is set by avcodec_open2()
dec_ctx2->framerate = fmt_ctx->streams[audio_stream_index]->avg_frame_rate;
dec_ctx2->pkt_timebase = fmt_ctx->streams[audio_stream_index]->time_base; // SRS - packet timebase for frame3->pts timestamps
if( ( ret2 = avcodec_open2( dec_ctx2, dec2, NULL ) ) < 0 )
{
common->Warning( "idCinematic: Cannot open audio decoder for: '%s', %d\n", qpath, looping );
//return false;
}
if( dec_ctx2->sample_fmt >= AV_SAMPLE_FMT_U8P ) // SRS - Planar formats start at AV_SAMPLE_FMT_U8P
{
dst_smp = static_cast<AVSampleFormat>( dec_ctx2->sample_fmt - AV_SAMPLE_FMT_U8P ); // SRS - Setup context to convert from planar to packed
#if LIBSWRESAMPLE_VERSION_INT >= AV_VERSION_INT(4,7,100)
if( ( ret2 = swr_alloc_set_opts2( &swr_ctx, &dec_ctx2->ch_layout, dst_smp, dec_ctx2->sample_rate, &dec_ctx2->ch_layout, dec_ctx2->sample_fmt, dec_ctx2->sample_rate, 0, NULL ) ) < 0 )
{
av_strerror( ret2, error, sizeof( error ) );
common->Warning( "idCinematic: Failed to create audio resample context with error: %s\n", error );
}
#else
swr_ctx = swr_alloc_set_opts( NULL, dec_ctx2->channel_layout, dst_smp, dec_ctx2->sample_rate, dec_ctx2->channel_layout, dec_ctx2->sample_fmt, dec_ctx2->sample_rate, 0, NULL );
#endif
ret2 = swr_init( swr_ctx );
hasplanar = true;
}
else
{
dst_smp = dec_ctx2->sample_fmt; // SRS - Must always define the destination format
hasplanar = false;
}
common->Printf( "Cinematic audio stream found: Sample Rate=%d Hz, Channels=%d, Format=%s, Planar=%d\n", dec_ctx2->sample_rate,
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,37,100)
dec_ctx2->ch_layout.nb_channels,
#else
dec_ctx2->channels,
#endif
GetSampleFormat( dec_ctx2->sample_fmt ), hasplanar );
#if defined(_MSC_VER) && !defined(USE_OPENAL)
cinematicAudio = new( TAG_AUDIO ) CinematicAudio_XAudio2;
#else
cinematicAudio = new( TAG_AUDIO ) CinematicAudio_OpenAL;
#endif
cinematicAudio->InitAudio( dec_ctx2 );
}
//GK:End
CIN_WIDTH = dec_ctx->width;
CIN_HEIGHT = dec_ctx->height;
/** Calculate Duration in seconds
* This is the fundamental unit of time (in seconds) in terms
* of which frame timestamps are represented. For fixed-fps content,
* timebase should be 1/framerate and timestamp increments should be
* identically 1.
* - encoding: MUST be set by user.
* - decoding: Set by libavcodec.
*/
// SRS - Must use consistent duration and timebase parameters in the durationSec calculation (don't mix fmt_ctx duration with dec_ctx timebase)
float durationSec = static_cast<double>( fmt_ctx->streams[video_stream_index]->duration ) * av_q2d( fmt_ctx->streams[video_stream_index]->time_base );
//GK: No duration is given. Check if we get at least bitrate to calculate the length, otherwise set it to a fixed 100 seconds (should it be lower ?)
if( durationSec < 0 )
{
// SRS - First check the file context bit rate and estimate duration using file size and overall bit rate
if( fmt_ctx->bit_rate > 0 )
{
durationSec = file_size * 8.0 / fmt_ctx->bit_rate;
}
// SRS - Likely an RoQ file, so use the video bit rate tolerance plus audio bit rate to estimate duration, then add 10% to correct for variable bit rate
else if( dec_ctx->bit_rate_tolerance > 0 )
{
durationSec = file_size * 8.0 / ( dec_ctx->bit_rate_tolerance + ( dec_ctx2 ? dec_ctx2->bit_rate : 0 ) ) * 1.1;
}
// SRS - Otherwise just set a large max duration
else
{
durationSec = 100.0;
}
}
animationLength = durationSec * 1000;
frameRate = av_q2d( fmt_ctx->streams[video_stream_index]->avg_frame_rate );
common->Printf( "Loaded FFMPEG file: '%s', looping=%d, %dx%d, %3.2f FPS, %4.1f sec\n", qpath, looping, CIN_WIDTH, CIN_HEIGHT, frameRate, durationSec );
// SRS - Get image buffer size (dimensions mod 32 for bik & webm codecs, subsumes mod 16 for mp4 codec), then allocate image and fill with correct parameters
int bufWidth = ( CIN_WIDTH + 31 ) & ~31;
int bufHeight = ( CIN_HEIGHT + 31 ) & ~31;
int img_bytes = av_image_get_buffer_size( AV_PIX_FMT_BGR32, bufWidth, bufHeight, 1 );
image = ( byte* )Mem_Alloc( img_bytes, TAG_CINEMATIC );
av_image_fill_arrays( frame2->data, frame2->linesize, image, AV_PIX_FMT_BGR32, CIN_WIDTH, CIN_HEIGHT, 1 ); //GK: Straight out of the FFMPEG source code
img_convert_ctx = sws_getContext( dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt, CIN_WIDTH, CIN_HEIGHT, AV_PIX_FMT_BGR32, SWS_BICUBIC, NULL, NULL, NULL );
status = FMV_PLAY;
hasFrame = false;
framePos = -1;
ImageForTime( 0, commandList );
status = ( looping ) ? FMV_PLAY : FMV_IDLE;
return true;
}
#endif
/*
==============
idCinematicLocal::FFMPEGReset
==============
*/
#if defined(USE_FFMPEG)
void idCinematicLocal::FFMPEGReset()
{
// RB: don't reset startTime here because that breaks video replays in the PDAs
//startTime = 0;
framePos = -1;
// SRS - If we have cinematic audio, reset audio to release any stale buffers and avoid AV drift if looping
if( cinematicAudio )
{
cinematicAudio->ResetAudio();
while( !lagBuffer.empty() )
{
av_freep( &lagBuffer.front() );
lagBuffer.pop();
lagBufSize.pop();
}
}
// SRS - For non-RoQ (i.e. bik, mp4, webm, etc) files, use standard frame seek to rewind the stream
if( dec_ctx->codec_id != AV_CODEC_ID_ROQ && av_seek_frame( fmt_ctx, video_stream_index, 0, 0 ) >= 0 )
{
status = FMV_LOOPED;
}
// SRS - Special handling for RoQ files: only byte seek works and ffmpeg RoQ decoder needs reset
else if( dec_ctx->codec_id == AV_CODEC_ID_ROQ && av_seek_frame( fmt_ctx, video_stream_index, 0, AVSEEK_FLAG_BYTE ) >= 0 )
{
// Close and reopen the ffmpeg RoQ codec without clearing the context - this seems to reset the decoder properly
avcodec_close( dec_ctx );
avcodec_open2( dec_ctx, dec, NULL );
status = FMV_LOOPED;
}
// SRS - Can't rewind the stream so we really are at EOF
else
{
status = FMV_EOF;
}
}
#endif
/*
==============
idCinematicLocal::InitFromBinkDecFile
==============
*/
#ifdef USE_BINKDEC
bool idCinematicLocal::InitFromBinkDecFile( const char* qpath, bool amilooping, nvrhi::ICommandList* commandList )
{
looping = amilooping;
startTime = 0;
isRoQ = false;
CIN_HEIGHT = DEFAULT_CIN_HEIGHT;
CIN_WIDTH = DEFAULT_CIN_WIDTH;
idStr fullpath;
idFile* testFile = fileSystem->OpenFileRead( qpath );
if( testFile )
{
fullpath = testFile->GetFullPath();
fileSystem->CloseFile( testFile );
}
// RB: case sensitivity HACK for Linux
else if( idStr::Cmpn( qpath, "sound/vo", 8 ) == 0 )
{
idStr newPath( qpath );
newPath.Replace( "sound/vo", "sound/VO" );
testFile = fileSystem->OpenFileRead( newPath );
if( testFile )
{
fullpath = testFile->GetFullPath();
fileSystem->CloseFile( testFile );
}
else
{
common->Warning( "idCinematic: Cannot open Bink video file: '%s', %d\n", qpath, looping );
return false;
}
}
binkHandle = Bink_Open( fullpath );
if( !binkHandle.isValid )
{
common->Warning( "idCinematic: Cannot open Bink video file: '%s', %d\n", qpath, looping );
return false;
}
{
uint32_t w = 0, h = 0;
Bink_GetFrameSize( binkHandle, w, h );
CIN_WIDTH = w;
CIN_HEIGHT = h;
}
// SRS - Support Bink Audio for cinematic playback
audioTracks = Bink_GetNumAudioTracks( binkHandle );
if( audioTracks > 0 && s_playCinematicAudio.GetBool() )
{
trackIndex = 0; // SRS - Use the first audio track - is this reasonable?
binkInfo = Bink_GetAudioTrackDetails( binkHandle, trackIndex );
common->Printf( "Cinematic audio stream found: Sample Rate=%d Hz, Channels=%d, Format=16-bit\n", binkInfo.sampleRate, binkInfo.nChannels );
#if defined(_MSC_VER) && !defined(USE_OPENAL)
cinematicAudio = new( TAG_AUDIO ) CinematicAudio_XAudio2;
#else
cinematicAudio = new( TAG_AUDIO ) CinematicAudio_OpenAL;
#endif
cinematicAudio->InitAudio( &binkInfo );
}
frameRate = Bink_GetFrameRate( binkHandle );
numFrames = Bink_GetNumFrames( binkHandle );
float durationSec = numFrames / frameRate; // SRS - fixed Bink durationSec calculation
animationLength = durationSec * 1000; // SRS - animationLength is in milliseconds
common->Printf( "Loaded Bink file: '%s', looping=%d, %dx%d, %3.2f FPS, %4.1f sec\n", qpath, looping, CIN_WIDTH, CIN_HEIGHT, frameRate, durationSec );
memset( yuvBuffer, 0, sizeof( yuvBuffer ) );
status = FMV_PLAY;
hasFrame = false; // SRS - Implemented hasFrame for BinkDec behaviour consistency with FFMPEG
framePos = -1;
ImageForTime( 0, commandList ); // SRS - Was missing initial call to ImageForTime() - fixes validation errors when using Vulkan renderer
status = ( looping ) ? FMV_PLAY : FMV_IDLE; // SRS - Update status based on looping flag
return true;
}
/*
==============
idCinematicLocal::BinkDecReset
==============
*/
void idCinematicLocal::BinkDecReset()
{
framePos = -1;
// SRS - If we have cinematic audio, reset audio to release any stale buffers (even if looping)
if( cinematicAudio )
{
cinematicAudio->ResetAudio();
}
Bink_GotoFrame( binkHandle, 0 );
status = FMV_LOOPED;
}
#endif // USE_BINKDEC
/*
==============
idCinematicLocal::InitFromFile
==============
*/
bool idCinematicLocal::InitFromFile( const char* qpath, bool amilooping, nvrhi::ICommandList* commandList )
{
unsigned short RoQID;
// SRS - Don't need to call Close() here, all initialization is handled by constructor
//Close();
inMemory = 0;
animationLength = 100000;
// Carl: if no folder is specified, look in the video folder
if( strstr( qpath, "/" ) == NULL && strstr( qpath, "\\" ) == NULL )
{
sprintf( fileName, "video/%s", qpath );
}
else