-
Notifications
You must be signed in to change notification settings - Fork 8
/
DecodeContext.cs
1504 lines (1240 loc) · 46.3 KB
/
DecodeContext.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using Microsoft.Xna.Framework.Audio;
using MonoGame.Extended.Framework.Media;
using MonoGame.Extended.VideoPlayback.AudioDecoding;
using MonoGame.Extended.VideoPlayback.Extensions;
using MonoGame.Extended.VideoPlayback.VideoDecoding;
using Sdcb.FFmpeg.Raw;
namespace MonoGame.Extended.VideoPlayback;
/// <inheritdoc />
/// <summary>
/// The coordinator and core of decoding management.
/// </summary>
internal sealed unsafe class DecodeContext : DisposableBase
{
/// <summary>
/// Creates a new <see cref="DecodeContext"/> instance.
/// </summary>
/// <param name="url">The URL of the video source. If a file system path is provided, make sure it is an absolute path.</param>
/// <param name="decodingOptions">Decoding options.</param>
internal DecodeContext(string url, DecodingOptions decodingOptions)
{
_decodingOptions = decodingOptions;
// 1. Open a format context.
var formatContext = ffmpeg.avformat_alloc_context();
_formatContext = formatContext;
FFmpegHelper.Verify(ffmpeg.avformat_open_input(&formatContext, url, null, null), Dispose);
// 2. Try to read stream information (codec, duration, etc.).
FFmpegHelper.Verify(ffmpeg.avformat_find_stream_info(formatContext, null), Dispose);
// The rest are initialized lazily. See LazyInitialize().
}
/// <summary>
/// Raises when video playback is ended.
/// </summary>
/// <remarks>
/// This event MUST be raised asynchronously.
/// The reason is that subscribers (i.e. <see cref="Framework.Media.Video.decodeContext_Ended"/>) may raise their events synchronously.
/// The call flow can go to <see cref="Framework.Media.VideoPlayer.video_Ended"/>, where <see cref="Framework.Media.VideoPlayer.Stop"/> is called.
/// Inside <see cref="Framework.Media.VideoPlayer.Stop"/>, it calls <see cref="Thread.Join()"/> on <see cref="DecodingThread.SystemThread"/>,
/// which waits for the decoding thread that raises the initial <see cref="Ended"/> event infinitely.
/// So you see, there will be a dead lock if <see cref="Ended"/> is raised synchronously.
/// </remarks>
internal event EventHandler<EventArgs>? Ended;
/// <summary>
/// The underlying <see cref="AVFormatContext"/>.
/// </summary>
[MaybeNull]
internal AVFormatContext* FormatContext
{
[DebuggerStepThrough]
get
{
EnsureNotDisposed();
return _formatContext;
}
}
/// <summary>
/// The <see cref="VideoDecodingContext"/> associated with this <see cref="DecodeContext"/>.
/// May be <see langword="null"/> if there is no video stream.
/// </summary>
internal VideoDecodingContext? VideoContext
{
[DebuggerStepThrough]
get
{
EnsureNotDisposed();
EnsureInitialized();
return _videoContext;
}
}
/// <summary>
/// The <see cref="AudioDecodingContext"/> associated with this <see cref="DecodeContext"/>.
/// May be <see langword="null"/> if there is no audio stream.
/// </summary>
internal AudioDecodingContext? AudioContext
{
[DebuggerStepThrough]
get
{
EnsureNotDisposed();
EnsureInitialized();
return _audioContext;
}
}
/// <summary>
/// The index of the video stream finally selected in the <see cref="AVFormatContext"/>.
/// May be <code>-1</code> if there is no video stream.
/// </summary>
internal int VideoStreamIndex
{
[DebuggerStepThrough]
get
{
EnsureInitialized();
return _videoStreamIndex;
}
}
/// <summary>
/// The index of the audio stream finally selected in the <see cref="AVFormatContext"/>.
/// May be <code>-1</code> if there is no audio stream.
/// </summary>
internal int AudioStreamIndex
{
[DebuggerStepThrough]
get
{
EnsureInitialized();
return _audioStreamIndex;
}
}
/// <summary>
/// Fetches the latest decoded video frame.
/// Remember to lock <see cref="VideoFrameTransmissionLock"/> when you use the fetched frame.
/// </summary>
/// <returns>The latest decoded video frame.</returns>
[return: MaybeNull]
internal AVFrame* FetchAvailableVideoFrame() => _currentVideoFrame;
/// <summary>
/// Name of the video codec.
/// May be <see cref="string.Empty"/> if there is no video stream.
/// </summary>
internal string VideoCodecName
{
[DebuggerStepThrough]
get
{
EnsureInitialized();
return _videoCodecName ?? string.Empty;
}
}
/// <summary>
/// Name of the audio codec.
/// May be <see cref="string.Empty"/> if there is no audio stream.
/// </summary>
internal string AudioCodecName
{
[DebuggerStepThrough]
get
{
EnsureInitialized();
return _audioCodecName ?? string.Empty;
}
}
/// <summary>
/// The index of the video stream user selected.
/// May be <code>-1</code> for auto selection.
/// </summary>
public int UserSelectedVideoStreamIndex
{
[DebuggerStepThrough]
get => _userSelectedVideoStreamIndex;
}
/// <summary>
/// The index of the audio stream user selected.
/// May be <code>-1</code> for auto selection.
/// </summary>
public int UserSelectedAudioStreamIndex
{
[DebuggerStepThrough]
get => _userSelectedAudioStreamIndex;
}
/// <summary>
/// Whether auto looping is enabled.
/// </summary>
internal bool IsLooped
{
[DebuggerStepThrough]
get => _isLooped;
[DebuggerStepThrough]
set
{
_isLooped = value;
if (!value)
{
_currentLoopNumber = 0;
}
}
}
/// <summary>
/// Gets the number of all types of streams in the media file.
/// </summary>
/// <returns>Number of all type of streams.</returns>
internal int GetTotalStreamCount()
{
return (int)_formatContext->nb_streams;
}
/// <summary>
/// Gets the number of video streams in the media file.
/// </summary>
/// <returns>Number of video streams.</returns>
internal int GetVideoStreamCount()
{
var count = 0;
for (var i = 0; i < _formatContext->nb_streams; ++i)
{
var avStream = _formatContext->streams[i];
if (avStream->codecpar->codec_type == AVMediaType.Video)
{
++count;
}
}
return count;
}
/// <summary>
/// Gets the number of audio streams in the media file.
/// </summary>
/// <returns>Number of audio streams.</returns>
internal int GetAudioStreamCount()
{
var count = 0;
for (var i = 0; i < _formatContext->nb_streams; ++i)
{
var avStream = _formatContext->streams[i];
if (avStream->codecpar->codec_type == AVMediaType.Audio)
{
++count;
}
}
return count;
}
/// <summary>
/// Selects a video stream by index.
/// This method is only valid before initialization.
/// </summary>
/// <param name="streamIndex">The index of video streams.</param>
internal void SelectVideoStream(int streamIndex)
{
if (_isInitialized)
{
return;
}
var totalStreams = GetTotalStreamCount();
if (streamIndex >= totalStreams)
{
streamIndex = -1;
}
_userSelectedVideoStreamIndex = streamIndex;
}
/// <summary>
/// Selects an audio stream by index.
/// This method is only valid before initialization.
/// </summary>
/// <param name="streamIndex">The index of audio streams.</param>
internal void SelectAudioStream(int streamIndex)
{
if (_isInitialized)
{
return;
}
var totalStreams = GetTotalStreamCount();
if (streamIndex >= totalStreams)
{
streamIndex = -1;
}
_userSelectedAudioStreamIndex = streamIndex;
}
/// <summary>
/// Forces initializing <see cref="DecodeContext"/> before it is automatically initialized by calling specific methods.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void Initialize()
{
EnsureInitialized();
}
/// <summary>
/// Reset the state of this <see cref="DecodeContext"/> for restarting playback.
/// </summary>
internal void Reset()
{
EnsureInitialized();
// This method may be called in Dispose() so no EnsureNotDisposed() call here.
LockFrameQueuesUpdate();
try
{
ResetBeforeSeek();
// When playing large video files, independently seeking audio and video streams
// causes error number -11 thrown in TryFetchVideoFrames at first several (sometimes more than 40) frames.
// But using the index -1 (seeking all streams at the same time) works...
if (VideoStreamIndex >= 0 || AudioStreamIndex >= 0)
{
FFmpegHelper.Verify(ffmpeg.av_seek_frame(FormatContext, -1, 0, (int)AVSEEK_FLAG.Backward), Dispose);
}
ResetAfterSeek();
}
finally
{
UnlockFrameQueueUpdate();
}
}
/// <summary>
/// Seek to the specified time. If the time is out of video range, it calls <see cref="Reset"/>.
/// </summary>
/// <param name="timeInSeconds">Target time in seconds.</param>
internal void Seek(double timeInSeconds)
{
Seek(timeInSeconds, true);
}
/// <summary>
/// Seek to the specified time. If the time is out of video range, it calls <see cref="Reset"/>.
/// </summary>
/// <param name="timeInSeconds">Target time in seconds.</param>
/// <param name="pseudoReset">Whether reset decoding state.</param>
private void Seek(double timeInSeconds, bool pseudoReset)
{
EnsureNotDisposed();
EnsureInitialized();
// Normal playback seeking behavior
if (!IsLooped)
{
if (timeInSeconds <= 0 || timeInSeconds >= GetDurationInSeconds())
{
Reset();
return;
}
}
LockFrameQueuesUpdate();
try
{
if (pseudoReset)
{
ResetBeforeSeek();
}
AVSEEK_FLAG seekFlags = 0;
if (_nextDecodingVideoTime > timeInSeconds)
{
seekFlags |= AVSEEK_FLAG.Backward;
}
if (VideoStreamIndex >= 0 || AudioStreamIndex >= 0)
{
var timestamp = FFmpegHelper.ConvertSecondsToPts(timeInSeconds);
FFmpegHelper.Verify(ffmpeg.av_seek_frame(FormatContext, -1, timestamp, (int)seekFlags), Dispose);
}
if (pseudoReset)
{
ResetAfterSeek();
}
}
finally
{
UnlockFrameQueueUpdate();
}
}
/// <summary>
/// Gets the duration of the video file, in seconds.
/// </summary>
/// <returns>The duration of the video file, in seconds.</returns>
internal double GetDurationInSeconds()
{
if (_duration == null)
{
// Duration info can be retrieved without initialization, so no need to call EnsureInitialized().
EnsureNotDisposed();
_duration = FFmpegHelper.GetDurationInSeconds(_formatContext);
}
return _duration.Value;
}
/// <summary>
/// Reads video packets and decode them into video frames, until presentation time of the frame decoded is after specified time.
/// </summary>
/// <param name="presentationTime">Current playback time, in seconds.</param>
internal void ReadVideoUntilPlaybackIsAfter(double presentationTime)
{
EnsureNotDisposed();
EnsureInitialized();
// If we don't have to decode any new frame (just use the current one), skip the later procedures.
if (_nextDecodingVideoTime > presentationTime)
{
return;
}
var videoContext = _videoContext;
var videoStream = _videoStream;
var framePool = _videoFramePool;
var frameQueue = _preparedVideoFrames;
var videoPackets = _videoPackets;
if (videoContext == null || videoStream == null || framePool == null || frameQueue == null || videoPackets == null)
{
return;
}
bool r;
double decodedPresentationTime = 0;
// The double queue + object pool design is used to solve the I/P/B frame order problem.
// For details about I/P/B frames, see http://dranger.com/ffmpeg/tutorial05.html.
do
{
// Try to fetch a number of video frames.
r = TryFetchVideoFrames(_decodingOptions.VideoPacketQueueSizeThreshold);
if (r)
{
// If the queue of decoded frames is not empty, then get its presentation timestamp (PTS) and convert it to seconds.
var decodedPresentationPts = frameQueue.PeekFirstKey();
decodedPresentationTime = PtsToSeconds(videoStream, decodedPresentationPts + _videoStartPts);
// Now get the frame.
var p = frameQueue.Dequeue();
var frame = (AVFrame*)p;
if (decodedPresentationTime < presentationTime)
{
// If the time is before current playback time, release the frame because we don't need it anymore.
framePool.Release(p);
}
else
{
// Otherwise, set it as the current frame.
lock (VideoFrameTransmissionLock)
{
var origFrame = _currentVideoFrame;
_currentVideoFrame = frame;
if (origFrame != null)
{
framePool.Release((IntPtr)origFrame);
}
}
}
// Caveats:
// The "current" frame is actually the first frame whose PTS is after current playback time.
// But for most videos, this does not matter.
// We can make it a little more complicated (queries if there is a second frame in the sorted list)
// to get the actual "current" frame.
}
}
while (r && decodedPresentationTime < presentationTime);
// If we did get a frame to show, then update the time.
if (r)
{
_nextDecodingVideoTime = decodedPresentationTime;
}
// If the video stream ends, raise Ended event.
if (!r && videoPackets.Count == 0)
{
if (IsLooped)
{
++_currentLoopNumber;
// About avcodec_flush_buffers:
// https://ffmpeg.org/doxygen/3.1/group__lavc__encdec.html
if (_videoContext != null)
{
ffmpeg.avcodec_flush_buffers(_videoContext.CodecContext);
}
if (_audioContext != null)
{
ffmpeg.avcodec_flush_buffers(_audioContext.CodecContext);
}
Seek(0, false);
}
else
{
if (!_isEndedTriggered)
{
// Must use BeginInvoke. See the explanations of Ended.
Ended?.BeginInvoke(this, EventArgs.Empty, null, null);
// var thread = new Thread(thisObject => {
// var context = (DecodeContext)thisObject;
// context.Ended?.Invoke(context, EventArgs.Empty);
// });
// thread.Start(this);
_isEndedTriggered = true;
}
}
}
}
/// <summary>
/// Reads audio packets, decode them into audio frames and send the data to an <see cref="DynamicSoundEffectInstance"/>, until presentation time of the frame decoded is after specified time.
/// </summary>
/// <param name="sound">The <see cref="DynamicSoundEffectInstance"/> to play audio data.</param>
/// <param name="presentationTime">Current playback time, in seconds.</param>
internal void ReadAudioUntilPlaybackIsAfter(DynamicSoundEffectInstance sound, double presentationTime)
{
EnsureNotDisposed();
EnsureInitialized();
var audioContext = _audioContext;
var audioStream = _audioStream;
var audioFrame = _audioFrame;
var extraAudioBufferingTime = (float)_decodingOptions.ExtraAudioBufferingTime / 1000;
if (audioContext == null || audioStream == null || audioFrame == null)
{
return;
}
using (var memoryStream = new MemoryStream())
{
// We want there is as much data in one audio buffer as possible, so that we don't have to allocate too many audio buffers.
// dataPushed is used for this task.
var dataPushed = false;
var fetchFramesPlease = true;
{
var pts = audioFrame->best_effort_timestamp;
var framePresentationTime = PtsToSeconds(audioStream, pts + _audioStartPts);
if (framePresentationTime > presentationTime + extraAudioBufferingTime)
{
// If our time has not come, skip the rest of the procedures.
fetchFramesPlease = false;
}
else
{
// Otherwise prepare to send the first lump of data.
if (FFmpegHelper.TransmitAudioFrame(this, audioFrame, out var buffer))
{
if (buffer != null)
{
memoryStream.Write(buffer, 0, buffer.Length);
dataPushed = true;
}
}
}
}
if (fetchFramesPlease)
{
// Fetch audio frames until its presentation timestamp (PTS) is later than current playback time.
// Prepare to send all the data received during this procedure.
while (TryFetchAudioFrame(audioFrame))
{
if (audioFrame->nb_samples == 0)
{
continue;
}
var pts = audioFrame->best_effort_timestamp;
var framePresentationTime = PtsToSeconds(audioStream, pts + _audioStartPts);
if (framePresentationTime > presentationTime + extraAudioBufferingTime)
{
break;
}
if (FFmpegHelper.TransmitAudioFrame(this, audioFrame, out var buffer))
{
if (buffer != null)
{
memoryStream.Write(buffer, 0, buffer.Length);
dataPushed = true;
}
}
}
}
// If there is data pushed...
if (dataPushed)
{
var audioData = memoryStream.ToArray();
// ... send the data to OpenAL's audio buffer...
// TODO: XAudio2 0x88960001?
sound.SubmitBuffer(audioData);
// ... and play it.
if (sound.State == SoundState.Stopped)
{
sound.Play();
}
}
}
}
/// <summary>
/// The lock object used to avoid unwanted frame data overwrites.
/// </summary>
internal readonly object VideoFrameTransmissionLock = new object();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void LockFrameQueuesUpdate()
{
Monitor.Enter(_frameQueueUpdateLock);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void UnlockFrameQueueUpdate()
{
Monitor.Exit(_frameQueueUpdateLock);
}
protected override void Dispose(bool disposing)
{
// Prevents initializing after disposal
_isInitialized = true;
Reset();
// Video frames are allocated by a frame pool. So we don't need to dispose it here.
_currentVideoFrame = null;
_videoFramePool?.Dispose();
_videoFramePool = null;
if (_audioFrame != null)
{
var audioFrame = _audioFrame;
ffmpeg.av_frame_free(&audioFrame);
_audioFrame = null;
}
_videoStream = null;
_audioStream = null;
_videoContext?.Dispose();
_audioContext?.Dispose();
_videoContext = null;
_audioContext = null;
if (_formatContext != null)
{
ffmpeg.avformat_free_context(_formatContext);
_formatContext = null;
}
}
/// <summary>
/// Tries to get the next video packet.
/// </summary>
/// <param name="packet">The packet got, or an empty packet if the operation fails.</param>
/// <returns><see langword="true"/> if the operation succeeds, otherwise <see langword="false"/>.</returns>
private bool TryGetNextVideoPacket([MaybeNullWhen(false)] out Packet packet)
{
EnsureNotDisposed();
var queue = _videoPackets;
Debug.Assert(queue != null, nameof(queue) + " != null");
if (!TryFillPacketQueue(queue, _decodingOptions.VideoPacketQueueSizeThreshold))
{
if (queue.Count == 0)
{
packet = default;
return false;
}
}
packet = queue.Dequeue();
return true;
}
/// <summary>
/// Tries to get the next audio packet.
/// </summary>
/// <param name="packet">The packet got, or an empty packet if the operation fails.</param>
/// <returns><see langword="true"/> if the operation succeeds, otherwise <see langword="false"/>.</returns>
private bool TryGetNextAudioPacket([MaybeNullWhen(false)] out Packet packet)
{
EnsureNotDisposed();
var queue = _audioPackets;
Debug.Assert(queue != null, nameof(queue) + " != null");
if (!TryFillPacketQueue(queue, _decodingOptions.AudioPacketQueueSizeThreshold))
{
if (queue.Count == 0)
{
packet = default;
return false;
}
}
packet = queue.Dequeue();
return true;
}
/// <summary>
/// Tries to fill a <see cref="PacketQueue"/> until the number of queued packets reaches expected count.
/// </summary>
/// <param name="queue">The packet queue to fill.</param>
/// <param name="count">Expected count.</param>
/// <returns><see langword="true"/> if the queue has at least expected number of items when the function returns, otherwise <see langword="false"/>.</returns>
private bool TryFillPacketQueue(PacketQueue queue, int count)
{
while (queue.Count < count)
{
if (!ReadNextPacket())
{
return false;
}
}
return true;
}
/// <summary>
/// Tries to decode and fetch some video frames, and store them in the video frame queue.
/// </summary>
/// <param name="count">Expected count of the frame queue, after fetching video frames.</param>
/// <returns><see langword="true"/> if the video frame queue has at least one frame when the function returns, otherwise <see langword="false"/>.</returns>
private bool TryFetchVideoFrames(int count)
{
EnsureNotDisposed();
if (_videoContext is null)
{
return false;
}
var avStream = _videoContext.VideoStream;
var codecContext = _videoContext.CodecContext;
var frameQueue = _preparedVideoFrames;
var framePool = _videoFramePool;
Debug.Assert(frameQueue != null && framePool != null);
Packet? packet = null;
try
{
packet = new Packet(_currentLoopNumber);
while (frameQueue.Count < count)
{
var decodingSuccessful = false;
while (true)
{
packet?.Dispose();
if (!TryGetNextVideoPacket(out packet))
{
break;
}
if (packet.RawPacket->size == 0)
{
break;
}
var videoTime = PtsToSeconds(avStream, packet.GetRobustTimestamp() + _videoStartPts);
if (videoTime < 0)
{
break;
}
// About avcodec_send_packet and avcodec_receive_frame:
// https://ffmpeg.org/doxygen/3.1/group__lavc__encdec.html
// First we send a video packet.
var error = ffmpeg.avcodec_send_packet(codecContext, packet.RawPacket);
if (error != 0)
{
if (error == ffmpeg.AVERROR_EOF)
{
// End of video, maybe some other buffered frames.
error = ffmpeg.avcodec_send_packet(codecContext, null);
if (error != 0)
{
if (error == ffmpeg.AVERROR_EOF)
{
// Go on.
}
else
{
FFmpegHelper.Verify(error, Dispose);
}
}
}
else
{
FFmpegHelper.Verify(error, Dispose);
}
}
var frame = (AVFrame*)framePool.Acquire();
// Then we receive the decoded frame.
error = ffmpeg.avcodec_receive_frame(codecContext, frame);
var bestEffortPts = frame->best_effort_timestamp;
if (error == 0)
{
// If everything goes well, then again, lucky us.
packet.Dispose();
// Fix duplicate key (why does this happen?)
if (frameQueue.ContainsKey(bestEffortPts))
{
// Drop the old frame and put it back to the pool.
frameQueue.TryGetValue(bestEffortPts, out var oldFramePtr);
frameQueue.Remove(bestEffortPts);
framePool.Release(oldFramePtr);
}
frameQueue.Enqueue(bestEffortPts, (IntPtr)frame);
decodingSuccessful = true;
break;
}
else
{
// If this packet contains multiple frames, we have to enqueue all those frames.
if (error == ffmpeg.EAGAIN)
{
frameQueue.Enqueue(bestEffortPts, (IntPtr)frame);
decodingSuccessful = true;
}
while (error == ffmpeg.EAGAIN)
{
frame = (AVFrame*)framePool.Acquire();
error = ffmpeg.avcodec_receive_frame(codecContext, frame);
decodingSuccessful = true;
if (error >= 0)
{
frameQueue.Enqueue(bestEffortPts, (IntPtr)frame);
}
}
// If an error occurs, release the frame we acquired because its data will not be used by now.
if (error < 0)
{
framePool.Release((IntPtr)frame);
}
if (error == ffmpeg.AVERROR_EOF)
{
// Go on.
}
else if (error == -11)
{
// Device not ready; don't know why this happens.
}
else
{
FFmpegHelper.Verify(error, Dispose);
}
}
}
if (!decodingSuccessful)
{
break;
}
}
}
finally
{
packet?.Dispose();
}
return frameQueue.Count > 0;
}
/// <summary>
/// Tries to decode and fetch an audio frame and fill the data in given <see cref="AVFrame"/>.
/// </summary>
/// <param name="frame">The frame which stores the data.</param>
/// <returns><see langword="true"/> if the operation succeeds, otherwise <see langword="false"/>.</returns>
private bool TryFetchAudioFrame([JetBrains.Annotations.NotNull] AVFrame* frame)
{
EnsureNotDisposed();
if (_audioContext == null)
{
return false;
}
var avStream = _audioContext.AudioStream;
var codecContext = _audioContext.CodecContext;
// If we were decoding audio packets, and the last packets is not fully consumed yet,
// then try to receive one more frame.
if (_audioPacketDecodingOngoing)
{
var error = ffmpeg.avcodec_receive_frame(codecContext, frame);
if (error == 0)
{
return true;
}
else
{
_audioPacketDecodingOngoing = false;
if (error == ffmpeg.AVERROR_EOF)
{
return false;
}
}
}
Packet? packet = null;
try
{
packet = new Packet(_currentLoopNumber);
// Other logics are similar to those in TryFetchVideoFrames.
while (true)
{
packet.Dispose();
if (!TryGetNextAudioPacket(out packet))
{
break;
}