CVideoHandler.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  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. return false;
  530. data = CResourceHandler::get()->load(resource);
  531. static const int BUFFER_SIZE = 4096;
  532. unsigned char * buffer = (unsigned char *)av_malloc(BUFFER_SIZE);// will be freed by ffmpeg
  533. context = avio_alloc_context( buffer, BUFFER_SIZE, 0, (void *)this, lodRead, NULL, lodSeek);
  534. format = avformat_alloc_context();
  535. format->pb = context;
  536. // filename is not needed - file was already open and stored in this->data;
  537. int avfopen = avformat_open_input(&format, "dummyFilename", nullptr, nullptr);
  538. if (avfopen != 0)
  539. {
  540. return false;
  541. }
  542. // Retrieve stream information
  543. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  544. if (av_find_stream_info(format) < 0)
  545. #else
  546. if (avformat_find_stream_info(format, NULL) < 0)
  547. #endif
  548. return false;
  549. // Find the first video stream
  550. stream = -1;
  551. for(ui32 i=0; i<format->nb_streams; i++)
  552. {
  553. if (format->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
  554. {
  555. stream = i;
  556. break;
  557. }
  558. }
  559. if (stream < 0)
  560. // No video stream in that file
  561. return false;
  562. // Get a pointer to the codec context for the video stream
  563. codecContext = format->streams[stream]->codec;
  564. // Find the decoder for the video stream
  565. codec = avcodec_find_decoder(codecContext->codec_id);
  566. if (codec == NULL)
  567. {
  568. // Unsupported codec
  569. return false;
  570. }
  571. // Open codec
  572. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 6, 0)
  573. if ( avcodec_open(codecContext, codec) < 0 )
  574. #else
  575. if ( avcodec_open2(codecContext, codec, NULL) < 0 )
  576. #endif
  577. {
  578. // Could not open codec
  579. codec = NULL;
  580. return false;
  581. }
  582. // Allocate video frame
  583. frame = avcodec_alloc_frame();
  584. // Allocate a place to put our YUV image on that screen
  585. if (useOverlay)
  586. {
  587. overlay = SDL_CreateYUVOverlay(codecContext->width, codecContext->height,
  588. SDL_YV12_OVERLAY, screen);
  589. }
  590. else
  591. {
  592. dest = CSDL_Ext::newSurface(codecContext->width, codecContext->height);
  593. destRect.x = destRect.y = 0;
  594. destRect.w = codecContext->width;
  595. destRect.h = codecContext->height;
  596. }
  597. if (overlay == NULL && dest == NULL)
  598. return false;
  599. // Convert the image into YUV format that SDL uses
  600. if (overlay)
  601. {
  602. sws = sws_getContext(codecContext->width, codecContext->height,
  603. codecContext->pix_fmt, codecContext->width, codecContext->height,
  604. PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
  605. }
  606. else
  607. {
  608. PixelFormat screenFormat = PIX_FMT_NONE;
  609. if (screen->format->Bshift > screen->format->Rshift)
  610. {
  611. // this a BGR surface
  612. switch (screen->format->BytesPerPixel)
  613. {
  614. case 2: screenFormat = PIX_FMT_BGR565; break;
  615. case 3: screenFormat = PIX_FMT_BGR24; break;
  616. case 4: screenFormat = PIX_FMT_BGR32; break;
  617. default: return false;
  618. }
  619. }
  620. else
  621. {
  622. // this a RGB surface
  623. switch (screen->format->BytesPerPixel)
  624. {
  625. case 2: screenFormat = PIX_FMT_RGB565; break;
  626. case 3: screenFormat = PIX_FMT_RGB24; break;
  627. case 4: screenFormat = PIX_FMT_RGB32; break;
  628. default: return false;
  629. }
  630. }
  631. sws = sws_getContext(codecContext->width, codecContext->height,
  632. codecContext->pix_fmt, codecContext->width, codecContext->height,
  633. screenFormat, SWS_BICUBIC, NULL, NULL, NULL);
  634. }
  635. if (sws == NULL)
  636. return false;
  637. pos.w = codecContext->width;
  638. pos.h = codecContext->height;
  639. return true;
  640. }
  641. // Read the next frame. Return false on error/end of file.
  642. bool CVideoPlayer::nextFrame()
  643. {
  644. AVPacket packet;
  645. int frameFinished = 0;
  646. bool gotError = false;
  647. if (sws == NULL)
  648. return false;
  649. while(!frameFinished)
  650. {
  651. int ret = av_read_frame(format, &packet);
  652. if (ret < 0)
  653. {
  654. // Error. It's probably an end of file.
  655. if (doLoop && !gotError)
  656. {
  657. // Rewind
  658. if (av_seek_frame(format, stream, 0, 0) < 0)
  659. break;
  660. gotError = true;
  661. }
  662. else
  663. {
  664. break;
  665. }
  666. }
  667. else
  668. {
  669. // Is this a packet from the video stream?
  670. if (packet.stream_index == stream)
  671. {
  672. // Decode video frame
  673. avcodec_decode_video2(codecContext, frame, &frameFinished, &packet);
  674. // Did we get a video frame?
  675. if (frameFinished)
  676. {
  677. AVPicture pict;
  678. if (overlay) {
  679. SDL_LockYUVOverlay(overlay);
  680. pict.data[0] = overlay->pixels[0];
  681. pict.data[1] = overlay->pixels[2];
  682. pict.data[2] = overlay->pixels[1];
  683. pict.linesize[0] = overlay->pitches[0];
  684. pict.linesize[1] = overlay->pitches[2];
  685. pict.linesize[2] = overlay->pitches[1];
  686. sws_scale(sws, frame->data, frame->linesize,
  687. 0, codecContext->height, pict.data, pict.linesize);
  688. SDL_UnlockYUVOverlay(overlay);
  689. }
  690. else
  691. {
  692. pict.data[0] = (ui8 *)dest->pixels;
  693. pict.linesize[0] = dest->pitch;
  694. sws_scale(sws, frame->data, frame->linesize,
  695. 0, codecContext->height, pict.data, pict.linesize);
  696. }
  697. }
  698. }
  699. av_free_packet(&packet);
  700. }
  701. }
  702. return frameFinished != 0;
  703. }
  704. void CVideoPlayer::show( int x, int y, SDL_Surface *dst, bool update )
  705. {
  706. if (sws == NULL)
  707. return;
  708. pos.x = x;
  709. pos.y = y;
  710. CSDL_Ext::blitSurface(dest, &destRect, dst, &pos);
  711. if (update)
  712. SDL_UpdateRect(dst, pos.x, pos.y, pos.w, pos.h);
  713. }
  714. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  715. {
  716. show(x, y, dst, update);
  717. }
  718. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  719. {
  720. if (sws == NULL)
  721. return;
  722. if (refreshCount <= 0)
  723. {
  724. refreshCount = refreshWait;
  725. if (nextFrame())
  726. show(x,y,dst,update);
  727. else
  728. {
  729. open(fname);
  730. nextFrame();
  731. // The y position is wrong at the first frame.
  732. // Note: either the windows player or the linux player is
  733. // broken. Compensate here until the bug is found.
  734. show(x, y--, dst, update);
  735. }
  736. }
  737. else
  738. {
  739. redraw(x, y, dst, update);
  740. }
  741. refreshCount --;
  742. }
  743. void CVideoPlayer::close()
  744. {
  745. fname = "";
  746. if (sws)
  747. {
  748. sws_freeContext(sws);
  749. sws = NULL;
  750. }
  751. if (overlay)
  752. {
  753. SDL_FreeYUVOverlay(overlay);
  754. overlay = NULL;
  755. }
  756. if (dest)
  757. {
  758. SDL_FreeSurface(dest);
  759. dest = NULL;
  760. }
  761. if (frame)
  762. {
  763. av_free(frame);
  764. frame = NULL;
  765. }
  766. if (codec)
  767. {
  768. avcodec_close(codecContext);
  769. codec = NULL;
  770. codecContext = NULL;
  771. }
  772. if (format)
  773. {
  774. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  775. av_close_input_file(format);
  776. format = NULL;
  777. #else
  778. avformat_close_input(&format);
  779. #endif
  780. }
  781. if (context)
  782. {
  783. av_free(context);
  784. context = nullptr;
  785. }
  786. }
  787. // Plays a video. Only works for overlays.
  788. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  789. {
  790. // Note: either the windows player or the linux player is
  791. // broken. Compensate here until the bug is found.
  792. y--;
  793. pos.x = x;
  794. pos.y = y;
  795. while(nextFrame())
  796. {
  797. if(stopOnKey && keyDown())
  798. return false;
  799. SDL_DisplayYUVOverlay(overlay, &pos);
  800. // Wait 3 frames
  801. GH.mainFPSmng->framerateDelay();
  802. GH.mainFPSmng->framerateDelay();
  803. GH.mainFPSmng->framerateDelay();
  804. }
  805. return true;
  806. }
  807. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  808. {
  809. open(name, false, true);
  810. bool ret = playVideo(x, y, dst, stopOnKey);
  811. close();
  812. return ret;
  813. }
  814. CVideoPlayer::~CVideoPlayer()
  815. {
  816. close();
  817. }
  818. #endif
  819. #endif