CVideoHandler.cpp 23 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  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. #if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 117, 0)
  488. // Define a set of functions to read data
  489. static int lodRead(void* opaque, uint8_t* buf, int size)
  490. {
  491. auto video = reinterpret_cast<CVideoPlayer *>(opaque);
  492. vstd::amin(size, video->length - video->offset);
  493. if (size < 0)
  494. return -1;
  495. memcpy(buf, video->data + video->offset, size);
  496. video->offset += size;
  497. return 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->length;
  504. video->offset = pos;
  505. vstd::amin(video->offset, video->length);
  506. return video->offset;
  507. }
  508. #else
  509. static const char *protocol_name = "lod";
  510. // Open a pseudo file. Name is something like 'lod:0x56432ab6c43df8fe'
  511. static int lodOpen(URLContext *context, const char *filename, int flags)
  512. {
  513. CVideoPlayer *video;
  514. // Retrieve pointer to CVideoPlayer object
  515. filename += strlen(protocol_name) + 1;
  516. video = (CVideoPlayer *)(uintptr_t)strtoull(filename, NULL, 16);
  517. // TODO: check flags ?
  518. context->priv_data = video;
  519. return 0;
  520. }
  521. static int lodClose(URLContext* h)
  522. {
  523. return 0;
  524. }
  525. // Define a set of functions to read data
  526. static int lodRead(URLContext *context, ui8 *buf, int size)
  527. {
  528. CVideoPlayer *video = (CVideoPlayer *)context->priv_data;
  529. vstd::amin(size, video->length - video->offset);
  530. if (size < 0)
  531. return -1;
  532. // TODO: can we avoid that copy ?
  533. memcpy(buf, video->data + video->offset, size);
  534. video->offset += size;
  535. return size;
  536. }
  537. static si64 lodSeek(URLContext *context, si64 pos, int whence)
  538. {
  539. CVideoPlayer *video = (CVideoPlayer *)context->priv_data;
  540. if (whence & AVSEEK_SIZE)
  541. return video->length;
  542. video->offset = pos;
  543. vstd::amin(video->offset, video->length);
  544. return video->offset;
  545. }
  546. static URLProtocol lod_protocol =
  547. {
  548. protocol_name,
  549. lodOpen,
  550. lodRead,
  551. NULL, // no write
  552. lodSeek,
  553. lodClose
  554. };
  555. #endif
  556. CVideoPlayer::CVideoPlayer()
  557. {
  558. format = NULL;
  559. frame = NULL;
  560. codec = NULL;
  561. sws = NULL;
  562. overlay = NULL;
  563. dest = NULL;
  564. context = nullptr;
  565. buffer = nullptr;
  566. // Register codecs. TODO: May be overkill. Should call a
  567. // combination of av_register_input_format() /
  568. // av_register_output_format() / av_register_protocol() instead.
  569. av_register_all();
  570. #if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 117, 0)
  571. #elif LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 69, 0)
  572. // Register our protocol 'lod' so we can directly read from mmaped memory
  573. av_register_protocol2(&lod_protocol, sizeof(lod_protocol));
  574. #else
  575. av_register_protocol(&lod_protocol);
  576. #endif
  577. }
  578. bool CVideoPlayer::open(std::string fname)
  579. {
  580. return open(fname, true, false);
  581. }
  582. // loop = to loop through the video
  583. // useOverlay = directly write to the screen.
  584. bool CVideoPlayer::open(std::string fname, bool loop, bool useOverlay)
  585. {
  586. close();
  587. this->fname = fname;
  588. offset = 0;
  589. refreshWait = 3;
  590. refreshCount = -1;
  591. doLoop = loop;
  592. ResourceID resource(std::string("Video/") + fname, EResType::VIDEO);
  593. if (CResourceHandler::get()->existsResource(resource))
  594. {
  595. auto extracted = CResourceHandler::get()->loadData(resource);
  596. data = (char *)extracted.first.release();
  597. length = extracted.second;
  598. }
  599. else
  600. {
  601. data = nullptr;
  602. length = 0;
  603. return false;
  604. }
  605. #if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 117, 0)
  606. static const int BUFFER_SIZE = 4096;
  607. buffer = (unsigned char *)av_malloc(BUFFER_SIZE);// will be freed by ffmpeg
  608. context = avio_alloc_context( buffer, BUFFER_SIZE, 0, (void *)this, lodRead, NULL, lodSeek);
  609. format = avformat_alloc_context();
  610. format->pb = context;
  611. // filename is not needed - file was already open and stored in this->data;
  612. int avfopen = avformat_open_input(&format, "dummyFilename", nullptr, nullptr);
  613. #else
  614. std::string filePath;
  615. filePath.resize(100);
  616. // Create our URL name with the 'lod' protocol as a prefix and a
  617. // back pointer to our object. Should be 32 and 64 bits compatible.
  618. sprintf(&filePath[0], "%s:0x%016llx", protocol_name, (unsigned long long)(uintptr_t)this);
  619. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 0, 0)
  620. int avfopen = av_open_input_file(&format, filePath.c_str(), NULL, 0, NULL);
  621. #else
  622. int avfopen = avformat_open_input(&format, filePath.c_str(), NULL, NULL);
  623. #endif
  624. #endif
  625. if (avfopen != 0)
  626. {
  627. return false;
  628. }
  629. // Retrieve stream information
  630. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  631. if (av_find_stream_info(format) < 0)
  632. #else
  633. if (avformat_find_stream_info(format, NULL) < 0)
  634. #endif
  635. return false;
  636. // Find the first video stream
  637. stream = -1;
  638. for(ui32 i=0; i<format->nb_streams; i++)
  639. {
  640. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 0, 0)
  641. if (format->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO)
  642. #else
  643. if (format->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
  644. #endif
  645. {
  646. stream = i;
  647. break;
  648. }
  649. }
  650. if (stream < 0)
  651. // No video stream in that file
  652. return false;
  653. // Get a pointer to the codec context for the video stream
  654. codecContext = format->streams[stream]->codec;
  655. // Find the decoder for the video stream
  656. codec = avcodec_find_decoder(codecContext->codec_id);
  657. if (codec == NULL)
  658. {
  659. // Unsupported codec
  660. return false;
  661. }
  662. // Open codec
  663. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 6, 0)
  664. if ( avcodec_open(codecContext, codec) < 0 )
  665. #else
  666. if ( avcodec_open2(codecContext, codec, NULL) < 0 )
  667. #endif
  668. {
  669. // Could not open codec
  670. codec = NULL;
  671. return false;
  672. }
  673. // Allocate video frame
  674. frame = avcodec_alloc_frame();
  675. // Allocate a place to put our YUV image on that screen
  676. if (useOverlay)
  677. {
  678. overlay = SDL_CreateYUVOverlay(codecContext->width, codecContext->height,
  679. SDL_YV12_OVERLAY, screen);
  680. }
  681. else
  682. {
  683. dest = CSDL_Ext::newSurface(codecContext->width, codecContext->height);
  684. destRect.x = destRect.y = 0;
  685. destRect.w = codecContext->width;
  686. destRect.h = codecContext->height;
  687. }
  688. if (overlay == NULL && dest == NULL)
  689. return false;
  690. // Convert the image into YUV format that SDL uses
  691. if (overlay)
  692. {
  693. sws = sws_getContext(codecContext->width, codecContext->height,
  694. codecContext->pix_fmt, codecContext->width, codecContext->height,
  695. PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
  696. }
  697. else
  698. {
  699. PixelFormat screenFormat = PIX_FMT_NONE;
  700. if (screen->format->Bshift > screen->format->Rshift)
  701. {
  702. // this a BGR surface
  703. switch (screen->format->BytesPerPixel)
  704. {
  705. case 2: screenFormat = PIX_FMT_BGR565; break;
  706. case 3: screenFormat = PIX_FMT_BGR24; break;
  707. case 4: screenFormat = PIX_FMT_BGR32; break;
  708. default: return false;
  709. }
  710. }
  711. else
  712. {
  713. // this a RGB surface
  714. switch (screen->format->BytesPerPixel)
  715. {
  716. case 2: screenFormat = PIX_FMT_RGB565; break;
  717. case 3: screenFormat = PIX_FMT_RGB24; break;
  718. case 4: screenFormat = PIX_FMT_RGB32; break;
  719. default: return false;
  720. }
  721. }
  722. sws = sws_getContext(codecContext->width, codecContext->height,
  723. codecContext->pix_fmt, codecContext->width, codecContext->height,
  724. screenFormat, SWS_BICUBIC, NULL, NULL, NULL);
  725. }
  726. if (sws == NULL)
  727. return false;
  728. pos.w = codecContext->width;
  729. pos.h = codecContext->height;
  730. return true;
  731. }
  732. // Read the next frame. Return false on error/end of file.
  733. bool CVideoPlayer::nextFrame()
  734. {
  735. AVPacket packet;
  736. int frameFinished = 0;
  737. bool gotError = false;
  738. if (sws == NULL)
  739. return false;
  740. while(!frameFinished)
  741. {
  742. int ret = av_read_frame(format, &packet);
  743. if (ret < 0)
  744. {
  745. // Error. It's probably an end of file.
  746. if (doLoop && !gotError)
  747. {
  748. // Rewind
  749. if (av_seek_frame(format, stream, 0, 0) < 0)
  750. break;
  751. gotError = true;
  752. }
  753. else
  754. {
  755. break;
  756. }
  757. }
  758. else
  759. {
  760. // Is this a packet from the video stream?
  761. if (packet.stream_index == stream)
  762. {
  763. // Decode video frame
  764. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(52, 25, 0)
  765. avcodec_decode_video(codecContext, frame, &frameFinished, packet.data, packet.size);
  766. #else
  767. avcodec_decode_video2(codecContext, frame, &frameFinished, &packet);
  768. #endif
  769. // Did we get a video frame?
  770. if (frameFinished)
  771. {
  772. AVPicture pict;
  773. if (overlay) {
  774. SDL_LockYUVOverlay(overlay);
  775. pict.data[0] = overlay->pixels[0];
  776. pict.data[1] = overlay->pixels[2];
  777. pict.data[2] = overlay->pixels[1];
  778. pict.linesize[0] = overlay->pitches[0];
  779. pict.linesize[1] = overlay->pitches[2];
  780. pict.linesize[2] = overlay->pitches[1];
  781. sws_scale(sws, frame->data, frame->linesize,
  782. 0, codecContext->height, pict.data, pict.linesize);
  783. SDL_UnlockYUVOverlay(overlay);
  784. }
  785. else
  786. {
  787. pict.data[0] = (ui8 *)dest->pixels;
  788. pict.linesize[0] = dest->pitch;
  789. sws_scale(sws, frame->data, frame->linesize,
  790. 0, codecContext->height, pict.data, pict.linesize);
  791. }
  792. }
  793. }
  794. av_free_packet(&packet);
  795. }
  796. }
  797. return frameFinished != 0;
  798. }
  799. void CVideoPlayer::show( int x, int y, SDL_Surface *dst, bool update )
  800. {
  801. if (sws == NULL)
  802. return;
  803. pos.x = x;
  804. pos.y = y;
  805. CSDL_Ext::blitSurface(dest, &destRect, dst, &pos);
  806. if (update)
  807. SDL_UpdateRect(dst, pos.x, pos.y, pos.w, pos.h);
  808. }
  809. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  810. {
  811. show(x, y, dst, update);
  812. }
  813. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  814. {
  815. if (sws == NULL)
  816. return;
  817. if (refreshCount <= 0)
  818. {
  819. refreshCount = refreshWait;
  820. if (nextFrame())
  821. show(x,y,dst,update);
  822. else
  823. {
  824. open(fname);
  825. nextFrame();
  826. // The y position is wrong at the first frame.
  827. // Note: either the windows player or the linux player is
  828. // broken. Compensate here until the bug is found.
  829. show(x, y--, dst, update);
  830. }
  831. }
  832. else
  833. {
  834. redraw(x, y, dst, update);
  835. }
  836. refreshCount --;
  837. }
  838. void CVideoPlayer::close()
  839. {
  840. fname = "";
  841. if (sws)
  842. {
  843. sws_freeContext(sws);
  844. sws = NULL;
  845. }
  846. if (overlay)
  847. {
  848. SDL_FreeYUVOverlay(overlay);
  849. overlay = NULL;
  850. }
  851. if (dest)
  852. {
  853. SDL_FreeSurface(dest);
  854. dest = NULL;
  855. }
  856. if (frame)
  857. {
  858. av_free(frame);
  859. frame = NULL;
  860. }
  861. if (codec)
  862. {
  863. avcodec_close(codecContext);
  864. codec = NULL;
  865. codecContext = NULL;
  866. }
  867. if (format)
  868. {
  869. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  870. av_close_input_file(format);
  871. format = NULL;
  872. #else
  873. avformat_close_input(&format);
  874. #endif
  875. }
  876. #if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 117, 0)
  877. if (context)
  878. {
  879. av_free(context);
  880. context = nullptr;
  881. }
  882. #endif
  883. }
  884. // Plays a video. Only works for overlays.
  885. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  886. {
  887. // Note: either the windows player or the linux player is
  888. // broken. Compensate here until the bug is found.
  889. y--;
  890. pos.x = x;
  891. pos.y = y;
  892. while(nextFrame())
  893. {
  894. if(stopOnKey && keyDown())
  895. return false;
  896. SDL_DisplayYUVOverlay(overlay, &pos);
  897. // Wait 3 frames
  898. GH.mainFPSmng->framerateDelay();
  899. GH.mainFPSmng->framerateDelay();
  900. GH.mainFPSmng->framerateDelay();
  901. }
  902. return true;
  903. }
  904. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  905. {
  906. open(name, false, true);
  907. bool ret = playVideo(x, y, dst, stopOnKey);
  908. close();
  909. return ret;
  910. }
  911. CVideoPlayer::~CVideoPlayer()
  912. {
  913. close();
  914. }
  915. #endif
  916. #endif