CVideoHandler.cpp 22 KB

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