This repository has been archived by the owner on Jan 12, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lgvid.cpp
1713 lines (1369 loc) · 45.2 KB
/
lgvid.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
/*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
*/
// Based on tutorial08.c
// A pedagogical video player that really works!
//
// Code based on FFplay, Copyright (c) 2003 Fabrice Bellard,
// and a tutorial by Martin Bohme (boehme@inb.uni-luebeckREMOVETHIS.de)
#include <cassert>
#include <algorithm>
#include <condition_variable>
#include <mutex>
#include <system_error>
#include <thread>
#include <vector>
#include <ObjBase.h>
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswresample/swresample.h>
#include <libswscale/swscale.h>
#include <libavutil/time.h>
#include <libavutil/opt.h>
}
#include "lgviddecoder.h"
#ifdef LGVS_USE_SUBS
#include "lgvs_lgvid_subs.h"
#endif // LGVS_NO_SUBS
#ifdef _DEBUG
#include <assert.h>
#define Warning(_x) FFmpeg::mprintf _x
#define Assert_(_x) assert(_x)
#define AssertMsg(_x, _msg) assert(_x)
#define AssertMsg1(_x, _msg, _a1) assert(_x)
#else
#define Warning(_x)
#define Assert_(_x)
#define AssertMsg(_x, _msg)
#define AssertMsg1(_x, _msg, _a1)
#endif
typedef unsigned long ulong;
const int AUDIO_BUFFER_SIZE = 16 * 1024;
const int MIN_AUDIOQ_SIZE = 20 * 16 * 1024;
const int MIN_FRAMES = 5;
const double AV_SYNC_THRESHOLD = 0.01;
const double AV_NOSYNC_THRESHOLD = 10.0;
const int SAMPLE_CORRECTION_PERCENT_MAX = 10;
const int AUDIO_DIFF_AVG_NB = 20;
const int VIDEO_PICTURE_QUEUE_SIZE = 2;
//#define DEFAULT_AV_SYNC_TYPE AV_SYNC_EXTERNAL_MASTER
static int sws_flags = SWS_BICUBIC;
#ifdef _DEBUG
// uncomment to simulate movie playback on slower CPU
//#define SIMULATE_SLOW_CPU
// simulated extra time (ms) for an audio packet to decode
#define AUDIO_DECODE_STALL (1000 / 60)
// simluated extra time (ms) for a video frame to decode
#define VIDEO_DECODE_STALL (1000 / 25)
#endif
///////////////////////////////////////////////////////////////////////////////
struct VideoState;
class cLGVideoDecoder : public ILGVideoDecoder {
public:
ILGVideoDecoderHost *m_pHostIface;
VideoState *is;
public:
cLGVideoDecoder(ILGVideoDecoderHost *pHostIface);
virtual ~cLGVideoDecoder();
// ILGVideoDecoder interface implementation
STDMETHOD_(void, Destroy)();
STDMETHOD_(BOOL, Start)();
STDMETHOD_(BOOL, IsFinished)();
STDMETHOD_(BOOL, IsVideoFrameAvailable)();
STDMETHOD_(void, RequestVideoFrame)();
STDMETHOD_(void, RequestAudio)(unsigned int len);
void Stop();
BOOL Init(const char* filename);
};
///////////////////////////////////////////////////////////////////////////////
//
// FFmpeg dynamic lib API
//
namespace FFmpeg {
cLGVideoDecoder *pOuter = nullptr;
static void mprintf(const char *fmt, ...)
{
char buf[1536];
if (pOuter) {
va_list ap;
va_start(ap, fmt);
vsprintf(buf, fmt, ap);
va_end(ap);
pOuter->m_pHostIface->LogPrint(buf);
}
}
void Shutdown()
{
pOuter = nullptr;
}
BOOL Init(cLGVideoDecoder *pOuter_)
{
pOuter = pOuter_;
return TRUE;
}
//
// I/O interface
//
struct IOContext {
void *pStream;
ulong size;
IOContext(void *str) { pStream = str; size = pOuter->m_pHostIface->FileSize(str); }
};
static int Read(void *opaque, uint8_t *buf, int buf_size)
{
IOContext *io = (IOContext*) opaque;
return pOuter->m_pHostIface->FileRead(io->pStream, buf, buf_size);
}
static int64_t Seek(void *opaque, int64_t offset, int whence)
{
IOContext *io = (IOContext*) opaque;
return (whence == AVSEEK_SIZE) ? (uint64_t) io->size : pOuter->m_pHostIface->FileSeek(io->pStream, static_cast<long>(offset), whence);
}
int OpenFile(AVFormatContext **ic_ptr, const char *filename)
{
void *pStream = pOuter->m_pHostIface->FileOpen(filename);
if (!pStream) {
mprintf("failed to open file '%s'", filename);
return -1;
}
int ret = 0;
IOContext *ctxt = new IOContext(pStream);
AVIOContext *pb = avio_alloc_context(nullptr, 0, 0, ctxt, Read, nullptr/*Write*/, Seek);
(*ic_ptr)->pb = pb;
ret = avformat_open_input(ic_ptr, filename, nullptr, nullptr);
if (ret) {
pOuter->m_pHostIface->FileClose(pStream);
delete ctxt;
av_free(pb);
}
return ret;
}
void CloseFile(AVFormatContext *s)
{
Assert_(s != nullptr);
AVIOContext *pb = s->pb;
if (pb) {
if (pb->opaque) {
IOContext *io = (IOContext*) pb->opaque;
if (io->pStream)
pOuter->m_pHostIface->FileClose(io->pStream);
delete io;
pb->opaque = nullptr;
}
av_free(pb);
}
avformat_close_input(&s);
}
};
#pragma pack(8)
///////////////////////////////////////////////////////////////////////////////
// Thread Utilities
class WorkerThread {
public:
WorkerThread() :
thread_()
{
}
virtual ~WorkerThread()
{
if (thread_ != nullptr)
wait_for_close();
}
bool create()
{
if (thread_ != nullptr)
return false;
try {
thread_ = new std::thread(
WorkerThread::thread_proc_wrapper,
this);
} catch (const std::system_error&) {
}
return thread_ != nullptr;
}
void wait_for_close()
{
if (thread_ == nullptr)
return;
thread_->join();
thread_ = nullptr;
}
protected:
virtual void thread_proc() = 0;
private:
static void thread_proc_wrapper(
void* pv)
{
auto pThread = static_cast<WorkerThread*>(pv);
pThread->thread_proc();
}
std::thread* thread_;
};
///////////////////////////////////////////////////////////////////////////////
//
// PacketQueue
//
struct PacketQueue {
PacketQueue() : first_pkt(0), last_pkt(0), nb_packets(0), size(0), quit(0), finished(0) {};
~PacketQueue()
{
Flush();
}
AVPacketList *first_pkt, *last_pkt;
int nb_packets;
int size;
std::mutex mutex;
std::condition_variable cond;
int Put(AVPacket *pkt)
{
Assert_(!finished && !quit);
AVPacketList *pkt1;
if (av_dup_packet(pkt) < 0) {
return -1;
}
pkt1 = (AVPacketList*) av_malloc(sizeof(AVPacketList));
if (!pkt1)
return -1;
pkt1->pkt = *pkt;
pkt1->next = nullptr;
mutex.lock();
if (!last_pkt)
first_pkt = pkt1;
else
last_pkt->next = pkt1;
last_pkt = pkt1;
nb_packets++;
size += pkt1->pkt.size + sizeof(*pkt1);
cond.notify_one();
mutex.unlock();
return 0;
}
int Get(AVPacket *pkt, int block)
{
AVPacketList *pkt1;
int ret;
std::unique_lock<std::mutex> locked_mutex(mutex);
for (;;) {
if (quit) {
ret = -1;
break;
}
pkt1 = first_pkt;
if (pkt1) {
first_pkt = pkt1->next;
if (!first_pkt)
last_pkt = nullptr;
nb_packets--;
size -= pkt1->pkt.size + sizeof(*pkt1);
*pkt = pkt1->pkt;
av_free(pkt1);
ret = 1;
break;
} else if (!block) {
ret = 0;
break;
} else {
// If finished and queue is empty, let receiver know
if (finished) {
ret = -1;
break;
}
cond.wait(locked_mutex);
}
}
return ret;
}
void Flush()
{
AVPacketList *pkt, *pkt1;
mutex.lock();
for (pkt = first_pkt; pkt != nullptr; pkt = pkt1) {
pkt1 = pkt->next;
av_free_packet(&pkt->pkt);
av_freep(&pkt);
}
last_pkt = nullptr;
first_pkt = nullptr;
nb_packets = 0;
size = 0;
mutex.unlock();
}
void Quit(int ret = 1)
{
mutex.lock();
quit = ret;
cond.notify_one();
mutex.unlock();
}
void Finished(int ret = 1)
{
mutex.lock();
finished = ret;
cond.notify_one();
mutex.unlock();
}
void Depleted()
{
mutex.lock();
finished = 1;
if (!first_pkt)
cond.notify_one();
mutex.unlock();
}
private:
int quit;
int finished;
};
///////////////////////////////////////////////////////////////////////////////
//
// VideoState
//
struct VideoState {
struct VideoPicture {
void *bmp;
double pts; ///<presentation time stamp for this picture
double target_clock; ///<av_gettime() time at which this should be displayed ideally
int64_t pos; ///<byte position in file
};
enum AV_SYNC {
AV_SYNC_AUDIO_MASTER,
AV_SYNC_VIDEO_MASTER,
AV_SYNC_EXTERNAL_MASTER,
AV_SYNC_DEFAULT = AV_SYNC_EXTERNAL_MASTER
};
cLGVideoDecoder *pOuter;
AVFormatContext *pFormatCtx;
int videoStream, audioStream;
AV_SYNC av_sync_type;
double external_clock; /* external clock base */
int64_t external_clock_time;
double audio_clock;
AVStream *audio_st;
PacketQueue audioq;
AVFrame* audio_frame;
std::vector<uint8_t> avr_buffer;
uint8_t *audio_buf;
unsigned int audio_buf_size;
unsigned int audio_buf_index;
AVPacket audio_pkt;
AVPacket audio_pkt2;
AVSampleFormat audio_src_fmt;
SwrContext* avr_context;
double audio_diff_cum; /* used for AV difference average computation */
double audio_diff_avg_coef;
double audio_diff_threshold;
int audio_diff_avg_count;
double frame_timer;
double frame_last_pts;
double frame_last_delay;
double video_clock; ///<pts of last decoded frame / predicted pts of next decoded frame
double video_current_pts; ///<current displayed pts (different from video_clock if frame fifos are used)
double video_current_pts_drift; ///<video_current_pts - time (av_gettime) at which we updated video_current_pts - used to have running video pts
int64_t video_current_pos; ///<current displayed file pos
int64_t video_current_pts_time; ///<time (av_gettime) at which we updated video_current_pts - used to have running video pts
AVStream *video_st;
PacketQueue videoq;
PixelFormat pict_pix_fmt;
VideoPicture pictq[VIDEO_PICTURE_QUEUE_SIZE];
int pictq_size, pictq_rindex, pictq_windex;
std::mutex pictq_mutex;
std::condition_variable pictq_cond;
class DecodeThread *parse_tid;
class VideoThread *video_tid;
int quit;
SwsContext *img_convert_ctx;
HANDLE timer;
int decode_finished;
int video_finished;
int audio_finished;
float skip_frames;
float skip_frames_index;
int refresh;
#ifdef LGVS_USE_SUBS
lgvs::LgVidSubs subs;
#endif // LGVS_NO_SUBS
VideoState(cLGVideoDecoder *pOuter_) :
pOuter(pOuter_),
pFormatCtx(),
videoStream(-1),
audioStream(-1),
av_sync_type(AV_SYNC_DEFAULT),
external_clock(),
external_clock_time(),
audio_clock(),
audio_st(),
audio_buf_size(),
audio_buf_index(),
audio_src_fmt(AV_SAMPLE_FMT_NONE),
avr_context(),
audio_diff_cum(),
audio_diff_avg_coef(),
audio_diff_threshold(),
audio_diff_avg_count(),
frame_timer(),
frame_last_pts(),
frame_last_delay(),
video_clock(),
video_current_pts(),
video_current_pts_drift(),
video_current_pos(),
video_current_pts_time(),
video_st(),
pictq_size(),
pictq_rindex(),
pictq_windex(),
parse_tid(),
video_tid(),
quit(),
img_convert_ctx(),
decode_finished(),
video_finished(),
audio_finished(),
skip_frames(),
skip_frames_index(),
refresh()
#ifdef LGVS_USE_SUBS
,
subs()
#endif // LGVS_NO_SUBS
{
audio_frame = av_frame_alloc();
av_init_packet(&audio_pkt);
memset(pictq, 0, sizeof(pictq));
}
~VideoState()
{
Close();
}
void schedule_refresh(int delay)
{
}
double get_audio_clock() const
{
double pts;
int hw_buf_size, bytes_per_sec;
pts = audio_clock;
hw_buf_size = audio_buf_size - audio_buf_index;
bytes_per_sec = 0;
if (audio_st) {
bytes_per_sec = audio_st->codec->sample_rate *
2 * audio_st->codec->channels;
}
if (bytes_per_sec)
pts -= (double) hw_buf_size / bytes_per_sec;
return pts;
}
void DecodeFinished()
{
videoq.Finished();
audioq.Finished();
decode_finished = 1;
}
void VideoFinished()
{
video_finished = 1;
}
void AudioFinished()
{
audio_finished = 1;
}
double get_video_clock() const
{
return video_current_pts_drift + av_gettime() / 1000000.0;
}
double get_external_clock() const
{
const int64_t ti = av_gettime();
return external_clock + ((ti - external_clock_time) * 1e-6);
}
double get_master_clock() const
{
double val;
if (av_sync_type == AV_SYNC_VIDEO_MASTER) {
if (video_st)
val = get_video_clock();
else
val = get_audio_clock();
} else if (av_sync_type == AV_SYNC_AUDIO_MASTER) {
if (audio_st)
val = get_audio_clock();
else
val = get_video_clock();
} else {
val = get_external_clock();
}
return val;
}
BOOL Open(const char *filename, int target_w, int target_h, PixelFormat dst_pix_fmt)
{
Close();
pFormatCtx = avformat_alloc_context();
// Open video file
if (FFmpeg::OpenFile(&pFormatCtx, filename) != 0)
return FALSE; // Couldn't open file
// Retrieve stream information
if (avformat_find_stream_info(pFormatCtx, nullptr) < 0)
return FALSE; // Couldn't find stream information
if (pFormatCtx->pb)
pFormatCtx->pb->eof_reached = 0;
#if defined(_DEBUG) || defined(DEBUG)
// Dump information about file onto standard error
av_dump_format(pFormatCtx, 0, filename, 0);
#endif
// Find the first video stream
int st_index[AVMEDIA_TYPE_NB];
memset(st_index, -1, sizeof(st_index));
for (unsigned int i = 0; i < pFormatCtx->nb_streams; i++)
pFormatCtx->streams[i]->discard = AVDISCARD_ALL;
st_index[AVMEDIA_TYPE_VIDEO] = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
st_index[AVMEDIA_TYPE_AUDIO] = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_AUDIO, -1, st_index[AVMEDIA_TYPE_VIDEO], nullptr, 0);
// Open streams
if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {
stream_component_open(st_index[AVMEDIA_TYPE_AUDIO]);
}
if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
stream_component_open(st_index[AVMEDIA_TYPE_VIDEO]);
}
if (videoStream < 0) {
AssertMsg1(FALSE, "%s: could not open codecs\n", filename);
return FALSE;
}
// Init video scaler
pict_pix_fmt = dst_pix_fmt;
// Allocate frame buffer(s)
for (int i = 0; i < VIDEO_PICTURE_QUEUE_SIZE; ++i)
pictq[i].bmp = pOuter->m_pHostIface->CreateImageBuffer();
#ifdef LGVS_USE_SUBS
subs.initialize(pOuter->m_pHostIface, filename);
#endif // LGVS_NO_SUBS
return TRUE;
}
void Stop();
void Close()
{
Stop();
swr_free(&avr_context);
videoStream = -1;
audioStream = -1;
videoq.Flush();
audioq.Flush();
// Close the codec
if (video_st)
avcodec_close(video_st->codec);
video_st = nullptr;
if (audio_st)
avcodec_close(audio_st->codec);
audio_st = nullptr;
// Close the video file
if (pFormatCtx)
FFmpeg::CloseFile(pFormatCtx);
pFormatCtx = nullptr;
if (img_convert_ctx)
sws_freeContext(img_convert_ctx);
img_convert_ctx = nullptr;
for (int i = 0; i < VIDEO_PICTURE_QUEUE_SIZE; ++i)
pictq[i].bmp = nullptr;
}
BOOL Play();
void video_refresh_timer()
{
VideoPicture *vp;
if (video_st) {
retry:
if (pictq_size == 0) {
schedule_refresh(1);
} else {
double time = av_gettime() / 1000000.0;
double next_target;
/* dequeue the picture */
vp = &pictq[pictq_rindex];
if (time < vp->target_clock)
return;
/* update current video pts */
video_current_pts = vp->pts;
video_current_pts_drift = video_current_pts - time;
video_current_pos = vp->pos;
if (pictq_size > 1) {
VideoPicture *nextvp = &pictq[(pictq_rindex + 1) % VIDEO_PICTURE_QUEUE_SIZE];
Assert_(nextvp->target_clock >= vp->target_clock);
next_target = nextvp->target_clock;
} else {
next_target = vp->target_clock + video_clock - vp->pts; //FIXME pass durations cleanly
}
#define FRAME_SKIP_FACTOR 0.05F
/**/const BOOL framedrop = TRUE;
if (framedrop && time > next_target) {
skip_frames *= 1.0F + FRAME_SKIP_FACTOR;
if (pictq_size > 1 && time > next_target + 0.5) {
/* update queue size and signal for next picture */
if (++pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE)
pictq_rindex = 0;
#ifdef _DEBUG
Warning(("ffmpeg: dropped display frame dt:%g q:%d sf:%g\n", next_target - time, pictq_size, skip_frames));
#endif
pictq_mutex.lock();
pictq_size--;
pictq_cond.notify_one();
pictq_mutex.unlock();
goto retry;
}
}
// show the picture!
#ifdef LGVS_USE_SUBS
if (!subs.has_subtitles()) {
#endif // LGVS_NO_SUBS
pOuter->m_pHostIface->BeginVideoFrame(pictq[pictq_rindex].bmp);
// update queue for next picture!
if (++pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE) {
pictq_rindex = 0;
}
pictq_mutex.lock();
pictq_size--;
pictq_cond.notify_one();
pictq_mutex.unlock();
pOuter->m_pHostIface->EndVideoFrame();
#ifdef LGVS_USE_SUBS
} else
subs.refresh_video = true;
#endif // LGVS_NO_SUBS
}
} else
schedule_refresh(100);
}
double compute_target_time(double frame_current_pts)
{
double delay, sync_threshold, diff;
/* compute nominal delay */
delay = frame_current_pts - frame_last_pts;
if (delay <= 0 || delay >= 10.0) {
/* if incorrect delay, use previous one */
delay = frame_last_delay;
} else {
frame_last_delay = delay;
}
frame_last_pts = frame_current_pts;
/* update delay to follow master synchronisation source */
if (((av_sync_type == AV_SYNC_AUDIO_MASTER && audio_st) ||
av_sync_type == AV_SYNC_EXTERNAL_MASTER)) {
/* if video is slave, we try to correct big delays by
duplicating or deleting a frame */
diff = get_video_clock() - get_master_clock();
/* skip or repeat frame. We take into account the
delay to compute the threshold. I still don't know
if it is the best guess */
sync_threshold = FFMAX(AV_SYNC_THRESHOLD, delay);
if (fabs(diff) < AV_NOSYNC_THRESHOLD) {
if (diff <= -sync_threshold)
delay = 0;
else if (diff >= sync_threshold)
delay = 2 * delay;
}
}
frame_timer += delay;
return frame_timer;
}
void audio_request(unsigned int len)
{
int len1, audio_size = 0;
double pts;
if (!len) {
AudioFinished();
return;
}
while (len > 0) {
if (audio_buf_index >= audio_buf_size) {
/* We have already sent all our data; get more */
audio_size = audio_decode_frame(&pts);
if (audio_size < 0) {
/* If error, output silence */
audio_buf_size = 1024;
memset(audio_buf, 0, audio_buf_size);
} else {
audio_size = synchronize_audio((int16_t *) audio_buf,
audio_size, pts);
audio_buf_size = audio_size;
}
audio_buf_index = 0;
}
len1 = audio_buf_size - audio_buf_index;
if (len1 > (int) len)
len1 = len;
if (len1 > 0)
audio_buf_index += pOuter->m_pHostIface->QueueAudioData(audio_buf + audio_buf_index, len1);
len -= len1;
}
}
private:
int stream_component_open(int stream_index);
/* Add or subtract samples to get a better sync, return new
audio buffer size */
int synchronize_audio(short *samples, int samples_size, double pts)
{
int n;
double ref_clock;
n = 2 * audio_st->codec->channels;
if (av_sync_type != AV_SYNC_AUDIO_MASTER) {
double diff, avg_diff;
int wanted_size, min_size, max_size;
ref_clock = get_master_clock();
diff = get_audio_clock() - ref_clock;
if (diff < AV_NOSYNC_THRESHOLD) {
// accumulate the diffs
audio_diff_cum = diff + audio_diff_avg_coef
* audio_diff_cum;
if (audio_diff_avg_count < AUDIO_DIFF_AVG_NB) {
audio_diff_avg_count++;
} else {
avg_diff = audio_diff_cum * (1.0 - audio_diff_avg_coef);
if (fabs(avg_diff) >= audio_diff_threshold) {
wanted_size = samples_size + ((int) (diff * audio_st->codec->sample_rate) * n);
min_size = samples_size * ((100 - SAMPLE_CORRECTION_PERCENT_MAX) / 100);
max_size = samples_size * ((100 + SAMPLE_CORRECTION_PERCENT_MAX) / 100);
if (wanted_size < min_size) {
wanted_size = min_size;
} else if (wanted_size > max_size) {
wanted_size = max_size;
}
if (wanted_size < samples_size) {
/* remove samples */
samples_size = wanted_size;
} else if (wanted_size > samples_size) {
uint8_t *samples_end, *q;
int nb;
/* add samples by copying final sample*/
nb = (samples_size - wanted_size);
samples_end = (uint8_t *) samples + samples_size - n;
q = samples_end + n;
while (nb > 0) {
memcpy(q, samples_end, n);
q += n;
nb -= n;
}
samples_size = wanted_size;
}
}
}
} else {
/* difference is TOO big; reset diff stuff */
audio_diff_avg_count = 0;
audio_diff_cum = 0;
}
}
return samples_size;
}
int audio_decode_frame(double *pts_ptr)
{
int len1, data_size, n;
AVPacket *pkt = &audio_pkt;
AVPacket *pkt2 = &audio_pkt2;
AVCodecContext *dec = audio_st->codec;
double pts;
int failed_frames = 0;
for (;;) {
while (pkt2->size > 0) {
int got_frame = 0;
len1 = avcodec_decode_audio4(
dec, audio_frame, &got_frame, pkt2);
#ifdef SIMULATE_SLOW_CPU
Sleep(AUDIO_DECODE_STALL);
#endif
if (len1 < 0) {
/* if error, skip frame */
pkt2->size = 0;
// try to avoid inifinite loop if something goes wrong
if (++failed_frames > 512)
return -1;
break;
}
pkt2->data += len1;
pkt2->size -= len1;
if (dec->sample_fmt != audio_src_fmt &&
avr_context == nullptr) {
avr_context = swr_alloc();
auto src_channel_layout = audio_frame->channel_layout;
if (src_channel_layout == 0) {
src_channel_layout = av_get_default_channel_layout(
audio_frame->channels);
}
auto dst_channel_layout =
av_get_default_channel_layout(2);
auto sample_rate = audio_frame->sample_rate;
int av_result = 0;
bool is_succeed = true;
//
av_result = av_opt_set_int(
avr_context,