Files
itgmania212121/stepmania/src/arch/MovieTexture/MovieTexture_FFMpeg.cpp
T

1063 lines
26 KiB
C++
Raw Normal View History

2003-08-29 04:34:10 +00:00
#include "global.h"
2003-09-02 04:01:01 +00:00
#include "MovieTexture_FFMpeg.h"
2003-08-29 04:34:10 +00:00
#include "RageLog.h"
#include "RageTextureManager.h"
#include "RageUtil.h"
2003-09-02 07:47:37 +00:00
#include "RageTimer.h"
2003-12-05 06:35:22 +00:00
#include "RageFile.h"
2004-06-14 01:09:11 +00:00
#include "RageSurface.h"
2004-04-02 23:15:29 +00:00
#include "PrefsManager.h"
2003-08-29 04:34:10 +00:00
2004-04-05 05:22:32 +00:00
#include <cerrno>
2003-12-05 19:44:41 +00:00
2005-04-30 05:22:14 +00:00
#if defined(WIN32) && !defined(XBOX)
2004-06-14 05:36:42 +00:00
#include <windows.h>
#endif
2003-09-03 02:20:22 +00:00
namespace avcodec
{
2005-09-03 20:57:58 +00:00
#if defined(WIN32)
2003-09-03 02:20:22 +00:00
#include "ffmpeg/include/ffmpeg/avformat.h"
#else
#include <ffmpeg/avformat.h>
#endif
};
2003-08-29 04:34:10 +00:00
#if defined(_MSC_VER) && !defined(XBOX)
2003-09-02 04:01:01 +00:00
#pragma comment(lib, "ffmpeg/lib/avcodec.lib")
#pragma comment(lib, "ffmpeg/lib/avformat.lib")
#endif
2003-08-29 04:34:10 +00:00
struct AVPixelFormat_t
{
int bpp;
int masks[4];
avcodec::PixelFormat pf;
bool HighColor;
bool ByteSwapOnLittleEndian;
} AVPixelFormats[] = {
2003-09-03 04:25:07 +00:00
{
/* This format is really ARGB, and is affected by endianness, unlike PIX_FMT_RGB24
* and PIX_FMT_BGR24. */
32,
{ 0x00FF0000,
0x0000FF00,
0x000000FF,
0xFF000000 },
avcodec::PIX_FMT_RGBA32,
true,
false
},
2003-08-29 04:34:10 +00:00
{
24,
{ 0xFF0000,
0x00FF00,
0x0000FF,
0x000000 },
avcodec::PIX_FMT_RGB24,
true,
true
},
{
24,
{ 0x0000FF,
0x00FF00,
0xFF0000,
0x000000 },
avcodec::PIX_FMT_BGR24,
true,
true
},
{
16,
{ 0x7C00,
0x03E0,
0x001F,
0x8000 },
avcodec::PIX_FMT_RGB555,
false,
false
},
2003-09-19 01:22:02 +00:00
{ 0, { 0,0,0,0 }, avcodec::PIX_FMT_NB, true, false }
2003-08-29 04:34:10 +00:00
};
static void FixLilEndian()
{
2004-06-13 07:36:15 +00:00
#if defined(ENDIAN_LITTLE)
2003-08-29 04:34:10 +00:00
static bool Initialized = false;
if( Initialized )
return;
Initialized = true;
for( int i = 0; i < AVPixelFormats[i].bpp; ++i )
{
AVPixelFormat_t &pf = AVPixelFormats[i];
if( !pf.ByteSwapOnLittleEndian )
continue;
for( int mask = 0; mask < 4; ++mask)
{
int m = pf.masks[mask];
switch( pf.bpp )
{
2004-06-13 07:36:15 +00:00
case 24: m = Swap24(m); break;
case 32: m = Swap32(m); break;
2003-08-29 04:34:10 +00:00
default: ASSERT(0);
}
pf.masks[mask] = m;
}
}
#endif
}
static int FindCompatibleAVFormat( PixelFormat &pixfmt, bool HighColor )
2003-08-29 04:34:10 +00:00
{
for( int i = 0; AVPixelFormats[i].bpp; ++i )
{
AVPixelFormat_t &fmt = AVPixelFormats[i];
if( fmt.HighColor != HighColor )
continue;
pixfmt = DISPLAY->FindPixelFormat( fmt.bpp,
fmt.masks[0],
fmt.masks[1],
fmt.masks[2],
fmt.masks[3],
true /* realtime */
);
2003-08-29 04:34:10 +00:00
if( pixfmt == PixelFormat_INVALID )
2003-08-29 04:34:10 +00:00
continue;
return i;
}
return -1;
}
class FFMpeg_Helper
{
public:
FFMpeg_Helper();
~FFMpeg_Helper();
int GetFrame();
void Init();
CString Open( CString sFile );
void Close();
2005-10-19 23:41:48 +00:00
/* Get the timestamp, in seconds, when the current frame should be
* displayed. The first frame will always be 0. */
float GetTimestamp() const;
/* Get the duration, in seconds, to display the current frame. */
float GetFrameDuration() const;
2005-10-19 23:03:38 +00:00
avcodec::AVStream *m_stream;
avcodec::AVFrame frame;
private:
2005-10-19 23:41:48 +00:00
float m_fPTS;
avcodec::AVFormatContext *m_fctx;
2005-10-19 23:03:38 +00:00
bool m_bGetNextTimestamp;
float m_fCurrentTimestamp;
2005-10-19 23:41:48 +00:00
float m_fLastFrameDelay;
2005-10-19 23:03:38 +00:00
int m_iFrameNumber;
avcodec::AVPacket pkt;
int m_iCurrentPacketOffset;
/* 0 = no EOF
* 1 = EOF from ReadPacket
* 2 = EOF from ReadPacket and DecodePacket */
2005-10-19 23:03:38 +00:00
int m_iEOF;
int ReadPacket();
int DecodePacket();
2005-10-19 23:03:38 +00:00
float m_fTimestampOffset;
};
FFMpeg_Helper::FFMpeg_Helper()
{
2005-10-19 23:03:38 +00:00
m_fctx = NULL;
m_stream = NULL;
m_iCurrentPacketOffset = -1;
Init();
}
FFMpeg_Helper::~FFMpeg_Helper()
{
2005-10-19 23:03:38 +00:00
if( m_iCurrentPacketOffset != -1 )
{
avcodec::av_free_packet( &pkt );
2005-10-19 23:03:38 +00:00
m_iCurrentPacketOffset = -1;
}
}
void FFMpeg_Helper::Init()
{
2005-10-19 23:03:38 +00:00
m_iEOF = 0;
m_bGetNextTimestamp = true;
m_fCurrentTimestamp = 0;
m_fLastFrameDelay = 0;
m_fPTS = -1;
m_iFrameNumber = -1; /* decode one frame and you're on the 0th */
m_fTimestampOffset = 0;
2005-10-19 23:03:38 +00:00
if( m_iCurrentPacketOffset != -1 )
{
avcodec::av_free_packet( &pkt );
2005-10-19 23:03:38 +00:00
m_iCurrentPacketOffset = -1;
}
}
/* Read until we get a frame, EOF or error. Return -1 on error, 0 on EOF, 1 if we have a frame. */
int FFMpeg_Helper::GetFrame()
{
while( 1 )
{
int ret = DecodePacket();
if( ret == 1 )
2004-01-07 04:43:13 +00:00
break;
if( ret == -1 )
return -1;
2005-10-19 23:03:38 +00:00
if( ret == 0 && m_iEOF > 0 )
return 0; /* eof */
ASSERT( ret == 0 );
ret = ReadPacket();
if( ret < 0 )
return ret; /* error */
}
2004-01-07 04:43:13 +00:00
2005-10-19 23:03:38 +00:00
++m_iFrameNumber;
2004-01-07 04:43:13 +00:00
2005-10-19 23:03:38 +00:00
if( m_iFrameNumber == 1 )
2004-01-07 04:43:13 +00:00
{
/* Some videos start with a timestamp other than 0. I think this is used
* when audio starts before the video. We don't want to honor that, since
* the DShow renderer doesn't and we don't want to break sync compatibility.
*
* Look at the second frame. (If we have B-frames, the first frame will be an
* I-frame with the timestamp of the next P-frame, not its own timestamp, and we
* want to ignore that and look at the next B-frame.) */
2005-10-19 23:03:38 +00:00
const float expect = m_fLastFrameDelay;
const float actual = m_fCurrentTimestamp;
2004-01-07 04:43:13 +00:00
if( actual - expect > 0 )
{
LOG->Trace("Expect %f, got %f -> %f", expect, actual, actual - expect );
2005-10-19 23:03:38 +00:00
m_fTimestampOffset = actual - expect;
2004-01-07 04:43:13 +00:00
}
}
return 1;
}
float FFMpeg_Helper::GetTimestamp() const
{
/* The first frame always has a timestamp of 0. */
2005-10-19 23:03:38 +00:00
if( m_iFrameNumber == 0 )
2004-01-07 04:43:13 +00:00
return 0;
2005-10-19 23:03:38 +00:00
return m_fCurrentTimestamp - m_fTimestampOffset;
}
2005-10-19 23:41:48 +00:00
float FFMpeg_Helper::GetFrameDuration() const
{
return m_fLastFrameDelay;
}
/* Read a packet. Return -1 on error, 0 on EOF, 1 on OK. */
int FFMpeg_Helper::ReadPacket()
{
2005-10-19 23:03:38 +00:00
if( m_iEOF > 0 )
return 0;
while( 1 )
{
CHECKPOINT;
2005-10-19 23:03:38 +00:00
if( m_iCurrentPacketOffset != -1 )
{
2005-10-19 23:03:38 +00:00
m_iCurrentPacketOffset = -1;
avcodec::av_free_packet( &pkt );
}
2004-08-06 20:22:48 +00:00
int ret = avcodec::av_read_frame( m_fctx, &pkt );
2003-10-14 07:06:23 +00:00
/* XXX: why is avformat returning AVERROR_NOMEM on EOF? */
if( ret < 0 )
{
/* EOF. */
2005-10-19 23:03:38 +00:00
m_iEOF = 1;
pkt.size = 0;
return 0;
}
if( pkt.stream_index == m_stream->index )
{
2005-10-19 23:03:38 +00:00
m_iCurrentPacketOffset = 0;
return 1;
}
/* It's not for the video stream; ignore it. */
avcodec::av_free_packet( &pkt );
}
}
/* Decode data from the current packet. Return -1 on error, 0 if the packet is finished,
* and 1 if we have a frame (we may have more data in the packet). */
int FFMpeg_Helper::DecodePacket()
{
2005-10-19 23:03:38 +00:00
if( m_iEOF == 0 && m_iCurrentPacketOffset == -1 )
return 0; /* no packet */
2005-10-19 23:03:38 +00:00
while( m_iEOF == 1 || (m_iEOF == 0 && m_iCurrentPacketOffset < pkt.size) )
{
2005-10-19 23:03:38 +00:00
if( m_bGetNextTimestamp )
{
2004-10-07 04:55:31 +00:00
if (pkt.dts != int64_t(AV_NOPTS_VALUE))
2005-10-19 23:03:38 +00:00
m_fPTS = (float)pkt.dts / AV_TIME_BASE;
else
2005-10-19 23:03:38 +00:00
m_fPTS = -1;
m_bGetNextTimestamp = false;
}
2004-08-06 20:22:48 +00:00
/* If we have no data on the first frame, just return EOF; passing an empty packet
2004-02-10 03:06:13 +00:00
* to avcodec_decode_video in this case is crashing it. However, passing an empty
* packet is normal with B-frames, to flush. This may be unnecessary in newer
* versions of avcodec, but I'm waiting until a new stable release to upgrade. */
2005-10-19 23:03:38 +00:00
if( pkt.size == 0 && m_iFrameNumber == -1 )
2004-02-10 03:06:13 +00:00
return 0; /* eof */
int got_frame;
CHECKPOINT;
2004-10-16 00:42:41 +00:00
/* Hack: we need to send size = 0 to flush frames at the end, but we have
* to give it a buffer to read from since it tries to read anyway. */
static uint8_t dummy[FF_INPUT_BUFFER_PADDING_SIZE] = { 0 };
int len = avcodec::avcodec_decode_video(
&m_stream->codec,
&frame, &got_frame,
2004-10-16 00:42:41 +00:00
pkt.size? pkt.data:dummy, pkt.size );
CHECKPOINT;
2005-10-19 23:03:38 +00:00
if( len < 0 )
{
LOG->Warn("avcodec_decode_video: %i", len);
return -1; // XXX
}
2005-10-19 23:03:38 +00:00
m_iCurrentPacketOffset += len;
2005-10-19 23:03:38 +00:00
if( !got_frame )
{
2005-10-19 23:03:38 +00:00
if( m_iEOF == 1 )
m_iEOF = 2;
continue;
}
2005-10-19 23:03:38 +00:00
m_bGetNextTimestamp = true;
2005-10-19 23:03:38 +00:00
if( m_fPTS != -1 )
{
2005-10-19 23:03:38 +00:00
m_fCurrentTimestamp = m_fPTS;
}
else
{
/* If the timestamp is zero, this frame is to be played at the
* time of the last frame plus the length of the last frame. */
2005-10-19 23:03:38 +00:00
m_fCurrentTimestamp += m_fLastFrameDelay;
}
2003-09-21 07:49:36 +00:00
/* Length of this frame: */
2005-10-19 23:03:38 +00:00
m_fLastFrameDelay = (float)m_stream->codec.frame_rate_base / m_stream->codec.frame_rate;
m_fLastFrameDelay += frame.repeat_pict * (m_fLastFrameDelay * 0.5f);
2003-09-21 07:49:36 +00:00
return 1;
}
return 0; /* packet done */
}
void MovieTexture_FFMpeg::ConvertFrame()
{
2004-06-16 00:38:31 +00:00
ASSERT_M( m_ImageWaiting == FRAME_DECODED, ssprintf("%i", m_ImageWaiting ) );
2004-04-04 00:39:23 +00:00
avcodec::AVPicture pict;
2005-10-19 23:03:38 +00:00
pict.data[0] = (unsigned char *) m_pSurface->pixels;
pict.linesize[0] = m_pSurface->pitch;
2005-10-19 23:03:38 +00:00
avcodec::img_convert( &pict, AVPixelFormats[m_AVTexfmt].pf,
(avcodec::AVPicture *) &m_pDecoder->frame, m_pDecoder->m_stream->codec.pix_fmt,
m_pDecoder->m_stream->codec.width, m_pDecoder->m_stream->codec.height );
2004-04-04 00:39:23 +00:00
m_ImageWaiting = FRAME_WAITING;
}
2003-08-29 04:34:10 +00:00
static avcodec::AVStream *FindVideoStream( avcodec::AVFormatContext *m_fctx )
{
for( int stream = 0; stream < m_fctx->nb_streams; ++stream )
{
avcodec::AVStream *enc = m_fctx->streams[stream];
if( enc->codec.codec_type == avcodec::CODEC_TYPE_VIDEO )
return enc;
}
return NULL;
}
2003-09-02 04:01:01 +00:00
MovieTexture_FFMpeg::MovieTexture_FFMpeg( RageTextureID ID ):
2004-06-14 05:36:42 +00:00
RageMovieTexture( ID ),
m_BufferFinished( "BufferFinished", 0 )
2003-08-29 04:34:10 +00:00
{
2003-09-02 19:12:45 +00:00
LOG->Trace( "MovieTexture_FFMpeg::MovieTexture_FFMpeg(%s)", ID.filename.c_str() );
2003-08-29 04:34:10 +00:00
FixLilEndian();
2005-10-19 23:03:38 +00:00
m_pDecoder = new FFMpeg_Helper;
2003-08-29 04:34:10 +00:00
m_uTexHandle = 0;
m_bLoop = true;
m_State = DECODER_QUIT; /* it's quit until we call StartThread */
2005-10-19 23:03:38 +00:00
m_pSurface = NULL;
2004-04-04 00:39:23 +00:00
m_ImageWaiting = FRAME_NONE;
2005-10-19 23:06:23 +00:00
m_fRate = 1;
m_bWantRewind = false;
2005-10-19 23:06:23 +00:00
m_fClock = 0;
m_bFrameSkipMode = false;
m_bThreaded = PREFSMAN->m_bThreadedMovieDecode.Get();
2004-11-30 21:17:13 +00:00
}
CString MovieTexture_FFMpeg::Init()
{
CString sError = CreateDecoder();
if( sError != "" )
return sError;
2003-08-29 04:34:10 +00:00
2005-10-19 23:03:38 +00:00
LOG->Trace( "Bitrate: %i", m_pDecoder->m_stream->codec.bit_rate );
LOG->Trace( "Codec pixel format: %s", avcodec::avcodec_get_pix_fmt_name(m_pDecoder->m_stream->codec.pix_fmt) );
2003-09-02 06:08:02 +00:00
/* Decode one frame, to guarantee that the texture is drawn when this function returns. */
2005-10-19 23:03:38 +00:00
int ret = m_pDecoder->GetFrame();
if( ret == -1 )
2004-11-30 21:17:13 +00:00
return ssprintf( "%s: error getting first frame", GetID().filename.c_str() );
if( ret == 0 )
{
2004-02-10 03:06:13 +00:00
/* There's nothing there. */
2004-11-30 21:17:13 +00:00
return ssprintf( "%s: EOF getting first frame", GetID().filename.c_str() );
}
2004-11-30 21:17:13 +00:00
2004-04-04 00:39:23 +00:00
m_ImageWaiting = FRAME_DECODED;
2004-02-10 03:06:13 +00:00
CreateTexture();
2004-11-30 21:17:13 +00:00
LOG->Trace( "Resolution: %ix%i (%ix%i, %ix%i)",
2004-02-10 03:06:13 +00:00
m_iSourceWidth, m_iSourceHeight,
2004-11-30 21:17:13 +00:00
m_iImageWidth, m_iImageHeight, m_iTextureWidth, m_iTextureHeight );
LOG->Trace( "Texture pixel format: %i", m_AVTexfmt );
2004-02-10 03:06:13 +00:00
CreateFrameRects();
ConvertFrame();
UpdateFrame();
2003-09-02 06:08:02 +00:00
CHECKPOINT;
StartThread();
2004-02-10 03:06:13 +00:00
return CString();
2004-02-10 03:06:13 +00:00
}
2003-08-29 04:34:10 +00:00
2004-01-07 04:08:23 +00:00
MovieTexture_FFMpeg::~MovieTexture_FFMpeg()
{
StopThread();
DestroyDecoder();
DestroyTexture();
2005-10-19 23:03:38 +00:00
delete m_pDecoder;
2004-01-07 04:08:23 +00:00
}
2003-08-29 16:50:47 +00:00
static CString averr_ssprintf( int err, const char *fmt, ... )
{
ASSERT( err < 0 );
va_list va;
va_start(va, fmt);
CString s = vssprintf( fmt, va );
va_end(va);
CString Error;
switch( err )
{
case AVERROR_IO: Error = "I/O error"; break;
case AVERROR_NUMEXPECTED: Error = "number syntax expected in filename"; break;
case AVERROR_INVALIDDATA: Error = "invalid data found"; break;
case AVERROR_NOMEM: Error = "not enough memory"; break;
case AVERROR_NOFMT: Error = "unknown format"; break;
case AVERROR_UNKNOWN: Error = "unknown error"; break;
default: Error = ssprintf( "unknown error %i", err ); break;
}
return s + " (" + Error + ")";
}
2003-12-05 06:35:22 +00:00
int URLRageFile_open( avcodec::URLContext *h, const char *filename, int flags )
{
if( strncmp( filename, "rage://", 7 ) )
{
LOG->Warn("URLRageFile_open: Unexpected path \"%s\"", filename );
return -EIO;
}
filename += 7;
2004-10-18 02:54:15 +00:00
int mode = 0;
switch( flags )
{
case URL_RDONLY: mode = RageFile::READ; break;
case URL_WRONLY: mode = RageFile::WRITE | RageFile::STREAMED; break;
case URL_RDWR: FAIL_M( "O_RDWR unsupported" );
}
2003-12-05 06:35:22 +00:00
RageFile *f = new RageFile;
2004-10-18 02:54:15 +00:00
if( !f->Open(filename, mode) )
2003-12-05 06:35:22 +00:00
{
LOG->Trace("Error opening \"%s\": %s", filename, f->GetError().c_str() );
delete f;
return -EIO;
}
h->is_streamed = false;
h->priv_data = f;
return 0;
}
int URLRageFile_read( avcodec::URLContext *h, unsigned char *buf, int size )
{
RageFile *f = (RageFile *) h->priv_data;
return f->Read( buf, size );
}
2004-10-18 02:54:15 +00:00
int URLRageFile_write( avcodec::URLContext *h, unsigned char *buf, int size )
{
RageFile *f = (RageFile *) h->priv_data;
return f->Write( buf, size );
}
2003-12-05 06:35:22 +00:00
avcodec::offset_t URLRageFile_seek( avcodec::URLContext *h, avcodec::offset_t pos, int whence )
{
RageFile *f = (RageFile *) h->priv_data;
return f->Seek( (int) pos, whence );
}
int URLRageFile_close( avcodec::URLContext *h )
{
RageFile *f = (RageFile *) h->priv_data;
delete f;
return 0;
}
static avcodec::URLProtocol RageProtocol =
{
"rage",
URLRageFile_open,
URLRageFile_read,
2004-10-18 02:54:15 +00:00
URLRageFile_write,
2003-12-05 06:35:22 +00:00
URLRageFile_seek,
URLRageFile_close,
2003-12-05 19:44:41 +00:00
NULL
2003-12-05 06:35:22 +00:00
};
CString FFMpeg_Helper::Open( CString sFile )
2003-12-05 06:35:22 +00:00
{
static bool bDone = false;
if( !bDone )
{
avcodec::av_register_all();
avcodec::register_protocol( &RageProtocol );
bDone = true;
}
2003-12-05 06:35:22 +00:00
int ret = avcodec::av_open_input_file( &m_fctx, "rage://" + sFile, NULL, 0, NULL );
2003-08-29 04:34:10 +00:00
if( ret < 0 )
return ssprintf( averr_ssprintf(ret, "AVCodec: Couldn't open \"%s\"", sFile.c_str()) );
2003-08-29 04:34:10 +00:00
ret = avcodec::av_find_stream_info( m_fctx );
if( ret < 0 )
return ssprintf( averr_ssprintf(ret, "AVCodec (%s): Couldn't find codec parameters", sFile.c_str()) );
2004-02-25 05:26:20 +00:00
avcodec::AVStream *stream = FindVideoStream( m_fctx );
2004-02-25 05:26:20 +00:00
if ( stream == NULL )
return ssprintf( "AVCodec (%s): Couldn't find any video streams", sFile.c_str() );
2003-08-29 04:34:10 +00:00
2004-02-25 05:26:20 +00:00
if( stream->codec.codec_id == avcodec::CODEC_ID_NONE )
return ssprintf( "AVCodec (%s): Unsupported codec %08x", sFile.c_str(), stream->codec.codec_tag );
2004-02-10 02:41:53 +00:00
2004-02-25 05:26:20 +00:00
avcodec::AVCodec *codec = avcodec::avcodec_find_decoder( stream->codec.codec_id );
2003-09-02 08:38:48 +00:00
if( codec == NULL )
return ssprintf( "AVCodec (%s): Couldn't find decoder %i", sFile.c_str(), stream->codec.codec_id );
2003-08-29 04:34:10 +00:00
2003-09-02 08:38:48 +00:00
LOG->Trace("Opening codec %s", codec->name );
2004-02-25 05:26:20 +00:00
ret = avcodec::avcodec_open( &stream->codec, codec );
2003-08-29 04:34:10 +00:00
if ( ret < 0 )
return ssprintf( averr_ssprintf(ret, "AVCodec (%s): Couldn't open codec \"%s\"", sFile.c_str(), codec->name) );
2004-02-25 05:26:20 +00:00
/* Don't set this until we successfully open stream->codec, so we don't try to close it
* on an exception unless it was really opened. */
m_stream = stream;
2004-11-30 21:17:13 +00:00
return CString();
2003-08-29 04:34:10 +00:00
}
void FFMpeg_Helper::Close()
{
if( m_stream )
{
avcodec::avcodec_close( &m_stream->codec );
m_stream = NULL;
}
if( m_fctx )
{
avcodec::av_close_input_file( m_fctx );
m_fctx = NULL;
}
}
CString MovieTexture_FFMpeg::CreateDecoder()
{
return m_pDecoder->Open( GetID().filename );
}
2003-08-29 04:34:10 +00:00
2003-09-02 06:08:02 +00:00
/* Delete the decoder. The decoding thread must be stopped. */
void MovieTexture_FFMpeg::DestroyDecoder()
{
m_pDecoder->Close();
2003-09-02 06:08:02 +00:00
}
/* Delete the surface and texture. The decoding thread must be stopped, and this
* is normally done after destroying the decoder. */
void MovieTexture_FFMpeg::DestroyTexture()
{
2005-10-19 23:03:38 +00:00
delete m_pSurface;
m_pSurface = NULL;
if( m_uTexHandle )
2003-08-29 04:34:10 +00:00
{
DISPLAY->DeleteTexture( m_uTexHandle );
m_uTexHandle = 0;
}
}
2003-09-02 04:01:01 +00:00
void MovieTexture_FFMpeg::CreateTexture()
2003-08-29 04:34:10 +00:00
{
if( m_uTexHandle )
return;
CHECKPOINT;
RageTextureID actualID = GetID();
actualID.iAlphaBits = 0;
/* Cap the max texture size to the hardware max. */
actualID.iMaxSize = min( actualID.iMaxSize, DISPLAY->GetMaxTextureSize() );
2005-10-19 23:03:38 +00:00
m_iSourceWidth = m_pDecoder->m_stream->codec.width;
m_iSourceHeight = m_pDecoder->m_stream->codec.height;
/* image size cannot exceed max size */
m_iImageWidth = min( m_iSourceWidth, actualID.iMaxSize );
m_iImageHeight = min( m_iSourceHeight, actualID.iMaxSize );
/* Texture dimensions need to be a power of two; jump to the next. */
2005-10-19 23:44:07 +00:00
m_iTextureWidth = power_of_two( m_iImageWidth );
m_iTextureHeight = power_of_two( m_iImageHeight );
2005-05-30 11:10:47 +00:00
/* Bogus assignment to shut gcc up. */
PixelFormat pixfmt = PixelFormat_RGBA8;
2005-10-19 23:44:07 +00:00
bool bPreferHighColor = (TEXTUREMAN->GetPrefs().m_iMovieColorDepth == 32);
m_AVTexfmt = FindCompatibleAVFormat( pixfmt, bPreferHighColor );
2003-08-29 04:34:10 +00:00
if( m_AVTexfmt == -1 )
2005-10-19 23:44:07 +00:00
m_AVTexfmt = FindCompatibleAVFormat( pixfmt, !bPreferHighColor );
2003-08-29 04:34:10 +00:00
if( m_AVTexfmt == -1 )
{
/* No dice. Use the first avcodec format of the preferred bit depth,
* and let the display system convert. */
for( m_AVTexfmt = 0; AVPixelFormats[m_AVTexfmt].bpp; ++m_AVTexfmt )
2005-10-19 23:44:07 +00:00
if( AVPixelFormats[m_AVTexfmt].HighColor == bPreferHighColor )
2003-08-29 04:34:10 +00:00
break;
ASSERT( AVPixelFormats[m_AVTexfmt].bpp );
switch( TEXTUREMAN->GetPrefs().m_iMovieColorDepth )
2003-08-29 04:34:10 +00:00
{
default:
ASSERT(0);
case 16:
if( DISPLAY->SupportsTextureFormat(PixelFormat_RGB5) )
pixfmt = PixelFormat_RGB5;
2003-08-29 04:34:10 +00:00
else
pixfmt = PixelFormat_RGBA4; // everything supports RGBA4
2003-08-29 04:34:10 +00:00
break;
case 32:
if( DISPLAY->SupportsTextureFormat(PixelFormat_RGB8) )
pixfmt = PixelFormat_RGB8;
else if( DISPLAY->SupportsTextureFormat(PixelFormat_RGBA8) )
pixfmt = PixelFormat_RGBA8;
else if( DISPLAY->SupportsTextureFormat(PixelFormat_RGB5) )
pixfmt = PixelFormat_RGB5;
2003-08-29 04:34:10 +00:00
else
pixfmt = PixelFormat_RGBA4; // everything supports RGBA4
2003-08-29 04:34:10 +00:00
break;
}
}
2005-10-19 23:03:38 +00:00
if( m_pSurface == NULL )
2003-08-29 04:34:10 +00:00
{
const AVPixelFormat_t *pfd = &AVPixelFormats[m_AVTexfmt];
LOG->Trace("format %i, %08x %08x %08x %08x",
pfd->bpp, pfd->masks[0], pfd->masks[1], pfd->masks[2], pfd->masks[3]);
2005-10-19 23:03:38 +00:00
m_pSurface = CreateSurface( m_iTextureWidth, m_iTextureHeight, pfd->bpp,
2004-06-14 01:09:11 +00:00
pfd->masks[0], pfd->masks[1], pfd->masks[2], pfd->masks[3] );
2003-08-29 04:34:10 +00:00
}
2005-10-19 23:03:38 +00:00
m_uTexHandle = DISPLAY->CreateTexture( pixfmt, m_pSurface, false );
2003-08-29 04:34:10 +00:00
}
2004-04-04 00:39:23 +00:00
/* Handle decoding for a frame. Return true if a frame was decoded, false if not
* (due to pause, EOF, etc). If true is returned, we'll be in FRAME_DECODED. */
bool MovieTexture_FFMpeg::DecodeFrame()
{
2004-06-16 00:38:31 +00:00
ASSERT_M( m_ImageWaiting == FRAME_NONE, ssprintf("%i", m_ImageWaiting) );
2003-08-29 04:34:10 +00:00
if( m_State == DECODER_QUIT )
2004-04-02 23:00:29 +00:00
return false;
CHECKPOINT;
/* Read a frame. */
2005-10-19 23:03:38 +00:00
int ret = m_pDecoder->GetFrame();
2004-04-02 23:00:29 +00:00
if( ret == -1 )
return false;
2005-10-19 23:03:38 +00:00
if( m_bWantRewind && m_pDecoder->GetTimestamp() == 0 )
2004-04-02 23:00:29 +00:00
m_bWantRewind = false; /* ignore */
if( ret == 0 )
{
/* EOF. */
if( !m_bLoop )
return false;
LOG->Trace( "File \"%s\" looping", GetID().filename.c_str() );
m_bWantRewind = true;
}
if( m_bWantRewind )
{
m_bWantRewind = false;
2004-10-07 14:37:05 +00:00
/* When resetting the clock, set it back by the length of the last frame,
* so it has a proper delay. */
2005-10-19 23:41:48 +00:00
float fDelay = m_pDecoder->GetFrameDuration();
2004-10-07 14:37:05 +00:00
2004-04-02 23:00:29 +00:00
/* Restart. */
DestroyDecoder();
2004-11-30 21:17:13 +00:00
CString sError = CreateDecoder();
if( sError != "" )
RageException::Throw( "Error rewinding stream %s: %s", GetID().filename.c_str(), sError.c_str() );
2004-04-02 23:00:29 +00:00
2005-10-19 23:03:38 +00:00
m_pDecoder->Init();
2005-10-19 23:06:23 +00:00
m_fClock = -fDelay;
2004-04-02 23:00:29 +00:00
return false;
}
/* We got a frame. */
2004-04-04 00:39:23 +00:00
m_ImageWaiting = FRAME_DECODED;
return true;
}
/*
* Call when m_ImageWaiting == FRAME_DECODED.
* Returns:
* == 0 if the currently decoded frame is ready to be displayed
* > 0 (seconds) if it's not yet time to display;
* == -1 if we're behind and the frame should be skipped
*/
float MovieTexture_FFMpeg::CheckFrameTime()
{
2004-06-16 00:38:31 +00:00
ASSERT_M( m_ImageWaiting == FRAME_DECODED, ssprintf("%i", m_ImageWaiting) );
2004-04-04 00:39:23 +00:00
2005-10-19 23:06:23 +00:00
if( m_fRate == 0 )
2004-08-31 03:52:00 +00:00
return 1; // "a long time until the next frame"
2005-10-19 23:06:23 +00:00
const float fOffset = (m_pDecoder->GetTimestamp() - m_fClock) / m_fRate;
2004-04-02 23:00:29 +00:00
/* If we're ahead, we're decoding too fast; delay. */
2005-10-19 23:06:23 +00:00
if( fOffset > 0.00001f )
2004-04-02 23:00:29 +00:00
{
2005-10-19 23:06:23 +00:00
if( m_bFrameSkipMode )
2004-04-02 23:00:29 +00:00
{
/* We're caught up; stop skipping frames. */
LOG->Trace( "stopped skipping frames" );
2005-10-19 23:06:23 +00:00
m_bFrameSkipMode = false;
2004-04-02 23:00:29 +00:00
}
2005-10-19 23:06:23 +00:00
return fOffset;
2004-04-04 00:39:23 +00:00
}
2004-04-02 23:00:29 +00:00
2004-04-04 00:39:23 +00:00
/*
* We're behind by -Offset seconds.
*
* If we're just slightly behind, don't worry about it; we'll simply
* not sleep, so we'll move as fast as we can to catch up.
*
* If we're far behind, we're short on CPU. Skip texture updates; this
* is a big bottleneck on many systems.
*
* If we hit a threshold, start skipping frames via #1. If we do that,
* don't stop once we hit the threshold; keep doing it until we're fully
* caught up.
*
* We should try to notice if we simply don't have enough CPU for the video;
* it's better to just stay in frame skip mode than to enter and exit it
* constantly, but we don't want to do that due to a single timing glitch.
*/
const float FrameSkipThreshold = 0.5f;
2005-10-19 23:06:23 +00:00
if( -fOffset >= FrameSkipThreshold && !m_bFrameSkipMode )
2004-04-04 00:39:23 +00:00
{
LOG->Trace( "(%s) Time is %f, and the movie is at %f. Entering frame skip mode.",
2005-10-19 23:06:23 +00:00
GetID().filename.c_str(), m_fClock, m_pDecoder->GetTimestamp());
m_bFrameSkipMode = true;
2004-04-02 23:00:29 +00:00
}
2005-10-19 23:06:23 +00:00
if( m_bFrameSkipMode && m_pDecoder->m_stream->codec.frame_number % 2 )
2004-04-04 00:39:23 +00:00
return -1; /* skip */
2004-04-02 23:00:29 +00:00
2004-04-04 00:39:23 +00:00
return 0;
}
2004-04-02 23:00:29 +00:00
2004-04-04 00:39:23 +00:00
void MovieTexture_FFMpeg::DiscardFrame()
{
2004-06-16 00:38:31 +00:00
ASSERT_M( m_ImageWaiting == FRAME_DECODED, ssprintf("%i", m_ImageWaiting) );
2004-04-04 00:39:23 +00:00
m_ImageWaiting = FRAME_NONE;
2004-04-02 23:00:29 +00:00
}
2003-08-29 04:34:10 +00:00
2003-09-02 04:01:01 +00:00
void MovieTexture_FFMpeg::DecoderThread()
2003-08-29 04:34:10 +00:00
{
2003-09-25 03:39:52 +00:00
#if defined(_WINDOWS)
/* Windows likes to boost priority when processes come out of a wait state. We don't
* want that, since it'll result in us having a small priority boost after each movie
* frame, resulting in skips in the gameplay thread. */
2004-07-22 23:04:44 +00:00
if( !SetThreadPriorityBoost(GetCurrentThread(), TRUE) && GetLastError() != ERROR_CALL_NOT_IMPLEMENTED )
LOG->Warn( werr_ssprintf(GetLastError(), "SetThreadPriorityBoost failed") );
2003-09-25 03:39:52 +00:00
#endif
2003-08-29 04:34:10 +00:00
CHECKPOINT;
2003-09-02 07:47:37 +00:00
2003-08-29 04:34:10 +00:00
while( m_State != DECODER_QUIT )
{
2004-04-04 00:39:23 +00:00
if( m_ImageWaiting == FRAME_NONE )
DecodeFrame();
/* If we still have no frame, we're at EOF and we didn't loop. */
2004-04-04 00:39:23 +00:00
if( m_ImageWaiting != FRAME_DECODED )
{
usleep( 10000 );
continue;
}
2004-04-04 00:39:23 +00:00
const float fTime = CheckFrameTime();
2004-08-31 03:52:00 +00:00
if( fTime == -1 ) // skip frame
2004-04-04 00:39:23 +00:00
{
DiscardFrame();
}
2004-08-31 03:52:00 +00:00
else if( fTime > 0 ) // not time to decode a new frame yet
2004-04-04 00:39:23 +00:00
{
2004-08-31 03:52:00 +00:00
/* This needs to be relatively short so that we wake up quickly
2005-10-19 23:06:23 +00:00
* from being paused or for changes in m_fRate. */
2004-08-31 03:52:00 +00:00
usleep( 10000 );
2004-04-04 00:39:23 +00:00
}
2004-08-31 03:52:00 +00:00
else // fTime == 0
{
{
/* The only reason m_BufferFinished might be non-zero right now (before
* ConvertFrame()) is if we're quitting. */
int n = m_BufferFinished.GetValue();
ASSERT_M( n == 0 || m_State == DECODER_QUIT, ssprintf("%i, %i", n, m_State) );
}
ConvertFrame();
2004-04-04 00:39:23 +00:00
2004-08-31 03:52:00 +00:00
/* We just went into FRAME_WAITING. Don't actually check; the main thread
2004-09-25 06:33:46 +00:00
* will change us back to FRAME_NONE without locking, and poke m_BufferFinished.
* Don't time out on this; if a new screen has started loading, this might not
* return for a while. */
m_BufferFinished.Wait( false );
2004-08-31 03:52:00 +00:00
/* If the frame wasn't used, then we must be shutting down. */
ASSERT_M( m_ImageWaiting == FRAME_NONE || m_State == DECODER_QUIT, ssprintf("%i, %i", m_ImageWaiting, m_State) );
}
2003-08-29 04:34:10 +00:00
}
CHECKPOINT;
}
2003-09-02 04:01:01 +00:00
void MovieTexture_FFMpeg::Update(float fDeltaTime)
2003-08-29 04:34:10 +00:00
{
/* We might need to decode more than one frame per update. However, there
* have been bugs in ffmpeg that cause it to not handle EOF properly, which
* could make this never return, so let's play it safe. */
int iMax = 4;
while( --iMax )
2004-04-04 00:39:23 +00:00
{
if( !m_bThreaded )
2004-04-04 00:39:23 +00:00
{
/* If we don't have a frame decoded, decode one. */
if( m_ImageWaiting == FRAME_NONE )
DecodeFrame();
/* If we have a frame decoded, see if it's time to display it. */
if( m_ImageWaiting == FRAME_DECODED )
{
float fTime = CheckFrameTime();
if( fTime > 0 )
return;
else if( fTime == -1 )
DiscardFrame();
else
ConvertFrame();
}
2004-04-04 00:39:23 +00:00
}
/* Note that if there's an image waiting, we *must* signal m_BufferFinished, or
* the decoder thread may sit around waiting for it, even though Pause and Play
* calls, causing the clock to keep running. */
if( m_ImageWaiting != FRAME_WAITING )
return;
CHECKPOINT;
UpdateFrame();
if( m_bThreaded )
m_BufferFinished.Post();
2004-04-04 00:39:23 +00:00
}
2004-04-02 23:15:29 +00:00
LOG->MapLog( "ffmpeg_looping", "MovieTexture_FFMpeg::Update looping" );
}
2004-04-04 00:39:23 +00:00
/* Call from the main thread when m_ImageWaiting == FRAME_WAITING to update the
* texture. Sets FRAME_NONE. Does not signal m_BufferFinished. */
void MovieTexture_FFMpeg::UpdateFrame()
{
2004-04-04 00:39:23 +00:00
ASSERT_M( m_ImageWaiting == FRAME_WAITING, ssprintf("%i", m_ImageWaiting) );
2003-08-29 04:34:10 +00:00
/* Just in case we were invalidated: */
CreateTexture();
CHECKPOINT;
DISPLAY->UpdateTexture(
m_uTexHandle,
2005-10-19 23:03:38 +00:00
m_pSurface,
2003-08-29 04:34:10 +00:00
0, 0,
m_iImageWidth, m_iImageHeight );
CHECKPOINT;
2004-04-04 00:39:23 +00:00
m_ImageWaiting = FRAME_NONE;
2003-08-29 04:34:10 +00:00
}
2003-09-02 04:01:01 +00:00
void MovieTexture_FFMpeg::Reload()
2003-08-29 04:34:10 +00:00
{
}
2003-09-02 04:01:01 +00:00
void MovieTexture_FFMpeg::StartThread()
2003-08-29 04:34:10 +00:00
{
ASSERT( m_State == DECODER_QUIT );
m_State = DECODER_RUNNING;
2003-09-02 04:01:01 +00:00
m_DecoderThread.SetName( ssprintf("MovieTexture_FFMpeg(%s)", GetID().filename.c_str()) );
2004-04-02 23:15:29 +00:00
if( m_bThreaded )
m_DecoderThread.Create( DecoderThread_start, this );
2003-08-29 04:34:10 +00:00
}
2003-09-02 04:01:01 +00:00
void MovieTexture_FFMpeg::StopThread()
2003-08-29 04:34:10 +00:00
{
if( !m_DecoderThread.IsCreated() )
2003-08-29 04:34:10 +00:00
return;
2004-02-10 03:06:13 +00:00
LOG->Trace("Shutting down decoder thread ...");
2003-08-29 04:34:10 +00:00
m_State = DECODER_QUIT;
/* Make sure we don't deadlock waiting for m_BufferFinished. */
2004-06-14 05:36:42 +00:00
m_BufferFinished.Post();
2003-08-29 05:39:47 +00:00
CHECKPOINT;
2003-08-29 04:34:10 +00:00
m_DecoderThread.Wait();
2003-08-29 05:39:47 +00:00
CHECKPOINT;
2003-08-29 04:34:10 +00:00
2004-04-04 00:39:23 +00:00
m_ImageWaiting = FRAME_NONE;
2003-09-07 03:34:35 +00:00
2003-08-29 04:34:10 +00:00
/* Clear the above post, if the thread didn't. */
2004-06-14 05:36:42 +00:00
m_BufferFinished.TryWait();
2003-08-29 04:34:10 +00:00
LOG->Trace("Decoder thread shut down.");
}
2003-09-02 04:01:01 +00:00
void MovieTexture_FFMpeg::SetPosition( float fSeconds )
2003-08-29 04:34:10 +00:00
{
ASSERT( m_State != DECODER_QUIT );
/* We can reset to 0, but I don't think this API supports fast seeking
* yet. I don't think we ever actually seek except to 0 right now,
* anyway. XXX */
if( fSeconds != 0 )
{
2003-09-02 04:01:01 +00:00
LOG->Warn( "MovieTexture_FFMpeg::SetPosition(%f): non-0 seeking unsupported; ignored", fSeconds );
2003-08-29 04:34:10 +00:00
return;
}
2003-09-19 01:23:30 +00:00
LOG->Trace( "Seek to %f", fSeconds );
m_bWantRewind = true;
2003-08-29 04:34:10 +00:00
}
/* This is used to decode data. */
void MovieTexture_FFMpeg::DecodeSeconds( float fSeconds )
{
2005-10-19 23:06:23 +00:00
m_fClock += fSeconds * m_fRate;
/* If we're not threaded, we want to be sure to decode any new frames now,
* and not on the next frame. Update() may have already been called for this
* frame; call it again to be sure. */
Update(0);
}
2004-05-15 22:07:41 +00:00
/*
* (c) 2003-2004 Glenn Maynard
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/