CVideoHandler.cpp 21 KB

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