CVideoHandler.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  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. //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. #if defined(_WIN32) && (_MSC_VER < 1800 || !defined(USE_FFMPEG))
  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 don`t 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. auto data = CResourceHandler::get()->load(videoID)->readAll();
  355. // try to determine video format using magic number from header (3 bytes, SMK or BIK)
  356. std::string magic(reinterpret_cast<char*>(data.first.get()), 3);
  357. if (magic == "BIK")
  358. current = &bikPlayer;
  359. else if (magic == "SMK")
  360. current = &smkPlayer;
  361. else
  362. throw std::runtime_error("Unknown video format: " + magic);
  363. std::ofstream out(name, std::ofstream::binary);
  364. out.exceptions(std::ifstream::failbit | std::ifstream::badbit);
  365. out.write(reinterpret_cast<char*>(data.first.get()), data.second);
  366. }
  367. current->open(name);
  368. return true;
  369. }
  370. catch(std::exception &e)
  371. {
  372. current = nullptr;
  373. logGlobal->warnStream() << "Failed to open video file " << name << ": " << e.what();
  374. }
  375. return false;
  376. }
  377. void CVideoPlayer::close()
  378. {
  379. if(!current)
  380. {
  381. logGlobal->warnStream() << "Closing no opened player...?";
  382. return;
  383. }
  384. current->close();
  385. current = nullptr;
  386. if(!DeleteFileA(fname.c_str()))
  387. {
  388. logGlobal->errorStream() << "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. #ifdef _MSC_VER
  487. #pragma comment(lib, "avcodec.lib")
  488. #pragma comment(lib, "avutil.lib")
  489. #pragma comment(lib, "avformat.lib")
  490. #pragma comment(lib, "swscale.lib")
  491. #endif // _MSC_VER
  492. #ifndef DISABLE_VIDEO
  493. // Define a set of functions to read data
  494. static int lodRead(void* opaque, uint8_t* buf, int size)
  495. {
  496. auto video = reinterpret_cast<CVideoPlayer *>(opaque);
  497. return video->data->read(buf, size);
  498. }
  499. static si64 lodSeek(void * opaque, si64 pos, int whence)
  500. {
  501. auto video = reinterpret_cast<CVideoPlayer *>(opaque);
  502. if (whence & AVSEEK_SIZE)
  503. return video->data->getSize();
  504. return video->data->seek(pos);
  505. }
  506. CVideoPlayer::CVideoPlayer()
  507. {
  508. format = nullptr;
  509. frame = nullptr;
  510. codec = nullptr;
  511. sws = nullptr;
  512. overlay = nullptr;
  513. dest = nullptr;
  514. context = nullptr;
  515. // Register codecs. TODO: May be overkill. Should call a
  516. // combination of av_register_input_format() /
  517. // av_register_output_format() / av_register_protocol() instead.
  518. av_register_all();
  519. }
  520. bool CVideoPlayer::open(std::string fname)
  521. {
  522. return open(fname, true, false);
  523. }
  524. // loop = to loop through the video
  525. // useOverlay = directly write to the screen.
  526. bool CVideoPlayer::open(std::string fname, bool loop, bool useOverlay)
  527. {
  528. close();
  529. this->fname = fname;
  530. refreshWait = 3;
  531. refreshCount = -1;
  532. doLoop = loop;
  533. ResourceID resource(std::string("Video/") + fname, EResType::VIDEO);
  534. if (!CResourceHandler::get()->existsResource(resource))
  535. {
  536. logGlobal->errorStream() << "Error: video " << resource.getName() << " was not found";
  537. return false;
  538. }
  539. data = CResourceHandler::get()->load(resource);
  540. static const int BUFFER_SIZE = 4096;
  541. unsigned char * buffer = (unsigned char *)av_malloc(BUFFER_SIZE);// will be freed by ffmpeg
  542. context = avio_alloc_context( buffer, BUFFER_SIZE, 0, (void *)this, lodRead, nullptr, lodSeek);
  543. format = avformat_alloc_context();
  544. format->pb = context;
  545. // filename is not needed - file was already open and stored in this->data;
  546. int avfopen = avformat_open_input(&format, "dummyFilename", nullptr, nullptr);
  547. if (avfopen != 0)
  548. {
  549. return false;
  550. }
  551. // Retrieve stream information
  552. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  553. if (av_find_stream_info(format) < 0)
  554. #else
  555. if (avformat_find_stream_info(format, nullptr) < 0)
  556. #endif
  557. return false;
  558. // Find the first video stream
  559. stream = -1;
  560. for(ui32 i=0; i<format->nb_streams; i++)
  561. {
  562. if (format->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
  563. {
  564. stream = i;
  565. break;
  566. }
  567. }
  568. if (stream < 0)
  569. // No video stream in that file
  570. return false;
  571. // Get a pointer to the codec context for the video stream
  572. codecContext = format->streams[stream]->codec;
  573. // Find the decoder for the video stream
  574. codec = avcodec_find_decoder(codecContext->codec_id);
  575. if (codec == nullptr)
  576. {
  577. // Unsupported codec
  578. return false;
  579. }
  580. // Open codec
  581. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 6, 0)
  582. if ( avcodec_open(codecContext, codec) < 0 )
  583. #else
  584. if ( avcodec_open2(codecContext, codec, nullptr) < 0 )
  585. #endif
  586. {
  587. // Could not open codec
  588. codec = nullptr;
  589. return false;
  590. }
  591. // Allocate video frame
  592. frame = avcodec_alloc_frame();
  593. // Allocate a place to put our YUV image on that screen
  594. if (useOverlay)
  595. {
  596. overlay = SDL_CreateYUVOverlay(codecContext->width, codecContext->height,
  597. SDL_YV12_OVERLAY, screen);
  598. }
  599. else
  600. {
  601. dest = CSDL_Ext::newSurface(codecContext->width, codecContext->height);
  602. destRect.x = destRect.y = 0;
  603. destRect.w = codecContext->width;
  604. destRect.h = codecContext->height;
  605. }
  606. if (overlay == nullptr && dest == nullptr)
  607. return false;
  608. // Convert the image into YUV format that SDL uses
  609. if (overlay)
  610. {
  611. sws = sws_getContext(codecContext->width, codecContext->height,
  612. codecContext->pix_fmt, codecContext->width, codecContext->height,
  613. PIX_FMT_YUV420P, SWS_BICUBIC, nullptr, nullptr, nullptr);
  614. }
  615. else
  616. {
  617. PixelFormat screenFormat = PIX_FMT_NONE;
  618. if (screen->format->Bshift > screen->format->Rshift)
  619. {
  620. // this a BGR surface
  621. switch (screen->format->BytesPerPixel)
  622. {
  623. case 2: screenFormat = PIX_FMT_BGR565; break;
  624. case 3: screenFormat = PIX_FMT_BGR24; break;
  625. case 4: screenFormat = PIX_FMT_BGR32; break;
  626. default: return false;
  627. }
  628. }
  629. else
  630. {
  631. // this a RGB surface
  632. switch (screen->format->BytesPerPixel)
  633. {
  634. case 2: screenFormat = PIX_FMT_RGB565; break;
  635. case 3: screenFormat = PIX_FMT_RGB24; break;
  636. case 4: screenFormat = PIX_FMT_RGB32; break;
  637. default: return false;
  638. }
  639. }
  640. sws = sws_getContext(codecContext->width, codecContext->height,
  641. codecContext->pix_fmt, codecContext->width, codecContext->height,
  642. screenFormat, SWS_BICUBIC, nullptr, nullptr, nullptr);
  643. }
  644. if (sws == nullptr)
  645. return false;
  646. pos.w = codecContext->width;
  647. pos.h = codecContext->height;
  648. return true;
  649. }
  650. // Read the next frame. Return false on error/end of file.
  651. bool CVideoPlayer::nextFrame()
  652. {
  653. AVPacket packet;
  654. int frameFinished = 0;
  655. bool gotError = false;
  656. if (sws == nullptr)
  657. return false;
  658. while(!frameFinished)
  659. {
  660. int ret = av_read_frame(format, &packet);
  661. if (ret < 0)
  662. {
  663. // Error. It's probably an end of file.
  664. if (doLoop && !gotError)
  665. {
  666. // Rewind
  667. if (av_seek_frame(format, stream, 0, 0) < 0)
  668. break;
  669. gotError = true;
  670. }
  671. else
  672. {
  673. break;
  674. }
  675. }
  676. else
  677. {
  678. // Is this a packet from the video stream?
  679. if (packet.stream_index == stream)
  680. {
  681. // Decode video frame
  682. avcodec_decode_video2(codecContext, frame, &frameFinished, &packet);
  683. // Did we get a video frame?
  684. if (frameFinished)
  685. {
  686. AVPicture pict;
  687. if (overlay) {
  688. SDL_LockYUVOverlay(overlay);
  689. pict.data[0] = overlay->pixels[0];
  690. pict.data[1] = overlay->pixels[2];
  691. pict.data[2] = overlay->pixels[1];
  692. pict.linesize[0] = overlay->pitches[0];
  693. pict.linesize[1] = overlay->pitches[2];
  694. pict.linesize[2] = overlay->pitches[1];
  695. sws_scale(sws, frame->data, frame->linesize,
  696. 0, codecContext->height, pict.data, pict.linesize);
  697. SDL_UnlockYUVOverlay(overlay);
  698. }
  699. else
  700. {
  701. pict.data[0] = (ui8 *)dest->pixels;
  702. pict.linesize[0] = dest->pitch;
  703. sws_scale(sws, frame->data, frame->linesize,
  704. 0, codecContext->height, pict.data, pict.linesize);
  705. }
  706. }
  707. }
  708. av_free_packet(&packet);
  709. }
  710. }
  711. return frameFinished != 0;
  712. }
  713. void CVideoPlayer::show( int x, int y, SDL_Surface *dst, bool update )
  714. {
  715. if (sws == nullptr)
  716. return;
  717. pos.x = x;
  718. pos.y = y;
  719. CSDL_Ext::blitSurface(dest, &destRect, dst, &pos);
  720. if (update)
  721. SDL_UpdateRect(dst, pos.x, pos.y, pos.w, pos.h);
  722. }
  723. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  724. {
  725. show(x, y, dst, update);
  726. }
  727. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  728. {
  729. if (sws == nullptr)
  730. return;
  731. if (refreshCount <= 0)
  732. {
  733. refreshCount = refreshWait;
  734. if (nextFrame())
  735. show(x,y,dst,update);
  736. else
  737. {
  738. open(fname);
  739. nextFrame();
  740. // The y position is wrong at the first frame.
  741. // Note: either the windows player or the linux player is
  742. // broken. Compensate here until the bug is found.
  743. show(x, y--, dst, update);
  744. }
  745. }
  746. else
  747. {
  748. redraw(x, y, dst, update);
  749. }
  750. refreshCount --;
  751. }
  752. void CVideoPlayer::close()
  753. {
  754. fname = "";
  755. if (sws)
  756. {
  757. sws_freeContext(sws);
  758. sws = nullptr;
  759. }
  760. if (overlay)
  761. {
  762. SDL_FreeYUVOverlay(overlay);
  763. overlay = nullptr;
  764. }
  765. if (dest)
  766. {
  767. SDL_FreeSurface(dest);
  768. dest = nullptr;
  769. }
  770. if (frame)
  771. {
  772. av_free(frame);
  773. frame = nullptr;
  774. }
  775. if (codec)
  776. {
  777. avcodec_close(codecContext);
  778. codec = nullptr;
  779. codecContext = nullptr;
  780. }
  781. if (format)
  782. {
  783. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  784. av_close_input_file(format);
  785. format = nullptr;
  786. #else
  787. avformat_close_input(&format);
  788. #endif
  789. }
  790. if (context)
  791. {
  792. av_free(context);
  793. context = nullptr;
  794. }
  795. }
  796. // Plays a video. Only works for overlays.
  797. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  798. {
  799. // Note: either the windows player or the linux player is
  800. // broken. Compensate here until the bug is found.
  801. y--;
  802. pos.x = x;
  803. pos.y = y;
  804. while(nextFrame())
  805. {
  806. if(stopOnKey && keyDown())
  807. return false;
  808. SDL_DisplayYUVOverlay(overlay, &pos);
  809. // Wait 3 frames
  810. GH.mainFPSmng->framerateDelay();
  811. GH.mainFPSmng->framerateDelay();
  812. GH.mainFPSmng->framerateDelay();
  813. }
  814. return true;
  815. }
  816. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  817. {
  818. open(name, false, true);
  819. bool ret = playVideo(x, y, dst, stopOnKey);
  820. close();
  821. return ret;
  822. }
  823. CVideoPlayer::~CVideoPlayer()
  824. {
  825. close();
  826. }
  827. #endif
  828. #endif