2 * An example showing how to play a stream sync'd to video, using ffmpeg.
7 #include <condition_variable>
23 #include "libavcodec/avcodec.h"
24 #include "libavformat/avformat.h"
25 #include "libavformat/avio.h"
26 #include "libavutil/time.h"
27 #include "libavutil/pixfmt.h"
28 #include "libavutil/avstring.h"
29 #include "libavutil/channel_layout.h"
30 #include "libswscale/swscale.h"
31 #include "libswresample/swresample.h"
41 #ifndef AL_SOFT_map_buffer
42 #define AL_SOFT_map_buffer 1
43 typedef unsigned int ALbitfieldSOFT
;
44 #define AL_MAP_READ_BIT_SOFT 0x00000001
45 #define AL_MAP_WRITE_BIT_SOFT 0x00000002
46 #define AL_MAP_PERSISTENT_BIT_SOFT 0x00000004
47 #define AL_PRESERVE_DATA_BIT_SOFT 0x00000008
48 typedef void (AL_APIENTRY
*LPALBUFFERSTORAGESOFT
)(ALuint buffer
, ALenum format
, const ALvoid
*data
, ALsizei size
, ALsizei freq
, ALbitfieldSOFT flags
);
49 typedef void* (AL_APIENTRY
*LPALMAPBUFFERSOFT
)(ALuint buffer
, ALsizei offset
, ALsizei length
, ALbitfieldSOFT access
);
50 typedef void (AL_APIENTRY
*LPALUNMAPBUFFERSOFT
)(ALuint buffer
);
51 typedef void (AL_APIENTRY
*LPALFLUSHMAPPEDBUFFERSOFT
)(ALuint buffer
, ALsizei offset
, ALsizei length
);
54 #ifndef AL_SOFT_events
55 #define AL_SOFT_events 1
56 #define AL_EVENT_CALLBACK_FUNCTION_SOFT 0x1220
57 #define AL_EVENT_CALLBACK_USER_PARAM_SOFT 0x1221
58 #define AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT 0x1222
59 #define AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT 0x1223
60 #define AL_EVENT_TYPE_ERROR_SOFT 0x1224
61 #define AL_EVENT_TYPE_PERFORMANCE_SOFT 0x1225
62 #define AL_EVENT_TYPE_DEPRECATED_SOFT 0x1226
63 typedef void (AL_APIENTRY
*ALEVENTPROCSOFT
)(ALenum eventType
, ALuint object
, ALuint param
,
64 ALsizei length
, const ALchar
*message
,
66 typedef void (AL_APIENTRY
*LPALEVENTCONTROLSOFT
)(ALsizei count
, const ALenum
*types
, ALboolean enable
);
67 typedef void (AL_APIENTRY
*LPALEVENTCALLBACKSOFT
)(ALEVENTPROCSOFT callback
, void *userParam
);
68 typedef void* (AL_APIENTRY
*LPALGETPOINTERSOFT
)(ALenum pname
);
69 typedef void (AL_APIENTRY
*LPALGETPOINTERVSOFT
)(ALenum pname
, void **values
);
75 using nanoseconds
= std::chrono::nanoseconds
;
76 using microseconds
= std::chrono::microseconds
;
77 using milliseconds
= std::chrono::milliseconds
;
78 using seconds
= std::chrono::seconds
;
79 using seconds_d64
= std::chrono::duration
<double>;
81 const std::string
AppName("alffplay");
83 bool EnableDirectOut
= false;
84 LPALGETSOURCEI64VSOFT alGetSourcei64vSOFT
;
85 LPALCGETINTEGER64VSOFT alcGetInteger64vSOFT
;
87 LPALBUFFERSTORAGESOFT alBufferStorageSOFT
;
88 LPALMAPBUFFERSOFT alMapBufferSOFT
;
89 LPALUNMAPBUFFERSOFT alUnmapBufferSOFT
;
91 LPALEVENTCONTROLSOFT alEventControlSOFT
;
92 LPALEVENTCALLBACKSOFT alEventCallbackSOFT
;
94 const seconds
AVNoSyncThreshold(10);
96 const milliseconds
VideoSyncThreshold(10);
97 #define VIDEO_PICTURE_QUEUE_SIZE 16
99 const seconds_d64
AudioSyncThreshold(0.03);
100 const milliseconds
AudioSampleCorrectionMax(50);
101 /* Averaging filter coefficient for audio sync. */
102 #define AUDIO_DIFF_AVG_NB 20
103 const double AudioAvgFilterCoeff
= std::pow(0.01, 1.0/AUDIO_DIFF_AVG_NB
);
104 /* Per-buffer size, in time */
105 const milliseconds
AudioBufferTime(20);
106 /* Buffer total size, in time (should be divisible by the buffer time) */
107 const milliseconds
AudioBufferTotalTime(800);
109 #define MAX_QUEUE_SIZE (15 * 1024 * 1024) /* Bytes of compressed data to keep queued */
112 FF_UPDATE_EVENT
= SDL_USEREVENT
,
117 enum class SyncMaster
{
126 inline microseconds
get_avtime()
127 { return microseconds(av_gettime()); }
129 /* Define unique_ptrs to auto-cleanup associated ffmpeg objects. */
130 struct AVIOContextDeleter
{
131 void operator()(AVIOContext
*ptr
) { avio_closep(&ptr
); }
133 using AVIOContextPtr
= std::unique_ptr
<AVIOContext
,AVIOContextDeleter
>;
135 struct AVFormatCtxDeleter
{
136 void operator()(AVFormatContext
*ptr
) { avformat_close_input(&ptr
); }
138 using AVFormatCtxPtr
= std::unique_ptr
<AVFormatContext
,AVFormatCtxDeleter
>;
140 struct AVCodecCtxDeleter
{
141 void operator()(AVCodecContext
*ptr
) { avcodec_free_context(&ptr
); }
143 using AVCodecCtxPtr
= std::unique_ptr
<AVCodecContext
,AVCodecCtxDeleter
>;
145 struct AVFrameDeleter
{
146 void operator()(AVFrame
*ptr
) { av_frame_free(&ptr
); }
148 using AVFramePtr
= std::unique_ptr
<AVFrame
,AVFrameDeleter
>;
150 struct SwrContextDeleter
{
151 void operator()(SwrContext
*ptr
) { swr_free(&ptr
); }
153 using SwrContextPtr
= std::unique_ptr
<SwrContext
,SwrContextDeleter
>;
155 struct SwsContextDeleter
{
156 void operator()(SwsContext
*ptr
) { sws_freeContext(ptr
); }
158 using SwsContextPtr
= std::unique_ptr
<SwsContext
,SwsContextDeleter
>;
162 std::deque
<AVPacket
> mPackets
;
163 size_t mTotalSize
{0};
166 ~PacketQueue() { clear(); }
168 bool empty() const noexcept
{ return mPackets
.empty(); }
169 size_t totalSize() const noexcept
{ return mTotalSize
; }
171 void put(const AVPacket
*pkt
)
173 mPackets
.push_back(AVPacket
{});
174 if(av_packet_ref(&mPackets
.back(), pkt
) != 0)
177 mTotalSize
+= mPackets
.back().size
;
180 AVPacket
*front() noexcept
181 { return &mPackets
.front(); }
185 AVPacket
*pkt
= &mPackets
.front();
186 mTotalSize
-= pkt
->size
;
187 av_packet_unref(pkt
);
188 mPackets
.pop_front();
193 for(AVPacket
&pkt
: mPackets
)
194 av_packet_unref(&pkt
);
206 AVStream
*mStream
{nullptr};
207 AVCodecCtxPtr mCodecCtx
;
209 std::mutex mQueueMtx
;
210 std::condition_variable mQueueCond
;
212 /* Used for clock difference average computation */
213 seconds_d64 mClockDiffAvg
{0};
215 /* Time of the next sample to be buffered */
216 nanoseconds mCurrentPts
{0};
218 /* Device clock time that the stream started at. */
219 nanoseconds mDeviceStartTime
{nanoseconds::min()};
221 /* Decompressed sample frame, and swresample context for conversion */
222 AVFramePtr mDecodedFrame
;
223 SwrContextPtr mSwresCtx
;
225 /* Conversion format, for what gets fed to OpenAL */
226 int mDstChanLayout
{0};
227 AVSampleFormat mDstSampleFmt
{AV_SAMPLE_FMT_NONE
};
229 /* Storage of converted samples */
230 uint8_t *mSamples
{nullptr};
231 int mSamplesLen
{0}; /* In samples */
236 ALenum mFormat
{AL_NONE
};
237 ALsizei mFrameSize
{0};
239 std::mutex mSrcMutex
;
241 std::vector
<ALuint
> mBuffers
;
242 ALsizei mBufferIdx
{0};
244 AudioState(MovieState
&movie
) : mMovie(movie
)
249 alDeleteSources(1, &mSource
);
250 if(!mBuffers
.empty())
251 alDeleteBuffers(mBuffers
.size(), mBuffers
.data());
256 static void AL_APIENTRY
EventCallback(ALenum eventType
, ALuint object
, ALuint param
,
257 ALsizei length
, const ALchar
*message
,
260 nanoseconds
getClockNoLock();
261 nanoseconds
getClock()
263 std::lock_guard
<std::mutex
> lock(mSrcMutex
);
264 return getClockNoLock();
267 bool isBufferFilled();
268 void startPlayback();
272 bool readAudio(uint8_t *samples
, int length
);
280 AVStream
*mStream
{nullptr};
281 AVCodecCtxPtr mCodecCtx
;
283 std::mutex mQueueMtx
;
284 std::condition_variable mQueueCond
;
286 nanoseconds mClock
{0};
287 nanoseconds mFrameTimer
{0};
288 nanoseconds mFrameLastPts
{0};
289 nanoseconds mFrameLastDelay
{0};
290 nanoseconds mCurrentPts
{0};
291 /* time (av_gettime) at which we updated mCurrentPts - used to have running video pts */
292 microseconds mCurrentPtsTime
{0};
294 /* Decompressed video frame, and swscale context for conversion */
295 AVFramePtr mDecodedFrame
;
296 SwsContextPtr mSwscaleCtx
;
299 SDL_Texture
*mImage
{nullptr};
300 int mWidth
{0}, mHeight
{0}; /* Logical image size (actual size may be larger) */
301 std::atomic
<bool> mUpdated
{false};
307 SDL_DestroyTexture(mImage
);
311 std::array
<Picture
,VIDEO_PICTURE_QUEUE_SIZE
> mPictQ
;
312 size_t mPictQSize
{0}, mPictQRead
{0}, mPictQWrite
{0};
313 std::mutex mPictQMutex
;
314 std::condition_variable mPictQCond
;
315 bool mFirstUpdate
{true};
316 std::atomic
<bool> mEOS
{false};
317 std::atomic
<bool> mFinalUpdate
{false};
319 VideoState(MovieState
&movie
) : mMovie(movie
) { }
321 nanoseconds
getClock();
322 bool isBufferFilled();
324 static Uint32 SDLCALL
sdl_refresh_timer_cb(Uint32 interval
, void *opaque
);
325 void schedRefresh(milliseconds delay
);
326 void display(SDL_Window
*screen
, SDL_Renderer
*renderer
);
327 void refreshTimer(SDL_Window
*screen
, SDL_Renderer
*renderer
);
328 void updatePicture(SDL_Window
*screen
, SDL_Renderer
*renderer
);
329 int queuePicture(nanoseconds pts
);
334 AVIOContextPtr mIOContext
;
335 AVFormatCtxPtr mFormatCtx
;
337 SyncMaster mAVSyncType
{SyncMaster::Default
};
339 microseconds mClockBase
{0};
340 std::atomic
<bool> mPlaying
{false};
343 std::condition_variable mSendCond
;
344 /* NOTE: false/clear = need data, true/set = no data needed */
345 std::atomic_flag mSendDataGood
;
347 std::atomic
<bool> mQuit
{false};
352 std::thread mParseThread
;
353 std::thread mAudioThread
;
354 std::thread mVideoThread
;
356 std::string mFilename
;
358 MovieState(std::string fname
)
359 : mAudio(*this), mVideo(*this), mFilename(std::move(fname
))
364 if(mParseThread
.joinable())
368 static int decode_interrupt_cb(void *ctx
);
370 void setTitle(SDL_Window
*window
);
372 nanoseconds
getClock();
374 nanoseconds
getMasterClock();
376 nanoseconds
getDuration();
378 int streamComponentOpen(int stream_index
);
383 nanoseconds
AudioState::getClockNoLock()
385 // The audio clock is the timestamp of the sample currently being heard.
386 if(alcGetInteger64vSOFT
)
388 // If device start time = min, we aren't playing yet.
389 if(mDeviceStartTime
== nanoseconds::min())
390 return nanoseconds::zero();
392 // Get the current device clock time and latency.
393 auto device
= alcGetContextsDevice(alcGetCurrentContext());
394 ALCint64SOFT devtimes
[2] = {0,0};
395 alcGetInteger64vSOFT(device
, ALC_DEVICE_CLOCK_LATENCY_SOFT
, 2, devtimes
);
396 auto latency
= nanoseconds(devtimes
[1]);
397 auto device_time
= nanoseconds(devtimes
[0]);
399 // The clock is simply the current device time relative to the recorded
400 // start time. We can also subtract the latency to get more a accurate
401 // position of where the audio device actually is in the output stream.
402 return device_time
- mDeviceStartTime
- latency
;
405 /* The source-based clock is based on 4 components:
406 * 1 - The timestamp of the next sample to buffer (mCurrentPts)
407 * 2 - The length of the source's buffer queue
408 * (AudioBufferTime*AL_BUFFERS_QUEUED)
409 * 3 - The offset OpenAL is currently at in the source (the first value
410 * from AL_SAMPLE_OFFSET_LATENCY_SOFT)
411 * 4 - The latency between OpenAL and the DAC (the second value from
412 * AL_SAMPLE_OFFSET_LATENCY_SOFT)
414 * Subtracting the length of the source queue from the next sample's
415 * timestamp gives the timestamp of the sample at the start of the source
416 * queue. Adding the source offset to that results in the timestamp for the
417 * sample at OpenAL's current position, and subtracting the source latency
418 * from that gives the timestamp of the sample currently at the DAC.
420 nanoseconds pts
= mCurrentPts
;
423 ALint64SOFT offset
[2];
427 /* NOTE: The source state must be checked last, in case an underrun
428 * occurs and the source stops between retrieving the offset+latency
429 * and getting the state. */
430 if(alGetSourcei64vSOFT
)
431 alGetSourcei64vSOFT(mSource
, AL_SAMPLE_OFFSET_LATENCY_SOFT
, offset
);
435 alGetSourcei(mSource
, AL_SAMPLE_OFFSET
, &ioffset
);
436 offset
[0] = (ALint64SOFT
)ioffset
<< 32;
439 alGetSourcei(mSource
, AL_BUFFERS_QUEUED
, &queued
);
440 alGetSourcei(mSource
, AL_SOURCE_STATE
, &status
);
442 /* If the source is AL_STOPPED, then there was an underrun and all
443 * buffers are processed, so ignore the source queue. The audio thread
444 * will put the source into an AL_INITIAL state and clear the queue
445 * when it starts recovery. */
446 if(status
!= AL_STOPPED
)
448 using fixed32
= std::chrono::duration
<int64_t,std::ratio
<1,(1ll<<32)>>;
450 pts
-= AudioBufferTime
*queued
;
451 pts
+= std::chrono::duration_cast
<nanoseconds
>(
452 fixed32(offset
[0] / mCodecCtx
->sample_rate
)
455 /* Don't offset by the latency if the source isn't playing. */
456 if(status
== AL_PLAYING
)
457 pts
-= nanoseconds(offset
[1]);
460 return std::max(pts
, nanoseconds::zero());
463 bool AudioState::isBufferFilled()
465 /* All of OpenAL's buffer queueing happens under the mSrcMutex lock, as
466 * does the source gen. So when we're able to grab the lock and the source
467 * is valid, the queue must be full.
469 std::lock_guard
<std::mutex
> lock(mSrcMutex
);
473 void AudioState::startPlayback()
475 alSourcePlay(mSource
);
476 if(alcGetInteger64vSOFT
)
478 using fixed32
= std::chrono::duration
<int64_t,std::ratio
<1,(1ll<<32)>>;
480 // Subtract the total buffer queue time from the current pts to get the
481 // pts of the start of the queue.
482 nanoseconds startpts
= mCurrentPts
- AudioBufferTotalTime
;
483 int64_t srctimes
[2]={0,0};
484 alGetSourcei64vSOFT(mSource
, AL_SAMPLE_OFFSET_CLOCK_SOFT
, srctimes
);
485 auto device_time
= nanoseconds(srctimes
[1]);
486 auto src_offset
= std::chrono::duration_cast
<nanoseconds
>(fixed32(srctimes
[0])) /
487 mCodecCtx
->sample_rate
;
489 // The mixer may have ticked and incremented the device time and sample
490 // offset, so subtract the source offset from the device time to get
491 // the device time the source started at. Also subtract startpts to get
492 // the device time the stream would have started at to reach where it
494 mDeviceStartTime
= device_time
- src_offset
- startpts
;
498 int AudioState::getSync()
500 if(mMovie
.mAVSyncType
== SyncMaster::Audio
)
503 auto ref_clock
= mMovie
.getMasterClock();
504 auto diff
= ref_clock
- getClockNoLock();
506 if(!(diff
< AVNoSyncThreshold
&& diff
> -AVNoSyncThreshold
))
508 /* Difference is TOO big; reset accumulated average */
509 mClockDiffAvg
= seconds_d64::zero();
513 /* Accumulate the diffs */
514 mClockDiffAvg
= mClockDiffAvg
*AudioAvgFilterCoeff
+ diff
;
515 auto avg_diff
= mClockDiffAvg
*(1.0 - AudioAvgFilterCoeff
);
516 if(avg_diff
< AudioSyncThreshold
/2.0 && avg_diff
> -AudioSyncThreshold
)
519 /* Constrain the per-update difference to avoid exceedingly large skips */
520 diff
= std::min
<nanoseconds
>(std::max
<nanoseconds
>(diff
, -AudioSampleCorrectionMax
),
521 AudioSampleCorrectionMax
);
522 return (int)std::chrono::duration_cast
<seconds
>(diff
*mCodecCtx
->sample_rate
).count();
525 int AudioState::decodeFrame()
527 while(!mMovie
.mQuit
.load(std::memory_order_relaxed
))
529 std::unique_lock
<std::mutex
> lock(mQueueMtx
);
530 int ret
= avcodec_receive_frame(mCodecCtx
.get(), mDecodedFrame
.get());
531 if(ret
== AVERROR(EAGAIN
))
533 mMovie
.mSendDataGood
.clear(std::memory_order_relaxed
);
534 std::unique_lock
<std::mutex
>(mMovie
.mSendMtx
).unlock();
535 mMovie
.mSendCond
.notify_one();
537 mQueueCond
.wait(lock
);
538 ret
= avcodec_receive_frame(mCodecCtx
.get(), mDecodedFrame
.get());
539 } while(ret
== AVERROR(EAGAIN
));
542 if(ret
== AVERROR_EOF
) break;
543 mMovie
.mSendDataGood
.clear(std::memory_order_relaxed
);
544 mMovie
.mSendCond
.notify_one();
547 std::cerr
<< "Failed to decode frame: "<<ret
<<std::endl
;
551 if(mDecodedFrame
->nb_samples
<= 0)
553 av_frame_unref(mDecodedFrame
.get());
557 /* If provided, update w/ pts */
558 if(mDecodedFrame
->best_effort_timestamp
!= AV_NOPTS_VALUE
)
559 mCurrentPts
= std::chrono::duration_cast
<nanoseconds
>(
560 seconds_d64(av_q2d(mStream
->time_base
)*mDecodedFrame
->best_effort_timestamp
)
563 if(mDecodedFrame
->nb_samples
> mSamplesMax
)
567 &mSamples
, nullptr, mCodecCtx
->channels
,
568 mDecodedFrame
->nb_samples
, mDstSampleFmt
, 0
570 mSamplesMax
= mDecodedFrame
->nb_samples
;
572 /* Return the amount of sample frames converted */
573 int data_size
= swr_convert(mSwresCtx
.get(), &mSamples
, mDecodedFrame
->nb_samples
,
574 (const uint8_t**)mDecodedFrame
->data
, mDecodedFrame
->nb_samples
577 av_frame_unref(mDecodedFrame
.get());
584 /* Duplicates the sample at in to out, count times. The frame size is a
585 * multiple of the template type size.
588 static void sample_dup(uint8_t *out
, const uint8_t *in
, int count
, int frame_size
)
590 const T
*sample
= reinterpret_cast<const T
*>(in
);
591 T
*dst
= reinterpret_cast<T
*>(out
);
592 if(frame_size
== sizeof(T
))
593 std::fill_n(dst
, count
, *sample
);
596 /* NOTE: frame_size is a multiple of sizeof(T). */
597 int type_mult
= frame_size
/ sizeof(T
);
599 std::generate_n(dst
, count
*type_mult
,
600 [sample
,type_mult
,&i
]() -> T
611 bool AudioState::readAudio(uint8_t *samples
, int length
)
613 int sample_skip
= getSync();
616 /* Read the next chunk of data, refill the buffer, and queue it
618 length
/= mFrameSize
;
619 while(audio_size
< length
)
621 if(mSamplesLen
<= 0 || mSamplesPos
>= mSamplesLen
)
623 int frame_len
= decodeFrame();
624 if(frame_len
<= 0) break;
626 mSamplesLen
= frame_len
;
627 mSamplesPos
= std::min(mSamplesLen
, sample_skip
);
628 sample_skip
-= mSamplesPos
;
630 // Adjust the device start time and current pts by the amount we're
631 // skipping/duplicating, so that the clock remains correct for the
632 // current stream position.
633 auto skip
= nanoseconds(seconds(mSamplesPos
)) / mCodecCtx
->sample_rate
;
634 mDeviceStartTime
-= skip
;
639 int rem
= length
- audio_size
;
642 int len
= mSamplesLen
- mSamplesPos
;
643 if(rem
> len
) rem
= len
;
644 memcpy(samples
, mSamples
+ mSamplesPos
*mFrameSize
, rem
*mFrameSize
);
648 rem
= std::min(rem
, -mSamplesPos
);
650 /* Add samples by copying the first sample */
651 if((mFrameSize
&7) == 0)
652 sample_dup
<uint64_t>(samples
, mSamples
, rem
, mFrameSize
);
653 else if((mFrameSize
&3) == 0)
654 sample_dup
<uint32_t>(samples
, mSamples
, rem
, mFrameSize
);
655 else if((mFrameSize
&1) == 0)
656 sample_dup
<uint16_t>(samples
, mSamples
, rem
, mFrameSize
);
658 sample_dup
<uint8_t>(samples
, mSamples
, rem
, mFrameSize
);
662 mCurrentPts
+= nanoseconds(seconds(rem
)) / mCodecCtx
->sample_rate
;
663 samples
+= rem
*mFrameSize
;
669 if(audio_size
< length
)
671 int rem
= length
- audio_size
;
672 std::fill_n(samples
, rem
*mFrameSize
,
673 (mDstSampleFmt
== AV_SAMPLE_FMT_U8
) ? 0x80 : 0x00);
674 mCurrentPts
+= nanoseconds(seconds(rem
)) / mCodecCtx
->sample_rate
;
681 void AL_APIENTRY
AudioState::EventCallback(ALenum eventType
, ALuint object
, ALuint param
,
682 ALsizei length
, const ALchar
*message
,
685 AudioState
*self
= reinterpret_cast<AudioState
*>(userParam
);
687 if(eventType
== AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT
)
689 /* TODO: Signal the audio handler to wake up and decode another buffer. */
693 std::cout
<< "---- AL Event on AudioState "<<self
<<" ----\nEvent: ";
696 case AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT
: std::cout
<< "Buffer completed"; break;
697 case AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT
: std::cout
<< "Source state changed"; break;
698 case AL_EVENT_TYPE_ERROR_SOFT
: std::cout
<< "API error"; break;
699 case AL_EVENT_TYPE_PERFORMANCE_SOFT
: std::cout
<< "Performance"; break;
700 case AL_EVENT_TYPE_DEPRECATED_SOFT
: std::cout
<< "Deprecated"; break;
701 default: std::cout
<< "0x"<<std::hex
<<std::setw(4)<<std::setfill('0')<<eventType
<<
702 std::dec
<<std::setw(0)<<std::setfill(' '); break;
705 "Object ID: "<<object
<<'\n'<<
706 "Parameter: "<<param
<<'\n'<<
707 "Message: "<<std::string(message
, length
)<<"\n----"<<
711 int AudioState::handler()
713 const std::array
<ALenum
,5> types
{{
714 AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT
, AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT
,
715 AL_EVENT_TYPE_ERROR_SOFT
, AL_EVENT_TYPE_PERFORMANCE_SOFT
, AL_EVENT_TYPE_DEPRECATED_SOFT
717 std::unique_lock
<std::mutex
> lock(mSrcMutex
);
720 if(alEventControlSOFT
)
722 alEventControlSOFT(types
.size(), types
.data(), AL_TRUE
);
723 alEventCallbackSOFT(EventCallback
, this);
726 /* Find a suitable format for OpenAL. */
728 if(mCodecCtx
->sample_fmt
== AV_SAMPLE_FMT_U8
|| mCodecCtx
->sample_fmt
== AV_SAMPLE_FMT_U8P
)
730 mDstSampleFmt
= AV_SAMPLE_FMT_U8
;
732 if(mCodecCtx
->channel_layout
== AV_CH_LAYOUT_7POINT1
&&
733 alIsExtensionPresent("AL_EXT_MCFORMATS") &&
734 (fmt
=alGetEnumValue("AL_FORMAT_71CHN8")) != AL_NONE
&& fmt
!= -1)
736 mDstChanLayout
= mCodecCtx
->channel_layout
;
740 if((mCodecCtx
->channel_layout
== AV_CH_LAYOUT_5POINT1
||
741 mCodecCtx
->channel_layout
== AV_CH_LAYOUT_5POINT1_BACK
) &&
742 alIsExtensionPresent("AL_EXT_MCFORMATS") &&
743 (fmt
=alGetEnumValue("AL_FORMAT_51CHN8")) != AL_NONE
&& fmt
!= -1)
745 mDstChanLayout
= mCodecCtx
->channel_layout
;
749 if(mCodecCtx
->channel_layout
== AV_CH_LAYOUT_MONO
)
751 mDstChanLayout
= mCodecCtx
->channel_layout
;
753 mFormat
= AL_FORMAT_MONO8
;
757 mDstChanLayout
= AV_CH_LAYOUT_STEREO
;
759 mFormat
= AL_FORMAT_STEREO8
;
762 if((mCodecCtx
->sample_fmt
== AV_SAMPLE_FMT_FLT
|| mCodecCtx
->sample_fmt
== AV_SAMPLE_FMT_FLTP
) &&
763 alIsExtensionPresent("AL_EXT_FLOAT32"))
765 mDstSampleFmt
= AV_SAMPLE_FMT_FLT
;
767 if(mCodecCtx
->channel_layout
== AV_CH_LAYOUT_7POINT1
&&
768 alIsExtensionPresent("AL_EXT_MCFORMATS") &&
769 (fmt
=alGetEnumValue("AL_FORMAT_71CHN32")) != AL_NONE
&& fmt
!= -1)
771 mDstChanLayout
= mCodecCtx
->channel_layout
;
775 if((mCodecCtx
->channel_layout
== AV_CH_LAYOUT_5POINT1
||
776 mCodecCtx
->channel_layout
== AV_CH_LAYOUT_5POINT1_BACK
) &&
777 alIsExtensionPresent("AL_EXT_MCFORMATS") &&
778 (fmt
=alGetEnumValue("AL_FORMAT_51CHN32")) != AL_NONE
&& fmt
!= -1)
780 mDstChanLayout
= mCodecCtx
->channel_layout
;
784 if(mCodecCtx
->channel_layout
== AV_CH_LAYOUT_MONO
)
786 mDstChanLayout
= mCodecCtx
->channel_layout
;
788 mFormat
= AL_FORMAT_MONO_FLOAT32
;
792 mDstChanLayout
= AV_CH_LAYOUT_STEREO
;
794 mFormat
= AL_FORMAT_STEREO_FLOAT32
;
799 mDstSampleFmt
= AV_SAMPLE_FMT_S16
;
801 if(mCodecCtx
->channel_layout
== AV_CH_LAYOUT_7POINT1
&&
802 alIsExtensionPresent("AL_EXT_MCFORMATS") &&
803 (fmt
=alGetEnumValue("AL_FORMAT_71CHN16")) != AL_NONE
&& fmt
!= -1)
805 mDstChanLayout
= mCodecCtx
->channel_layout
;
809 if((mCodecCtx
->channel_layout
== AV_CH_LAYOUT_5POINT1
||
810 mCodecCtx
->channel_layout
== AV_CH_LAYOUT_5POINT1_BACK
) &&
811 alIsExtensionPresent("AL_EXT_MCFORMATS") &&
812 (fmt
=alGetEnumValue("AL_FORMAT_51CHN16")) != AL_NONE
&& fmt
!= -1)
814 mDstChanLayout
= mCodecCtx
->channel_layout
;
818 if(mCodecCtx
->channel_layout
== AV_CH_LAYOUT_MONO
)
820 mDstChanLayout
= mCodecCtx
->channel_layout
;
822 mFormat
= AL_FORMAT_MONO16
;
826 mDstChanLayout
= AV_CH_LAYOUT_STEREO
;
828 mFormat
= AL_FORMAT_STEREO16
;
831 void *samples
= nullptr;
832 ALsizei buffer_len
= std::chrono::duration_cast
<std::chrono::duration
<int>>(
833 mCodecCtx
->sample_rate
* AudioBufferTime
).count() * mFrameSize
;
840 mDecodedFrame
.reset(av_frame_alloc());
843 std::cerr
<< "Failed to allocate audio frame" <<std::endl
;
847 mSwresCtx
.reset(swr_alloc_set_opts(nullptr,
848 mDstChanLayout
, mDstSampleFmt
, mCodecCtx
->sample_rate
,
849 mCodecCtx
->channel_layout
? mCodecCtx
->channel_layout
:
850 (uint64_t)av_get_default_channel_layout(mCodecCtx
->channels
),
851 mCodecCtx
->sample_fmt
, mCodecCtx
->sample_rate
,
854 if(!mSwresCtx
|| swr_init(mSwresCtx
.get()) != 0)
856 std::cerr
<< "Failed to initialize audio converter" <<std::endl
;
860 mBuffers
.assign(AudioBufferTotalTime
/ AudioBufferTime
, 0);
861 alGenBuffers(mBuffers
.size(), mBuffers
.data());
862 alGenSources(1, &mSource
);
865 alSourcei(mSource
, AL_DIRECT_CHANNELS_SOFT
, AL_TRUE
);
867 if(alGetError() != AL_NO_ERROR
)
870 if(!alBufferStorageSOFT
)
871 samples
= av_malloc(buffer_len
);
874 for(ALuint bufid
: mBuffers
)
875 alBufferStorageSOFT(bufid
, mFormat
, nullptr, buffer_len
, mCodecCtx
->sample_rate
,
876 AL_MAP_WRITE_BIT_SOFT
);
877 if(alGetError() != AL_NO_ERROR
)
879 fprintf(stderr
, "Failed to use mapped buffers\n");
880 samples
= av_malloc(buffer_len
);
884 while(alGetError() == AL_NO_ERROR
&& !mMovie
.mQuit
.load(std::memory_order_relaxed
))
886 /* First remove any processed buffers. */
888 alGetSourcei(mSource
, AL_BUFFERS_PROCESSED
, &processed
);
891 std::array
<ALuint
,4> bids
;
892 alSourceUnqueueBuffers(mSource
, std::min
<ALsizei
>(bids
.size(), processed
),
894 processed
-= std::min
<ALsizei
>(bids
.size(), processed
);
897 /* Refill the buffer queue. */
899 alGetSourcei(mSource
, AL_BUFFERS_QUEUED
, &queued
);
900 while((ALuint
)queued
< mBuffers
.size())
902 ALuint bufid
= mBuffers
[mBufferIdx
];
904 uint8_t *ptr
= reinterpret_cast<uint8_t*>(
905 samples
? samples
: alMapBufferSOFT(bufid
, 0, buffer_len
, AL_MAP_WRITE_BIT_SOFT
)
909 /* Read the next chunk of data, filling the buffer, and queue it on
911 bool got_audio
= readAudio(ptr
, buffer_len
);
912 if(!samples
) alUnmapBufferSOFT(bufid
);
913 if(!got_audio
) break;
916 alBufferData(bufid
, mFormat
, samples
, buffer_len
, mCodecCtx
->sample_rate
);
918 alSourceQueueBuffers(mSource
, 1, &bufid
);
919 mBufferIdx
= (mBufferIdx
+1) % mBuffers
.size();
925 /* Check that the source is playing. */
927 alGetSourcei(mSource
, AL_SOURCE_STATE
, &state
);
928 if(state
== AL_STOPPED
)
930 /* AL_STOPPED means there was an underrun. Clear the buffer queue
931 * since this likely means we're late, and rewind the source to get
932 * it back into an AL_INITIAL state.
934 alSourceRewind(mSource
);
935 alSourcei(mSource
, AL_BUFFER
, 0);
939 /* (re)start the source if needed, and wait for a buffer to finish */
940 if(state
!= AL_PLAYING
&& state
!= AL_PAUSED
&&
941 mMovie
.mPlaying
.load(std::memory_order_relaxed
))
945 SDL_Delay((AudioBufferTime
/3).count());
949 alSourceRewind(mSource
);
950 alSourcei(mSource
, AL_BUFFER
, 0);
955 if(alEventControlSOFT
)
957 alEventControlSOFT(types
.size(), types
.data(), AL_FALSE
);
958 alEventCallbackSOFT(nullptr, nullptr);
965 nanoseconds
VideoState::getClock()
967 /* NOTE: This returns incorrect times while not playing. */
968 auto delta
= get_avtime() - mCurrentPtsTime
;
969 return mCurrentPts
+ delta
;
972 bool VideoState::isBufferFilled()
974 std::unique_lock
<std::mutex
> lock(mPictQMutex
);
975 return mPictQSize
>= mPictQ
.size();
978 Uint32 SDLCALL
VideoState::sdl_refresh_timer_cb(Uint32
/*interval*/, void *opaque
)
981 evt
.user
.type
= FF_REFRESH_EVENT
;
982 evt
.user
.data1
= opaque
;
984 return 0; /* 0 means stop timer */
987 /* Schedules an FF_REFRESH_EVENT event to occur in 'delay' ms. */
988 void VideoState::schedRefresh(milliseconds delay
)
990 SDL_AddTimer(delay
.count(), sdl_refresh_timer_cb
, this);
993 /* Called by VideoState::refreshTimer to display the next video frame. */
994 void VideoState::display(SDL_Window
*screen
, SDL_Renderer
*renderer
)
996 Picture
*vp
= &mPictQ
[mPictQRead
];
1005 if(mCodecCtx
->sample_aspect_ratio
.num
== 0)
1006 aspect_ratio
= 0.0f
;
1009 aspect_ratio
= av_q2d(mCodecCtx
->sample_aspect_ratio
) * mCodecCtx
->width
/
1012 if(aspect_ratio
<= 0.0f
)
1013 aspect_ratio
= (float)mCodecCtx
->width
/ (float)mCodecCtx
->height
;
1015 SDL_GetWindowSize(screen
, &win_w
, &win_h
);
1017 w
= ((int)rint(h
* aspect_ratio
) + 3) & ~3;
1021 h
= ((int)rint(w
/ aspect_ratio
) + 3) & ~3;
1023 x
= (win_w
- w
) / 2;
1024 y
= (win_h
- h
) / 2;
1026 SDL_Rect src_rect
{ 0, 0, vp
->mWidth
, vp
->mHeight
};
1027 SDL_Rect dst_rect
{ x
, y
, w
, h
};
1028 SDL_RenderCopy(renderer
, vp
->mImage
, &src_rect
, &dst_rect
);
1029 SDL_RenderPresent(renderer
);
1032 /* FF_REFRESH_EVENT handler called on the main thread where the SDL_Renderer
1033 * was created. It handles the display of the next decoded video frame (if not
1034 * falling behind), and sets up the timer for the following video frame.
1036 void VideoState::refreshTimer(SDL_Window
*screen
, SDL_Renderer
*renderer
)
1042 mFinalUpdate
= true;
1043 std::unique_lock
<std::mutex
>(mPictQMutex
).unlock();
1044 mPictQCond
.notify_all();
1047 schedRefresh(milliseconds(100));
1050 if(!mMovie
.mPlaying
.load(std::memory_order_relaxed
))
1052 schedRefresh(milliseconds(1));
1056 std::unique_lock
<std::mutex
> lock(mPictQMutex
);
1061 mFinalUpdate
= true;
1063 schedRefresh(milliseconds(1));
1065 mPictQCond
.notify_all();
1069 Picture
*vp
= &mPictQ
[mPictQRead
];
1070 mCurrentPts
= vp
->mPts
;
1071 mCurrentPtsTime
= get_avtime();
1073 /* Get delay using the frame pts and the pts from last frame. */
1074 auto delay
= vp
->mPts
- mFrameLastPts
;
1075 if(delay
<= seconds::zero() || delay
>= seconds(1))
1077 /* If incorrect delay, use previous one. */
1078 delay
= mFrameLastDelay
;
1080 /* Save for next frame. */
1081 mFrameLastDelay
= delay
;
1082 mFrameLastPts
= vp
->mPts
;
1084 /* Update delay to sync to clock if not master source. */
1085 if(mMovie
.mAVSyncType
!= SyncMaster::Video
)
1087 auto ref_clock
= mMovie
.getMasterClock();
1088 auto diff
= vp
->mPts
- ref_clock
;
1090 /* Skip or repeat the frame. Take delay into account. */
1091 auto sync_threshold
= std::min
<nanoseconds
>(delay
, VideoSyncThreshold
);
1092 if(!(diff
< AVNoSyncThreshold
&& diff
> -AVNoSyncThreshold
))
1094 if(diff
<= -sync_threshold
)
1095 delay
= nanoseconds::zero();
1096 else if(diff
>= sync_threshold
)
1101 mFrameTimer
+= delay
;
1102 /* Compute the REAL delay. */
1103 auto actual_delay
= mFrameTimer
- get_avtime();
1104 if(!(actual_delay
>= VideoSyncThreshold
))
1106 /* We don't have time to handle this picture, just skip to the next one. */
1107 mPictQRead
= (mPictQRead
+1)%mPictQ
.size();
1111 schedRefresh(std::chrono::duration_cast
<milliseconds
>(actual_delay
));
1113 /* Show the picture! */
1114 display(screen
, renderer
);
1116 /* Update queue for next picture. */
1117 mPictQRead
= (mPictQRead
+1)%mPictQ
.size();
1120 mPictQCond
.notify_all();
1123 /* FF_UPDATE_EVENT handler, updates the picture's texture. It's called on the
1124 * main thread where the renderer was created.
1126 void VideoState::updatePicture(SDL_Window
*screen
, SDL_Renderer
*renderer
)
1128 Picture
*vp
= &mPictQ
[mPictQWrite
];
1129 bool fmt_updated
= false;
1131 /* allocate or resize the buffer! */
1132 if(!vp
->mImage
|| vp
->mWidth
!= mCodecCtx
->width
|| vp
->mHeight
!= mCodecCtx
->height
)
1136 SDL_DestroyTexture(vp
->mImage
);
1137 vp
->mImage
= SDL_CreateTexture(
1138 renderer
, SDL_PIXELFORMAT_IYUV
, SDL_TEXTUREACCESS_STREAMING
,
1139 mCodecCtx
->coded_width
, mCodecCtx
->coded_height
1142 std::cerr
<< "Failed to create YV12 texture!" <<std::endl
;
1143 vp
->mWidth
= mCodecCtx
->width
;
1144 vp
->mHeight
= mCodecCtx
->height
;
1146 if(mFirstUpdate
&& vp
->mWidth
> 0 && vp
->mHeight
> 0)
1148 /* For the first update, set the window size to the video size. */
1149 mFirstUpdate
= false;
1152 int h
= vp
->mHeight
;
1153 if(mCodecCtx
->sample_aspect_ratio
.den
!= 0)
1155 double aspect_ratio
= av_q2d(mCodecCtx
->sample_aspect_ratio
);
1156 if(aspect_ratio
>= 1.0)
1157 w
= (int)(w
*aspect_ratio
+ 0.5);
1158 else if(aspect_ratio
> 0.0)
1159 h
= (int)(h
/aspect_ratio
+ 0.5);
1161 SDL_SetWindowSize(screen
, w
, h
);
1167 AVFrame
*frame
= mDecodedFrame
.get();
1168 void *pixels
= nullptr;
1171 if(mCodecCtx
->pix_fmt
== AV_PIX_FMT_YUV420P
)
1172 SDL_UpdateYUVTexture(vp
->mImage
, nullptr,
1173 frame
->data
[0], frame
->linesize
[0],
1174 frame
->data
[1], frame
->linesize
[1],
1175 frame
->data
[2], frame
->linesize
[2]
1177 else if(SDL_LockTexture(vp
->mImage
, nullptr, &pixels
, &pitch
) != 0)
1178 std::cerr
<< "Failed to lock texture" <<std::endl
;
1181 // Convert the image into YUV format that SDL uses
1182 int coded_w
= mCodecCtx
->coded_width
;
1183 int coded_h
= mCodecCtx
->coded_height
;
1184 int w
= mCodecCtx
->width
;
1185 int h
= mCodecCtx
->height
;
1186 if(!mSwscaleCtx
|| fmt_updated
)
1188 mSwscaleCtx
.reset(sws_getContext(
1189 w
, h
, mCodecCtx
->pix_fmt
,
1190 w
, h
, AV_PIX_FMT_YUV420P
, 0,
1191 nullptr, nullptr, nullptr
1195 /* point pict at the queue */
1196 uint8_t *pict_data
[3];
1197 pict_data
[0] = reinterpret_cast<uint8_t*>(pixels
);
1198 pict_data
[1] = pict_data
[0] + coded_w
*coded_h
;
1199 pict_data
[2] = pict_data
[1] + coded_w
*coded_h
/4;
1201 int pict_linesize
[3];
1202 pict_linesize
[0] = pitch
;
1203 pict_linesize
[1] = pitch
/ 2;
1204 pict_linesize
[2] = pitch
/ 2;
1206 sws_scale(mSwscaleCtx
.get(), (const uint8_t**)frame
->data
,
1207 frame
->linesize
, 0, h
, pict_data
, pict_linesize
);
1208 SDL_UnlockTexture(vp
->mImage
);
1212 vp
->mUpdated
.store(true, std::memory_order_release
);
1213 std::unique_lock
<std::mutex
>(mPictQMutex
).unlock();
1214 mPictQCond
.notify_one();
1217 int VideoState::queuePicture(nanoseconds pts
)
1219 /* Wait until we have space for a new pic */
1220 std::unique_lock
<std::mutex
> lock(mPictQMutex
);
1221 while(mPictQSize
>= mPictQ
.size() && !mMovie
.mQuit
.load(std::memory_order_relaxed
))
1222 mPictQCond
.wait(lock
);
1225 if(mMovie
.mQuit
.load(std::memory_order_relaxed
))
1228 Picture
*vp
= &mPictQ
[mPictQWrite
];
1230 /* We have to create/update the picture in the main thread */
1231 vp
->mUpdated
.store(false, std::memory_order_relaxed
);
1233 evt
.user
.type
= FF_UPDATE_EVENT
;
1234 evt
.user
.data1
= this;
1235 SDL_PushEvent(&evt
);
1237 /* Wait until the picture is updated. */
1239 while(!vp
->mUpdated
.load(std::memory_order_relaxed
))
1241 if(mMovie
.mQuit
.load(std::memory_order_relaxed
))
1243 mPictQCond
.wait(lock
);
1245 if(mMovie
.mQuit
.load(std::memory_order_relaxed
))
1249 mPictQWrite
= (mPictQWrite
+1)%mPictQ
.size();
1256 int VideoState::handler()
1258 mDecodedFrame
.reset(av_frame_alloc());
1259 while(!mMovie
.mQuit
.load(std::memory_order_relaxed
))
1261 std::unique_lock
<std::mutex
> lock(mQueueMtx
);
1262 /* Decode video frame */
1263 int ret
= avcodec_receive_frame(mCodecCtx
.get(), mDecodedFrame
.get());
1264 if(ret
== AVERROR(EAGAIN
))
1266 mMovie
.mSendDataGood
.clear(std::memory_order_relaxed
);
1267 std::unique_lock
<std::mutex
>(mMovie
.mSendMtx
).unlock();
1268 mMovie
.mSendCond
.notify_one();
1270 mQueueCond
.wait(lock
);
1271 ret
= avcodec_receive_frame(mCodecCtx
.get(), mDecodedFrame
.get());
1272 } while(ret
== AVERROR(EAGAIN
));
1275 if(ret
== AVERROR_EOF
) break;
1276 mMovie
.mSendDataGood
.clear(std::memory_order_relaxed
);
1277 mMovie
.mSendCond
.notify_one();
1280 std::cerr
<< "Failed to decode frame: "<<ret
<<std::endl
;
1284 /* Get the PTS for this frame. */
1286 if(mDecodedFrame
->best_effort_timestamp
!= AV_NOPTS_VALUE
)
1287 mClock
= std::chrono::duration_cast
<nanoseconds
>(
1288 seconds_d64(av_q2d(mStream
->time_base
)*mDecodedFrame
->best_effort_timestamp
)
1292 /* Update the video clock to the next expected PTS. */
1293 auto frame_delay
= av_q2d(mCodecCtx
->time_base
);
1294 frame_delay
+= mDecodedFrame
->repeat_pict
* (frame_delay
* 0.5);
1295 mClock
+= std::chrono::duration_cast
<nanoseconds
>(seconds_d64(frame_delay
));
1297 if(queuePicture(pts
) < 0)
1299 av_frame_unref(mDecodedFrame
.get());
1303 std::unique_lock
<std::mutex
> lock(mPictQMutex
);
1304 if(mMovie
.mQuit
.load(std::memory_order_relaxed
))
1310 while(!mFinalUpdate
)
1311 mPictQCond
.wait(lock
);
1317 int MovieState::decode_interrupt_cb(void *ctx
)
1319 return reinterpret_cast<MovieState
*>(ctx
)->mQuit
.load(std::memory_order_relaxed
);
1322 bool MovieState::prepare()
1324 AVIOContext
*avioctx
= nullptr;
1325 AVIOInterruptCB intcb
= { decode_interrupt_cb
, this };
1326 if(avio_open2(&avioctx
, mFilename
.c_str(), AVIO_FLAG_READ
, &intcb
, nullptr))
1328 std::cerr
<< "Failed to open "<<mFilename
<<std::endl
;
1331 mIOContext
.reset(avioctx
);
1333 /* Open movie file. If avformat_open_input fails it will automatically free
1334 * this context, so don't set it onto a smart pointer yet.
1336 AVFormatContext
*fmtctx
= avformat_alloc_context();
1337 fmtctx
->pb
= mIOContext
.get();
1338 fmtctx
->interrupt_callback
= intcb
;
1339 if(avformat_open_input(&fmtctx
, mFilename
.c_str(), nullptr, nullptr) != 0)
1341 std::cerr
<< "Failed to open "<<mFilename
<<std::endl
;
1344 mFormatCtx
.reset(fmtctx
);
1346 /* Retrieve stream information */
1347 if(avformat_find_stream_info(mFormatCtx
.get(), nullptr) < 0)
1349 std::cerr
<< mFilename
<<": failed to find stream info" <<std::endl
;
1353 mVideo
.schedRefresh(milliseconds(40));
1355 mParseThread
= std::thread(std::mem_fn(&MovieState::parse_handler
), this);
1359 void MovieState::setTitle(SDL_Window
*window
)
1361 auto pos1
= mFilename
.rfind('/');
1362 auto pos2
= mFilename
.rfind('\\');
1363 auto fpos
= ((pos1
== std::string::npos
) ? pos2
:
1364 (pos2
== std::string::npos
) ? pos1
:
1365 std::max(pos1
, pos2
)) + 1;
1366 SDL_SetWindowTitle(window
, (mFilename
.substr(fpos
)+" - "+AppName
).c_str());
1369 nanoseconds
MovieState::getClock()
1371 if(!mPlaying
.load(std::memory_order_relaxed
))
1372 return nanoseconds::zero();
1373 return get_avtime() - mClockBase
;
1376 nanoseconds
MovieState::getMasterClock()
1378 if(mAVSyncType
== SyncMaster::Video
)
1379 return mVideo
.getClock();
1380 if(mAVSyncType
== SyncMaster::Audio
)
1381 return mAudio
.getClock();
1385 nanoseconds
MovieState::getDuration()
1386 { return std::chrono::duration
<int64_t,std::ratio
<1,AV_TIME_BASE
>>(mFormatCtx
->duration
); }
1388 int MovieState::streamComponentOpen(int stream_index
)
1390 if(stream_index
< 0 || (unsigned int)stream_index
>= mFormatCtx
->nb_streams
)
1393 /* Get a pointer to the codec context for the stream, and open the
1396 AVCodecCtxPtr
avctx(avcodec_alloc_context3(nullptr));
1397 if(!avctx
) return -1;
1399 if(avcodec_parameters_to_context(avctx
.get(), mFormatCtx
->streams
[stream_index
]->codecpar
))
1402 AVCodec
*codec
= avcodec_find_decoder(avctx
->codec_id
);
1403 if(!codec
|| avcodec_open2(avctx
.get(), codec
, nullptr) < 0)
1405 std::cerr
<< "Unsupported codec: "<<avcodec_get_name(avctx
->codec_id
)
1406 << " (0x"<<std::hex
<<avctx
->codec_id
<<std::dec
<<")" <<std::endl
;
1410 /* Initialize and start the media type handler */
1411 switch(avctx
->codec_type
)
1413 case AVMEDIA_TYPE_AUDIO
:
1414 mAudio
.mStream
= mFormatCtx
->streams
[stream_index
];
1415 mAudio
.mCodecCtx
= std::move(avctx
);
1417 mAudioThread
= std::thread(std::mem_fn(&AudioState::handler
), &mAudio
);
1420 case AVMEDIA_TYPE_VIDEO
:
1421 mVideo
.mStream
= mFormatCtx
->streams
[stream_index
];
1422 mVideo
.mCodecCtx
= std::move(avctx
);
1424 mVideoThread
= std::thread(std::mem_fn(&VideoState::handler
), &mVideo
);
1431 return stream_index
;
1434 int MovieState::parse_handler()
1436 int video_index
= -1;
1437 int audio_index
= -1;
1439 /* Dump information about file onto standard error */
1440 av_dump_format(mFormatCtx
.get(), 0, mFilename
.c_str(), 0);
1442 /* Find the first video and audio streams */
1443 for(unsigned int i
= 0;i
< mFormatCtx
->nb_streams
;i
++)
1445 auto codecpar
= mFormatCtx
->streams
[i
]->codecpar
;
1446 if(codecpar
->codec_type
== AVMEDIA_TYPE_VIDEO
&& video_index
< 0)
1447 video_index
= streamComponentOpen(i
);
1448 else if(codecpar
->codec_type
== AVMEDIA_TYPE_AUDIO
&& audio_index
< 0)
1449 audio_index
= streamComponentOpen(i
);
1452 if(video_index
< 0 && audio_index
< 0)
1454 std::cerr
<< mFilename
<<": could not open codecs" <<std::endl
;
1458 PacketQueue audio_queue
, video_queue
;
1459 bool input_finished
= false;
1461 /* Main packet reading/dispatching loop */
1462 while(!mQuit
.load(std::memory_order_relaxed
) && !input_finished
)
1465 if(av_read_frame(mFormatCtx
.get(), &packet
) < 0)
1466 input_finished
= true;
1469 /* Copy the packet into the queue it's meant for. */
1470 if(packet
.stream_index
== video_index
)
1471 video_queue
.put(&packet
);
1472 else if(packet
.stream_index
== audio_index
)
1473 audio_queue
.put(&packet
);
1474 av_packet_unref(&packet
);
1478 /* Send whatever queued packets we have. */
1479 if(!audio_queue
.empty())
1481 std::unique_lock
<std::mutex
> lock(mAudio
.mQueueMtx
);
1484 ret
= avcodec_send_packet(mAudio
.mCodecCtx
.get(), audio_queue
.front());
1485 if(ret
!= AVERROR(EAGAIN
)) audio_queue
.pop();
1486 } while(ret
!= AVERROR(EAGAIN
) && !audio_queue
.empty());
1488 mAudio
.mQueueCond
.notify_one();
1490 if(!video_queue
.empty())
1492 std::unique_lock
<std::mutex
> lock(mVideo
.mQueueMtx
);
1495 ret
= avcodec_send_packet(mVideo
.mCodecCtx
.get(), video_queue
.front());
1496 if(ret
!= AVERROR(EAGAIN
)) video_queue
.pop();
1497 } while(ret
!= AVERROR(EAGAIN
) && !video_queue
.empty());
1499 mVideo
.mQueueCond
.notify_one();
1501 /* If the queues are completely empty, or it's not full and there's
1502 * more input to read, go get more.
1504 size_t queue_size
= audio_queue
.totalSize() + video_queue
.totalSize();
1505 if(queue_size
== 0 || (queue_size
< MAX_QUEUE_SIZE
&& !input_finished
))
1508 if(!mPlaying
.load(std::memory_order_relaxed
))
1510 if((!mAudio
.mCodecCtx
|| mAudio
.isBufferFilled()) &&
1511 (!mVideo
.mCodecCtx
|| mVideo
.isBufferFilled()))
1513 /* Set the base time 50ms ahead of the current av time. */
1514 mClockBase
= get_avtime() + milliseconds(50);
1515 mVideo
.mCurrentPtsTime
= mClockBase
;
1516 mVideo
.mFrameTimer
= mVideo
.mCurrentPtsTime
;
1517 mAudio
.startPlayback();
1518 mPlaying
.store(std::memory_order_release
);
1521 /* Nothing to send or get for now, wait a bit and try again. */
1522 { std::unique_lock
<std::mutex
> lock(mSendMtx
);
1523 if(mSendDataGood
.test_and_set(std::memory_order_relaxed
))
1524 mSendCond
.wait_for(lock
, milliseconds(10));
1526 } while(!mQuit
.load(std::memory_order_relaxed
));
1528 /* Pass a null packet to finish the send buffers (the receive functions
1529 * will get AVERROR_EOF when emptied).
1531 if(mVideo
.mCodecCtx
)
1533 { std::lock_guard
<std::mutex
> lock(mVideo
.mQueueMtx
);
1534 avcodec_send_packet(mVideo
.mCodecCtx
.get(), nullptr);
1536 mVideo
.mQueueCond
.notify_one();
1538 if(mAudio
.mCodecCtx
)
1540 { std::lock_guard
<std::mutex
> lock(mAudio
.mQueueMtx
);
1541 avcodec_send_packet(mAudio
.mCodecCtx
.get(), nullptr);
1543 mAudio
.mQueueCond
.notify_one();
1545 video_queue
.clear();
1546 audio_queue
.clear();
1548 /* all done - wait for it */
1549 if(mVideoThread
.joinable())
1550 mVideoThread
.join();
1551 if(mAudioThread
.joinable())
1552 mAudioThread
.join();
1555 std::unique_lock
<std::mutex
> lock(mVideo
.mPictQMutex
);
1556 while(!mVideo
.mFinalUpdate
)
1557 mVideo
.mPictQCond
.wait(lock
);
1561 evt
.user
.type
= FF_MOVIE_DONE_EVENT
;
1562 SDL_PushEvent(&evt
);
1568 // Helper class+method to print the time with human-readable formatting.
1572 inline std::ostream
&operator<<(std::ostream
&os
, const PrettyTime
&rhs
)
1574 using hours
= std::chrono::hours
;
1575 using minutes
= std::chrono::minutes
;
1576 using std::chrono::duration_cast
;
1578 seconds t
= rhs
.mTime
;
1585 // Only handle up to hour formatting
1587 os
<< duration_cast
<hours
>(t
).count() << 'h' << std::setfill('0') << std::setw(2)
1588 << (duration_cast
<minutes
>(t
).count() % 60) << 'm';
1590 os
<< duration_cast
<minutes
>(t
).count() << 'm' << std::setfill('0');
1591 os
<< std::setw(2) << (duration_cast
<seconds
>(t
).count() % 60) << 's' << std::setw(0)
1592 << std::setfill(' ');
1599 int main(int argc
, char *argv
[])
1601 std::unique_ptr
<MovieState
> movState
;
1605 std::cerr
<< "Usage: "<<argv
[0]<<" [-device <device name>] [-direct] <files...>" <<std::endl
;
1608 /* Register all formats and codecs */
1610 /* Initialize networking protocols */
1611 avformat_network_init();
1613 if(SDL_Init(SDL_INIT_VIDEO
| SDL_INIT_TIMER
))
1615 std::cerr
<< "Could not initialize SDL - <<"<<SDL_GetError() <<std::endl
;
1619 /* Make a window to put our video */
1620 SDL_Window
*screen
= SDL_CreateWindow(AppName
.c_str(), 0, 0, 640, 480, SDL_WINDOW_RESIZABLE
);
1623 std::cerr
<< "SDL: could not set video mode - exiting" <<std::endl
;
1626 /* Make a renderer to handle the texture image surface and rendering. */
1627 Uint32 render_flags
= SDL_RENDERER_ACCELERATED
| SDL_RENDERER_PRESENTVSYNC
;
1628 SDL_Renderer
*renderer
= SDL_CreateRenderer(screen
, -1, render_flags
);
1631 SDL_RendererInfo rinf
{};
1634 /* Make sure the renderer supports IYUV textures. If not, fallback to a
1635 * software renderer. */
1636 if(SDL_GetRendererInfo(renderer
, &rinf
) == 0)
1638 for(Uint32 i
= 0;!ok
&& i
< rinf
.num_texture_formats
;i
++)
1639 ok
= (rinf
.texture_formats
[i
] == SDL_PIXELFORMAT_IYUV
);
1643 std::cerr
<< "IYUV pixelformat textures not supported on renderer "<<rinf
.name
<<std::endl
;
1644 SDL_DestroyRenderer(renderer
);
1650 render_flags
= SDL_RENDERER_SOFTWARE
| SDL_RENDERER_PRESENTVSYNC
;
1651 renderer
= SDL_CreateRenderer(screen
, -1, render_flags
);
1655 std::cerr
<< "SDL: could not create renderer - exiting" <<std::endl
;
1658 SDL_SetRenderDrawColor(renderer
, 0, 0, 0, 255);
1659 SDL_RenderFillRect(renderer
, nullptr);
1660 SDL_RenderPresent(renderer
);
1662 /* Open an audio device */
1664 ALCdevice
*device
= [argc
,argv
,&fileidx
]() -> ALCdevice
*
1666 ALCdevice
*dev
= NULL
;
1667 if(argc
> 3 && strcmp(argv
[1], "-device") == 0)
1670 dev
= alcOpenDevice(argv
[2]);
1672 std::cerr
<< "Failed to open \""<<argv
[2]<<"\" - trying default" <<std::endl
;
1674 return alcOpenDevice(nullptr);
1676 ALCcontext
*context
= alcCreateContext(device
, nullptr);
1677 if(!context
|| alcMakeContextCurrent(context
) == ALC_FALSE
)
1679 std::cerr
<< "Failed to set up audio device" <<std::endl
;
1681 alcDestroyContext(context
);
1685 const ALCchar
*name
= nullptr;
1686 if(alcIsExtensionPresent(device
, "ALC_ENUMERATE_ALL_EXT"))
1687 name
= alcGetString(device
, ALC_ALL_DEVICES_SPECIFIER
);
1688 if(!name
|| alcGetError(device
) != AL_NO_ERROR
)
1689 name
= alcGetString(device
, ALC_DEVICE_SPECIFIER
);
1690 std::cout
<< "Opened \""<<name
<<"\"" <<std::endl
;
1692 if(alcIsExtensionPresent(device
, "ALC_SOFT_device_clock"))
1694 std::cout
<< "Found ALC_SOFT_device_clock" <<std::endl
;
1695 alcGetInteger64vSOFT
= reinterpret_cast<LPALCGETINTEGER64VSOFT
>(
1696 alcGetProcAddress(device
, "alcGetInteger64vSOFT")
1700 if(alIsExtensionPresent("AL_SOFT_source_latency"))
1702 std::cout
<< "Found AL_SOFT_source_latency" <<std::endl
;
1703 alGetSourcei64vSOFT
= reinterpret_cast<LPALGETSOURCEI64VSOFT
>(
1704 alGetProcAddress("alGetSourcei64vSOFT")
1707 if(alIsExtensionPresent("AL_SOFTX_map_buffer"))
1709 std::cout
<< "Found AL_SOFT_map_buffer" <<std::endl
;
1710 alBufferStorageSOFT
= reinterpret_cast<LPALBUFFERSTORAGESOFT
>(
1711 alGetProcAddress("alBufferStorageSOFT"));
1712 alMapBufferSOFT
= reinterpret_cast<LPALMAPBUFFERSOFT
>(
1713 alGetProcAddress("alMapBufferSOFT"));
1714 alUnmapBufferSOFT
= reinterpret_cast<LPALUNMAPBUFFERSOFT
>(
1715 alGetProcAddress("alUnmapBufferSOFT"));
1717 if(alIsExtensionPresent("AL_SOFTX_events"))
1719 std::cout
<< "Found AL_SOFT_events" <<std::endl
;
1720 alEventControlSOFT
= reinterpret_cast<LPALEVENTCONTROLSOFT
>(
1721 alGetProcAddress("alEventControlSOFT"));
1722 alEventCallbackSOFT
= reinterpret_cast<LPALEVENTCALLBACKSOFT
>(
1723 alGetProcAddress("alEventCallbackSOFT"));
1726 if(fileidx
< argc
&& strcmp(argv
[fileidx
], "-direct") == 0)
1729 if(!alIsExtensionPresent("AL_SOFT_direct_channels"))
1730 std::cerr
<< "AL_SOFT_direct_channels not supported for direct output" <<std::endl
;
1733 std::cout
<< "Found AL_SOFT_direct_channels" <<std::endl
;
1734 EnableDirectOut
= true;
1738 while(fileidx
< argc
&& !movState
)
1740 movState
= std::unique_ptr
<MovieState
>(new MovieState(argv
[fileidx
++]));
1741 if(!movState
->prepare()) movState
= nullptr;
1745 std::cerr
<< "Could not start a video" <<std::endl
;
1748 movState
->setTitle(screen
);
1750 /* Default to going to the next movie at the end of one. */
1751 enum class EomAction
{
1753 } eom_action
= EomAction::Next
;
1754 seconds
last_time(-1);
1758 int have_evt
= SDL_WaitEventTimeout(&event
, 10);
1760 auto cur_time
= std::chrono::duration_cast
<seconds
>(movState
->getMasterClock());
1761 if(cur_time
!= last_time
)
1763 auto end_time
= std::chrono::duration_cast
<seconds
>(movState
->getDuration());
1764 std::cout
<< "\r "<<PrettyTime
{cur_time
}<<" / "<<PrettyTime
{end_time
} <<std::flush
;
1765 last_time
= cur_time
;
1767 if(!have_evt
) continue;
1772 switch(event
.key
.keysym
.sym
)
1775 movState
->mQuit
= true;
1776 eom_action
= EomAction::Quit
;
1780 movState
->mQuit
= true;
1781 eom_action
= EomAction::Next
;
1789 case SDL_WINDOWEVENT
:
1790 switch(event
.window
.event
)
1792 case SDL_WINDOWEVENT_RESIZED
:
1793 SDL_SetRenderDrawColor(renderer
, 0, 0, 0, 255);
1794 SDL_RenderFillRect(renderer
, nullptr);
1803 movState
->mQuit
= true;
1804 eom_action
= EomAction::Quit
;
1807 case FF_UPDATE_EVENT
:
1808 reinterpret_cast<VideoState
*>(event
.user
.data1
)->updatePicture(
1813 case FF_REFRESH_EVENT
:
1814 reinterpret_cast<VideoState
*>(event
.user
.data1
)->refreshTimer(
1819 case FF_MOVIE_DONE_EVENT
:
1821 last_time
= seconds(-1);
1822 if(eom_action
!= EomAction::Quit
)
1825 while(fileidx
< argc
&& !movState
)
1827 movState
= std::unique_ptr
<MovieState
>(new MovieState(argv
[fileidx
++]));
1828 if(!movState
->prepare()) movState
= nullptr;
1832 movState
->setTitle(screen
);
1837 /* Nothing more to play. Shut everything down and quit. */
1840 alcMakeContextCurrent(nullptr);
1841 alcDestroyContext(context
);
1842 alcCloseDevice(device
);
1844 SDL_DestroyRenderer(renderer
);
1846 SDL_DestroyWindow(screen
);
1857 std::cerr
<< "SDL_WaitEvent error - "<<SDL_GetError() <<std::endl
;