CVideoHandler.cpp 20 KB

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