CVideoHandler.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  1. #include "StdInc.h"
  2. #include <SDL.h>
  3. #include "CVideoHandler.h"
  4. #include "gui/CGuiHandler.h"
  5. #include "gui/SDL_Extensions.h"
  6. #include "CPlayerInterface.h"
  7. #include "../lib/filesystem/Filesystem.h"
  8. extern CGuiHandler GH; //global gui handler
  9. #ifndef DISABLE_VIDEO
  10. //reads events and returns true on key down
  11. static bool keyDown()
  12. {
  13. SDL_Event ev;
  14. while(SDL_PollEvent(&ev))
  15. {
  16. if(ev.type == SDL_KEYDOWN || ev.type == SDL_MOUSEBUTTONDOWN)
  17. return true;
  18. }
  19. return false;
  20. }
  21. #endif
  22. #if defined(_WIN32) && (_MSC_VER < 1800 || !defined(USE_FFMPEG))
  23. void checkForError(bool throwing = true)
  24. {
  25. int error = GetLastError();
  26. if(!error)
  27. return;
  28. logGlobal->errorStream() << "Error " << error << " encountered!";
  29. std::string msg;
  30. char* pTemp = nullptr;
  31. FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
  32. nullptr, error, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), (LPSTR)&pTemp, 1, nullptr );
  33. logGlobal->errorStream() << "Error: " << pTemp;
  34. msg = pTemp;
  35. LocalFree( pTemp );
  36. pTemp = nullptr;
  37. if(throwing)
  38. throw std::runtime_error(msg);
  39. }
  40. void blitBuffer(char *buffer, int x, int y, int w, int h, SDL_Surface *dst)
  41. {
  42. const int bpp = dst->format->BytesPerPixel;
  43. char *dest;
  44. for(int i = h; i > 0; i--)
  45. {
  46. dest = (char*)dst->pixels + dst->pitch*(y+h-i) + x*dst->format->BytesPerPixel;
  47. memcpy(dest, buffer, bpp*w);
  48. buffer += bpp*w;
  49. }
  50. }
  51. void DLLHandler::Instantiate(const char *filename)
  52. {
  53. name = filename;
  54. dll = LoadLibraryA(filename);
  55. if(!dll)
  56. {
  57. logGlobal->errorStream() << "Failed loading " << filename;
  58. checkForError(true);
  59. }
  60. }
  61. void *DLLHandler::FindAddress(const char *symbol)
  62. {
  63. void *ret;
  64. if(!dll)
  65. {
  66. logGlobal->errorStream() << "Cannot look for " << symbol << " because DLL hasn't been appropriately loaded!";
  67. return nullptr;
  68. }
  69. ret = (void*) GetProcAddress(dll,symbol);
  70. if(!ret)
  71. {
  72. logGlobal->errorStream() << "Failed to find " << symbol << " in " << name;
  73. checkForError();
  74. }
  75. return ret;
  76. }
  77. DLLHandler::~DLLHandler()
  78. {
  79. if(dll)
  80. {
  81. if(!FreeLibrary(dll))
  82. {
  83. logGlobal->errorStream() << "Failed to free " << name;
  84. checkForError();
  85. }
  86. }
  87. }
  88. DLLHandler::DLLHandler()
  89. {
  90. dll = nullptr;
  91. }
  92. CBIKHandler::CBIKHandler()
  93. {
  94. Instantiate("BINKW32.DLL");
  95. //binkGetError = FindAddress("_BinkGetError@0");
  96. binkOpen = (BinkOpen)FindAddress("_BinkOpen@8");
  97. binkSetSoundSystem = (BinkSetSoundSystem)FindAddress("_BinkSetSoundSystem@8");
  98. //getPalette = (BinkGetPalette)FindAddress("_BinkGetPalette@4");
  99. binkNextFrame = (BinkNextFrame)FindAddress("_BinkNextFrame@4");
  100. binkDoFrame = (BinkDoFrame)FindAddress("_BinkDoFrame@4");
  101. binkCopyToBuffer = (BinkCopyToBuffer)FindAddress("_BinkCopyToBuffer@28");
  102. binkWait = (BinkWait)FindAddress("_BinkWait@4");
  103. binkClose = (BinkClose)FindAddress("_BinkClose@4");
  104. hBinkFile = nullptr;
  105. hBink = nullptr;
  106. buffer = nullptr;
  107. bufferSize = 0;
  108. }
  109. bool CBIKHandler::open(std::string name)
  110. {
  111. hBinkFile = CreateFileA
  112. (
  113. name.c_str(), // file name
  114. GENERIC_READ, // access mode
  115. FILE_SHARE_READ, // share mode
  116. nullptr, // Security Descriptor
  117. OPEN_EXISTING, // how to create
  118. FILE_ATTRIBUTE_NORMAL,//FILE_FLAG_SEQUENTIAL_SCAN, // file attributes
  119. 0 // handle to template file
  120. );
  121. if(hBinkFile == INVALID_HANDLE_VALUE)
  122. {
  123. logGlobal->errorStream() << "BIK handler: failed to open " << name;
  124. goto checkErrorAndClean;
  125. }
  126. //GCC wants scope of waveout to don`t cross labels/swith/goto
  127. {
  128. void *waveout = GetProcAddress(dll,"_BinkOpenWaveOut@4");
  129. if(waveout)
  130. binkSetSoundSystem(waveout,nullptr);
  131. }
  132. hBink = binkOpen(hBinkFile, 0x8a800000);
  133. if(!hBink)
  134. {
  135. logGlobal->errorStream() << "bink failed to open " << name;
  136. goto checkErrorAndClean;
  137. }
  138. allocBuffer();
  139. return true;
  140. checkErrorAndClean:
  141. CloseHandle(hBinkFile);
  142. hBinkFile = nullptr;
  143. checkForError();
  144. throw std::runtime_error("BIK failed opening video!");
  145. }
  146. void CBIKHandler::show( int x, int y, SDL_Surface *dst, bool update )
  147. {
  148. const int w = hBink->width,
  149. h = hBink->height,
  150. Bpp = dst->format->BytesPerPixel;
  151. int mode = -1;
  152. //screen color depth might have changed... (eg. because F4)
  153. if(bufferSize != w * h * Bpp)
  154. {
  155. freeBuffer();
  156. allocBuffer(Bpp);
  157. }
  158. switch(Bpp)
  159. {
  160. case 2:
  161. mode = 3; //565, mode 2 is 555 probably
  162. break;
  163. case 3:
  164. mode = 0;
  165. break;
  166. case 4:
  167. mode = 1;
  168. break;
  169. default:
  170. return; //not supported screen depth
  171. }
  172. binkDoFrame(hBink);
  173. binkCopyToBuffer(hBink, buffer, w*Bpp, h, 0, 0, mode);
  174. blitBuffer(buffer, x, y, w, h, dst);
  175. if(update)
  176. SDL_UpdateRect(dst, x, y, w, h);
  177. }
  178. bool CBIKHandler::nextFrame()
  179. {
  180. binkNextFrame(hBink);
  181. return true;
  182. }
  183. void CBIKHandler::close()
  184. {
  185. binkClose(hBink);
  186. hBink = nullptr;
  187. CloseHandle(hBinkFile);
  188. hBinkFile = nullptr;
  189. delete [] buffer;
  190. buffer = nullptr;
  191. bufferSize = 0;
  192. }
  193. bool CBIKHandler::wait()
  194. {
  195. return binkWait(hBink);
  196. }
  197. int CBIKHandler::curFrame() const
  198. {
  199. return hBink->currentFrame;
  200. }
  201. int CBIKHandler::frameCount() const
  202. {
  203. return hBink->frameCount;
  204. }
  205. void CBIKHandler::redraw( int x, int y, SDL_Surface *dst, bool update )
  206. {
  207. int w = hBink->width, h = hBink->height;
  208. blitBuffer(buffer, x, y, w, h, dst);
  209. if(update)
  210. SDL_UpdateRect(dst, x, y, w, h);
  211. }
  212. void CBIKHandler::allocBuffer(int Bpp)
  213. {
  214. if(!Bpp) Bpp = screen->format->BytesPerPixel;
  215. bufferSize = hBink->width * hBink->height * Bpp;
  216. buffer = new char[bufferSize];
  217. }
  218. void CBIKHandler::freeBuffer()
  219. {
  220. delete [] buffer;
  221. buffer = nullptr;
  222. bufferSize = 0;
  223. }
  224. bool CSmackPlayer::nextFrame()
  225. {
  226. ptrSmackNextFrame(data);
  227. return true;
  228. }
  229. bool CSmackPlayer::wait()
  230. {
  231. return ptrSmackWait(data);
  232. }
  233. CSmackPlayer::CSmackPlayer() : data(nullptr)
  234. {
  235. Instantiate("smackw32.dll");
  236. ptrSmackNextFrame = (SmackNextFrame)FindAddress("_SmackNextFrame@4");
  237. ptrSmackWait = (SmackWait)FindAddress("_SmackWait@4");
  238. ptrSmackDoFrame = (SmackDoFrame)FindAddress("_SmackDoFrame@4");
  239. ptrSmackToBuffer = (SmackToBuffer)FindAddress("_SmackToBuffer@28");
  240. ptrSmackOpen = (SmackOpen)FindAddress("_SmackOpen@12");
  241. ptrSmackSoundOnOff = (SmackSoundOnOff)FindAddress("_SmackSoundOnOff@8");
  242. ptrSmackClose = (SmackClose)FindAddress("_SmackClose@4");
  243. ptrVolumePan = (SmackVolumePan)FindAddress("_SmackVolumePan@16");
  244. }
  245. CSmackPlayer::~CSmackPlayer()
  246. {
  247. if(data)
  248. close();
  249. }
  250. void CSmackPlayer::close()
  251. {
  252. ptrSmackClose(data);
  253. data = nullptr;
  254. }
  255. bool CSmackPlayer::open( std::string name )
  256. {
  257. Uint32 flags[2] = {0xff400, 0xfe400};
  258. data = ptrSmackOpen( (void*)name.c_str(), flags[1], -1);
  259. if (!data)
  260. {
  261. logGlobal->errorStream() << "Smack cannot open " << name;
  262. checkForError();
  263. throw std::runtime_error("SMACK failed opening video");
  264. }
  265. buffer = new char[data->width*data->height*2];
  266. buf = buffer+data->width*(data->height-1)*2; // adjust pointer position for later use by 'SmackToBuffer'
  267. //ptrVolumePan(data, 0xfe000, 3640 * GDefaultOptions.musicVolume / 11, 0x8000); //set volume
  268. return true;
  269. }
  270. void CSmackPlayer::show( int x, int y, SDL_Surface *dst, bool update)
  271. {
  272. int w = data->width;
  273. int stripe = (-w*2) & (~3);
  274. //put frame to the buffer
  275. ptrSmackToBuffer(data, 0, 0, stripe, w, buf, 0x80000000);
  276. ptrSmackDoFrame(data);
  277. redraw(x, y, dst, update);
  278. }
  279. int CSmackPlayer::curFrame() const
  280. {
  281. return data->currentFrame;
  282. }
  283. int CSmackPlayer::frameCount() const
  284. {
  285. return data->frameCount;
  286. }
  287. void CSmackPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  288. {
  289. int w = std::min<int>(data->width, dst->w - x), h = std::min<int>(data->height, dst->h - y);
  290. /* Lock the screen for direct access to the pixels */
  291. if ( SDL_MUSTLOCK(dst) )
  292. {
  293. if ( SDL_LockSurface(dst) < 0 )
  294. {
  295. fprintf(stderr, "Can't lock screen: %s\n", SDL_GetError());
  296. return;
  297. }
  298. }
  299. // draw the frame
  300. Uint16* addr = (Uint16*) (buffer+w*(h-1)*2-2);
  301. if(dst->format->BytesPerPixel >= 3)
  302. {
  303. for( int j=0; j<h-1; j++) // why -1 ?
  304. {
  305. for ( int i=w-1; i>=0; i--)
  306. {
  307. Uint16 pixel = *addr;
  308. Uint8 *p = (Uint8 *)dst->pixels + (j+y) * dst->pitch + (i + x) * dst->format->BytesPerPixel;
  309. p[2] = ((pixel & 0x7c00) >> 10) * 8;
  310. p[1] = ((pixel & 0x3e0) >> 5) * 8;
  311. p[0] = ((pixel & 0x1F)) * 8;
  312. addr--;
  313. }
  314. }
  315. }
  316. else if(dst->format->BytesPerPixel == 2)
  317. {
  318. for( int j=0; j<h-1; j++) // why -1 ?
  319. {
  320. for ( int i=w-1; i>=0; i--)
  321. {
  322. //convert rgb 555 to 565
  323. Uint16 pixel = *addr;
  324. Uint16 *p = (Uint16 *)((Uint8 *)dst->pixels + (j+y) * dst->pitch + (i + x) * dst->format->BytesPerPixel);
  325. *p = (pixel & 0x1F)
  326. + ((pixel & 0x3e0) << 1)
  327. + ((pixel & 0x7c00) << 1);
  328. addr--;
  329. }
  330. }
  331. }
  332. if ( SDL_MUSTLOCK(dst) )
  333. {
  334. SDL_UnlockSurface(dst);
  335. }
  336. if(update)
  337. SDL_UpdateRect(dst, x, y, w, h);
  338. }
  339. CVideoPlayer::CVideoPlayer()
  340. {
  341. current = nullptr;
  342. }
  343. CVideoPlayer::~CVideoPlayer()
  344. {
  345. }
  346. bool CVideoPlayer::open(std::string name)
  347. {
  348. fname = name;
  349. first = true;
  350. try
  351. {
  352. // Extract video from video.vid so we can play it.
  353. // We can handle only videos in form of single file, no archive support yet.
  354. {
  355. ResourceID videoID = ResourceID("VIDEO/" + name, EResType::VIDEO);
  356. auto data = CResourceHandler::get()->load(videoID)->readAll();
  357. // try to determine video format using magic number from header (3 bytes, SMK or BIK)
  358. std::string magic(reinterpret_cast<char*>(data.first.get()), 3);
  359. if (magic == "BIK")
  360. current = &bikPlayer;
  361. else if (magic == "SMK")
  362. current = &smkPlayer;
  363. else
  364. throw std::runtime_error("Unknown video format: " + magic);
  365. std::ofstream out(name, std::ofstream::binary);
  366. out.exceptions(std::ifstream::failbit | std::ifstream::badbit);
  367. out.write(reinterpret_cast<char*>(data.first.get()), data.second);
  368. }
  369. current->open(name);
  370. return true;
  371. }
  372. catch(std::exception &e)
  373. {
  374. current = nullptr;
  375. logGlobal->warnStream() << "Failed to open video file " << name << ": " << e.what();
  376. }
  377. return false;
  378. }
  379. void CVideoPlayer::close()
  380. {
  381. if(!current)
  382. {
  383. logGlobal->warnStream() << "Closing no opened player...?";
  384. return;
  385. }
  386. current->close();
  387. current = nullptr;
  388. if(!DeleteFileA(fname.c_str()))
  389. {
  390. logGlobal->errorStream() << "Cannot remove temporarily extracted video file: " << fname;
  391. checkForError(false);
  392. }
  393. fname.clear();
  394. }
  395. bool CVideoPlayer::nextFrame()
  396. {
  397. if(current)
  398. {
  399. current->nextFrame();
  400. return true;
  401. }
  402. else
  403. return false;
  404. }
  405. void CVideoPlayer::show(int x, int y, SDL_Surface *dst, bool update)
  406. {
  407. if(current)
  408. current->show(x, y, dst, update);
  409. }
  410. bool CVideoPlayer::wait()
  411. {
  412. if(current)
  413. return current->wait();
  414. else
  415. return false;
  416. }
  417. int CVideoPlayer::curFrame() const
  418. {
  419. if(current)
  420. return current->curFrame();
  421. else
  422. return -1;
  423. }
  424. int CVideoPlayer::frameCount() const
  425. {
  426. if(current)
  427. return current->frameCount();
  428. else
  429. return -1;
  430. }
  431. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  432. {
  433. if(!open(name))
  434. return false;
  435. bool ret = playVideo(x, y, dst, stopOnKey);
  436. close();
  437. return ret;
  438. }
  439. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  440. {
  441. if(!current)
  442. return;
  443. bool w = false;
  444. if(!first)
  445. {
  446. w = wait(); //check if should keep current frame
  447. if(!w)
  448. nextFrame();
  449. }
  450. else
  451. {
  452. first = false;
  453. }
  454. if(!w)
  455. {
  456. show(x,y,dst,update);
  457. }
  458. else if (forceRedraw)
  459. {
  460. redraw(x, y, dst, update);
  461. }
  462. }
  463. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  464. {
  465. if(current)
  466. current->redraw(x, y, dst, update);
  467. }
  468. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  469. {
  470. if(!current)
  471. return false;
  472. int frame = 0;
  473. while(frame < frameCount()) //play all frames
  474. {
  475. if(stopOnKey && keyDown())
  476. return false;
  477. if(!wait())
  478. {
  479. show(x, y, dst);
  480. nextFrame();
  481. frame++;
  482. }
  483. SDL_Delay(20);
  484. }
  485. return true;
  486. }
  487. #else
  488. #ifdef _MSC_VER
  489. #pragma comment(lib, "avcodec.lib")
  490. #pragma comment(lib, "avutil.lib")
  491. #pragma comment(lib, "avformat.lib")
  492. #pragma comment(lib, "swscale.lib")
  493. #endif // _MSC_VER
  494. #ifndef DISABLE_VIDEO
  495. // Define a set of functions to read data
  496. static int lodRead(void* opaque, uint8_t* buf, int size)
  497. {
  498. auto video = reinterpret_cast<CVideoPlayer *>(opaque);
  499. return video->data->read(buf, size);
  500. }
  501. static si64 lodSeek(void * opaque, si64 pos, int whence)
  502. {
  503. auto video = reinterpret_cast<CVideoPlayer *>(opaque);
  504. if (whence & AVSEEK_SIZE)
  505. return video->data->getSize();
  506. return video->data->seek(pos);
  507. }
  508. CVideoPlayer::CVideoPlayer()
  509. {
  510. format = nullptr;
  511. frame = nullptr;
  512. codec = nullptr;
  513. sws = nullptr;
  514. overlay = nullptr;
  515. dest = nullptr;
  516. context = nullptr;
  517. // Register codecs. TODO: May be overkill. Should call a
  518. // combination of av_register_input_format() /
  519. // av_register_output_format() / av_register_protocol() instead.
  520. av_register_all();
  521. }
  522. bool CVideoPlayer::open(std::string fname)
  523. {
  524. return open(fname, true, false);
  525. }
  526. // loop = to loop through the video
  527. // useOverlay = directly write to the screen.
  528. bool CVideoPlayer::open(std::string fname, bool loop, bool useOverlay)
  529. {
  530. close();
  531. this->fname = fname;
  532. refreshWait = 3;
  533. refreshCount = -1;
  534. doLoop = loop;
  535. ResourceID resource(std::string("Video/") + fname, EResType::VIDEO);
  536. if (!CResourceHandler::get()->existsResource(resource))
  537. {
  538. logGlobal->errorStream() << "Error: video " << resource.getName() << " was not found";
  539. return false;
  540. }
  541. data = CResourceHandler::get()->load(resource);
  542. static const int BUFFER_SIZE = 4096;
  543. unsigned char * buffer = (unsigned char *)av_malloc(BUFFER_SIZE);// will be freed by ffmpeg
  544. context = avio_alloc_context( buffer, BUFFER_SIZE, 0, (void *)this, lodRead, nullptr, lodSeek);
  545. format = avformat_alloc_context();
  546. format->pb = context;
  547. // filename is not needed - file was already open and stored in this->data;
  548. int avfopen = avformat_open_input(&format, "dummyFilename", nullptr, nullptr);
  549. if (avfopen != 0)
  550. {
  551. return false;
  552. }
  553. // Retrieve stream information
  554. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  555. if (av_find_stream_info(format) < 0)
  556. #else
  557. if (avformat_find_stream_info(format, nullptr) < 0)
  558. #endif
  559. return false;
  560. // Find the first video stream
  561. stream = -1;
  562. for(ui32 i=0; i<format->nb_streams; i++)
  563. {
  564. if (format->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
  565. {
  566. stream = i;
  567. break;
  568. }
  569. }
  570. if (stream < 0)
  571. // No video stream in that file
  572. return false;
  573. // Get a pointer to the codec context for the video stream
  574. codecContext = format->streams[stream]->codec;
  575. // Find the decoder for the video stream
  576. codec = avcodec_find_decoder(codecContext->codec_id);
  577. if (codec == nullptr)
  578. {
  579. // Unsupported codec
  580. return false;
  581. }
  582. // Open codec
  583. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 6, 0)
  584. if ( avcodec_open(codecContext, codec) < 0 )
  585. #else
  586. if ( avcodec_open2(codecContext, codec, nullptr) < 0 )
  587. #endif
  588. {
  589. // Could not open codec
  590. codec = nullptr;
  591. return false;
  592. }
  593. // Allocate video frame
  594. frame = avcodec_alloc_frame();
  595. // Allocate a place to put our YUV image on that screen
  596. if (useOverlay)
  597. {
  598. overlay = SDL_CreateYUVOverlay(codecContext->width, codecContext->height,
  599. SDL_YV12_OVERLAY, screen);
  600. }
  601. else
  602. {
  603. dest = CSDL_Ext::newSurface(codecContext->width, codecContext->height);
  604. destRect.x = destRect.y = 0;
  605. destRect.w = codecContext->width;
  606. destRect.h = codecContext->height;
  607. }
  608. if (overlay == nullptr && dest == nullptr)
  609. return false;
  610. // Convert the image into YUV format that SDL uses
  611. if (overlay)
  612. {
  613. sws = sws_getContext(codecContext->width, codecContext->height,
  614. codecContext->pix_fmt, codecContext->width, codecContext->height,
  615. PIX_FMT_YUV420P, SWS_BICUBIC, nullptr, nullptr, nullptr);
  616. }
  617. else
  618. {
  619. PixelFormat screenFormat = PIX_FMT_NONE;
  620. if (screen->format->Bshift > screen->format->Rshift)
  621. {
  622. // this a BGR surface
  623. switch (screen->format->BytesPerPixel)
  624. {
  625. case 2: screenFormat = PIX_FMT_BGR565; break;
  626. case 3: screenFormat = PIX_FMT_BGR24; break;
  627. case 4: screenFormat = PIX_FMT_BGR32; break;
  628. default: return false;
  629. }
  630. }
  631. else
  632. {
  633. // this a RGB surface
  634. switch (screen->format->BytesPerPixel)
  635. {
  636. case 2: screenFormat = PIX_FMT_RGB565; break;
  637. case 3: screenFormat = PIX_FMT_RGB24; break;
  638. case 4: screenFormat = PIX_FMT_RGB32; break;
  639. default: return false;
  640. }
  641. }
  642. sws = sws_getContext(codecContext->width, codecContext->height,
  643. codecContext->pix_fmt, codecContext->width, codecContext->height,
  644. screenFormat, SWS_BICUBIC, nullptr, nullptr, nullptr);
  645. }
  646. if (sws == nullptr)
  647. return false;
  648. pos.w = codecContext->width;
  649. pos.h = codecContext->height;
  650. return true;
  651. }
  652. // Read the next frame. Return false on error/end of file.
  653. bool CVideoPlayer::nextFrame()
  654. {
  655. AVPacket packet;
  656. int frameFinished = 0;
  657. bool gotError = false;
  658. if (sws == nullptr)
  659. return false;
  660. while(!frameFinished)
  661. {
  662. int ret = av_read_frame(format, &packet);
  663. if (ret < 0)
  664. {
  665. // Error. It's probably an end of file.
  666. if (doLoop && !gotError)
  667. {
  668. // Rewind
  669. if (av_seek_frame(format, stream, 0, 0) < 0)
  670. break;
  671. gotError = true;
  672. }
  673. else
  674. {
  675. break;
  676. }
  677. }
  678. else
  679. {
  680. // Is this a packet from the video stream?
  681. if (packet.stream_index == stream)
  682. {
  683. // Decode video frame
  684. avcodec_decode_video2(codecContext, frame, &frameFinished, &packet);
  685. // Did we get a video frame?
  686. if (frameFinished)
  687. {
  688. AVPicture pict;
  689. if (overlay) {
  690. SDL_LockYUVOverlay(overlay);
  691. pict.data[0] = overlay->pixels[0];
  692. pict.data[1] = overlay->pixels[2];
  693. pict.data[2] = overlay->pixels[1];
  694. pict.linesize[0] = overlay->pitches[0];
  695. pict.linesize[1] = overlay->pitches[2];
  696. pict.linesize[2] = overlay->pitches[1];
  697. sws_scale(sws, frame->data, frame->linesize,
  698. 0, codecContext->height, pict.data, pict.linesize);
  699. SDL_UnlockYUVOverlay(overlay);
  700. }
  701. else
  702. {
  703. pict.data[0] = (ui8 *)dest->pixels;
  704. pict.linesize[0] = dest->pitch;
  705. sws_scale(sws, frame->data, frame->linesize,
  706. 0, codecContext->height, pict.data, pict.linesize);
  707. }
  708. }
  709. }
  710. av_free_packet(&packet);
  711. }
  712. }
  713. return frameFinished != 0;
  714. }
  715. void CVideoPlayer::show( int x, int y, SDL_Surface *dst, bool update )
  716. {
  717. if (sws == nullptr)
  718. return;
  719. pos.x = x;
  720. pos.y = y;
  721. CSDL_Ext::blitSurface(dest, &destRect, dst, &pos);
  722. if (update)
  723. SDL_UpdateRect(dst, pos.x, pos.y, pos.w, pos.h);
  724. }
  725. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  726. {
  727. show(x, y, dst, update);
  728. }
  729. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  730. {
  731. if (sws == nullptr)
  732. return;
  733. if (refreshCount <= 0)
  734. {
  735. refreshCount = refreshWait;
  736. if (nextFrame())
  737. show(x,y,dst,update);
  738. else
  739. {
  740. open(fname);
  741. nextFrame();
  742. // The y position is wrong at the first frame.
  743. // Note: either the windows player or the linux player is
  744. // broken. Compensate here until the bug is found.
  745. show(x, y--, dst, update);
  746. }
  747. }
  748. else
  749. {
  750. redraw(x, y, dst, update);
  751. }
  752. refreshCount --;
  753. }
  754. void CVideoPlayer::close()
  755. {
  756. fname = "";
  757. if (sws)
  758. {
  759. sws_freeContext(sws);
  760. sws = nullptr;
  761. }
  762. if (overlay)
  763. {
  764. SDL_FreeYUVOverlay(overlay);
  765. overlay = nullptr;
  766. }
  767. if (dest)
  768. {
  769. SDL_FreeSurface(dest);
  770. dest = nullptr;
  771. }
  772. if (frame)
  773. {
  774. av_free(frame);
  775. frame = nullptr;
  776. }
  777. if (codec)
  778. {
  779. avcodec_close(codecContext);
  780. codec = nullptr;
  781. codecContext = nullptr;
  782. }
  783. if (format)
  784. {
  785. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  786. av_close_input_file(format);
  787. format = nullptr;
  788. #else
  789. avformat_close_input(&format);
  790. #endif
  791. }
  792. if (context)
  793. {
  794. av_free(context);
  795. context = nullptr;
  796. }
  797. }
  798. // Plays a video. Only works for overlays.
  799. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  800. {
  801. // Note: either the windows player or the linux player is
  802. // broken. Compensate here until the bug is found.
  803. y--;
  804. pos.x = x;
  805. pos.y = y;
  806. while(nextFrame())
  807. {
  808. if(stopOnKey && keyDown())
  809. return false;
  810. SDL_DisplayYUVOverlay(overlay, &pos);
  811. // Wait 3 frames
  812. GH.mainFPSmng->framerateDelay();
  813. GH.mainFPSmng->framerateDelay();
  814. GH.mainFPSmng->framerateDelay();
  815. }
  816. return true;
  817. }
  818. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  819. {
  820. open(name, false, true);
  821. bool ret = playVideo(x, y, dst, stopOnKey);
  822. close();
  823. return ret;
  824. }
  825. CVideoPlayer::~CVideoPlayer()
  826. {
  827. close();
  828. }
  829. #endif
  830. #endif