CVideoHandler.cpp 23 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  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. if(boost::algorithm::ends_with(name, ".BIK"))
  348. current = &bikPlayer;
  349. else
  350. current = &smkPlayer;
  351. fname = name;
  352. first = true;
  353. try
  354. {
  355. // Extract video from video.vid so we can play it.
  356. // We can handle only videos in form of single file, no archive support yet.
  357. {
  358. auto myVideo = CResourceHandler::get()->load(ResourceID("VIDEO/" + name, EResType::VIDEO));
  359. unique_ptr<char[]> data = unique_ptr<char[]>(new char[myVideo->getSize()]);
  360. myVideo->read((ui8*)data.get(), myVideo->getSize());
  361. std::ofstream out(name, std::ofstream::binary);
  362. out.exceptions(std::ifstream::failbit | std::ifstream::badbit);
  363. out.write(data.get(), myVideo->getSize());
  364. }
  365. current->open(name);
  366. return true;
  367. }
  368. catch(std::exception &e)
  369. {
  370. current = nullptr;
  371. tlog3 << "Failed to open video file " << name << ": " << e.what() << std::endl;
  372. }
  373. return false;
  374. }
  375. void CVideoPlayer::close()
  376. {
  377. if(!current)
  378. {
  379. tlog2 << "Closing no opened player...?" << std::endl;
  380. return;
  381. }
  382. current->close();
  383. current = NULL;
  384. if(!DeleteFileA(fname.c_str()))
  385. {
  386. tlog1 << "Cannot remove temporarily extracted video file: " << fname;
  387. checkForError(false);
  388. }
  389. fname.clear();
  390. }
  391. bool CVideoPlayer::nextFrame()
  392. {
  393. if(current)
  394. {
  395. current->nextFrame();
  396. return true;
  397. }
  398. else
  399. return false;
  400. }
  401. void CVideoPlayer::show(int x, int y, SDL_Surface *dst, bool update)
  402. {
  403. if(current)
  404. current->show(x, y, dst, update);
  405. }
  406. bool CVideoPlayer::wait()
  407. {
  408. if(current)
  409. return current->wait();
  410. else
  411. return false;
  412. }
  413. int CVideoPlayer::curFrame() const
  414. {
  415. if(current)
  416. return current->curFrame();
  417. else
  418. return -1;
  419. }
  420. int CVideoPlayer::frameCount() const
  421. {
  422. if(current)
  423. return current->frameCount();
  424. else
  425. return -1;
  426. }
  427. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  428. {
  429. if(!open(name))
  430. return false;
  431. bool ret = playVideo(x, y, dst, stopOnKey);
  432. close();
  433. return ret;
  434. }
  435. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  436. {
  437. if(!current)
  438. return;
  439. bool w = false;
  440. if(!first)
  441. {
  442. w = wait(); //check if should keep current frame
  443. if(!w)
  444. nextFrame();
  445. }
  446. else
  447. {
  448. first = false;
  449. }
  450. if(!w)
  451. {
  452. show(x,y,dst,update);
  453. }
  454. else if (forceRedraw)
  455. {
  456. redraw(x, y, dst, update);
  457. }
  458. }
  459. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  460. {
  461. if(current)
  462. current->redraw(x, y, dst, update);
  463. }
  464. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  465. {
  466. if(!current)
  467. return false;
  468. int frame = 0;
  469. while(frame < frameCount()) //play all frames
  470. {
  471. if(stopOnKey && keyDown())
  472. return false;
  473. if(!wait())
  474. {
  475. show(x, y, dst);
  476. nextFrame();
  477. frame++;
  478. }
  479. SDL_Delay(20);
  480. }
  481. return true;
  482. }
  483. #else
  484. #ifndef DISABLE_VIDEO
  485. #if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 117, 0)
  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. vstd::amin(size, video->length - video->offset);
  491. if (size < 0)
  492. return -1;
  493. memcpy(buf, video->data + video->offset, size);
  494. video->offset += size;
  495. return size;
  496. }
  497. static si64 lodSeek(void * opaque, si64 pos, int whence)
  498. {
  499. auto video = reinterpret_cast<CVideoPlayer *>(opaque);
  500. if (whence & AVSEEK_SIZE)
  501. return video->length;
  502. video->offset = pos;
  503. vstd::amin(video->offset, video->length);
  504. return video->offset;
  505. }
  506. #else
  507. static const char *protocol_name = "lod";
  508. // Open a pseudo file. Name is something like 'lod:0x56432ab6c43df8fe'
  509. static int lodOpen(URLContext *context, const char *filename, int flags)
  510. {
  511. CVideoPlayer *video;
  512. // Retrieve pointer to CVideoPlayer object
  513. filename += strlen(protocol_name) + 1;
  514. video = (CVideoPlayer *)(uintptr_t)strtoull(filename, NULL, 16);
  515. // TODO: check flags ?
  516. context->priv_data = video;
  517. return 0;
  518. }
  519. static int lodClose(URLContext* h)
  520. {
  521. return 0;
  522. }
  523. // Define a set of functions to read data
  524. static int lodRead(URLContext *context, ui8 *buf, int size)
  525. {
  526. CVideoPlayer *video = (CVideoPlayer *)context->priv_data;
  527. vstd::amin(size, video->length - video->offset);
  528. if (size < 0)
  529. return -1;
  530. // TODO: can we avoid that copy ?
  531. memcpy(buf, video->data + video->offset, size);
  532. video->offset += size;
  533. return size;
  534. }
  535. static si64 lodSeek(URLContext *context, si64 pos, int whence)
  536. {
  537. CVideoPlayer *video = (CVideoPlayer *)context->priv_data;
  538. if (whence & AVSEEK_SIZE)
  539. return video->length;
  540. video->offset = pos;
  541. vstd::amin(video->offset, video->length);
  542. return video->offset;
  543. }
  544. static URLProtocol lod_protocol =
  545. {
  546. protocol_name,
  547. lodOpen,
  548. lodRead,
  549. NULL, // no write
  550. lodSeek,
  551. lodClose
  552. };
  553. #endif
  554. CVideoPlayer::CVideoPlayer()
  555. {
  556. format = NULL;
  557. frame = NULL;
  558. codec = NULL;
  559. sws = NULL;
  560. overlay = NULL;
  561. dest = NULL;
  562. context = nullptr;
  563. buffer = nullptr;
  564. // Register codecs. TODO: May be overkill. Should call a
  565. // combination of av_register_input_format() /
  566. // av_register_output_format() / av_register_protocol() instead.
  567. av_register_all();
  568. #if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 117, 0)
  569. #elif LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 69, 0)
  570. // Register our protocol 'lod' so we can directly read from mmaped memory
  571. av_register_protocol2(&lod_protocol, sizeof(lod_protocol));
  572. #else
  573. av_register_protocol(&lod_protocol);
  574. #endif
  575. }
  576. bool CVideoPlayer::open(std::string fname)
  577. {
  578. return open(fname, true, false);
  579. }
  580. // loop = to loop through the video
  581. // useOverlay = directly write to the screen.
  582. bool CVideoPlayer::open(std::string fname, bool loop, bool useOverlay)
  583. {
  584. close();
  585. this->fname = fname;
  586. offset = 0;
  587. refreshWait = 3;
  588. refreshCount = -1;
  589. doLoop = loop;
  590. ResourceID resource(std::string("Video/") + fname, EResType::VIDEO);
  591. if (CResourceHandler::get()->existsResource(resource))
  592. {
  593. auto extracted = CResourceHandler::get()->loadData(resource);
  594. data = (char *)extracted.first.release();
  595. length = extracted.second;
  596. }
  597. else
  598. {
  599. data = nullptr;
  600. length = 0;
  601. return false;
  602. }
  603. #if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 117, 0)
  604. static const int BUFFER_SIZE = 4096;
  605. buffer = (unsigned char *)av_malloc(BUFFER_SIZE);// will be freed by ffmpeg
  606. context = avio_alloc_context( buffer, BUFFER_SIZE, 0, (void *)this, lodRead, NULL, lodSeek);
  607. format = avformat_alloc_context();
  608. format->pb = context;
  609. // filename is not needed - file was already open and stored in this->data;
  610. int avfopen = avformat_open_input(&format, "dummyFilename", nullptr, nullptr);
  611. #else
  612. std::string filePath;
  613. filePath.resize(100);
  614. // Create our URL name with the 'lod' protocol as a prefix and a
  615. // back pointer to our object. Should be 32 and 64 bits compatible.
  616. sprintf(&filePath[0], "%s:0x%016llx", protocol_name, (unsigned long long)(uintptr_t)this);
  617. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 0, 0)
  618. int avfopen = av_open_input_file(&format, filePath.c_str(), NULL, 0, NULL);
  619. #else
  620. int avfopen = avformat_open_input(&format, filePath.c_str(), NULL, NULL);
  621. #endif
  622. #endif
  623. if (avfopen != 0)
  624. {
  625. return false;
  626. }
  627. // Retrieve stream information
  628. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  629. if (av_find_stream_info(format) < 0)
  630. #else
  631. if (avformat_find_stream_info(format, NULL) < 0)
  632. #endif
  633. return false;
  634. // Find the first video stream
  635. stream = -1;
  636. for(ui32 i=0; i<format->nb_streams; i++)
  637. {
  638. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 0, 0)
  639. if (format->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO)
  640. #else
  641. if (format->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
  642. #endif
  643. {
  644. stream = i;
  645. break;
  646. }
  647. }
  648. if (stream < 0)
  649. // No video stream in that file
  650. return false;
  651. // Get a pointer to the codec context for the video stream
  652. codecContext = format->streams[stream]->codec;
  653. // Find the decoder for the video stream
  654. codec = avcodec_find_decoder(codecContext->codec_id);
  655. if (codec == NULL)
  656. {
  657. // Unsupported codec
  658. return false;
  659. }
  660. // Open codec
  661. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 6, 0)
  662. if ( avcodec_open(codecContext, codec) < 0 )
  663. #else
  664. if ( avcodec_open2(codecContext, codec, NULL) < 0 )
  665. #endif
  666. {
  667. // Could not open codec
  668. codec = NULL;
  669. return false;
  670. }
  671. // Allocate video frame
  672. frame = avcodec_alloc_frame();
  673. // Allocate a place to put our YUV image on that screen
  674. if (useOverlay)
  675. {
  676. overlay = SDL_CreateYUVOverlay(codecContext->width, codecContext->height,
  677. SDL_YV12_OVERLAY, screen);
  678. }
  679. else
  680. {
  681. dest = CSDL_Ext::newSurface(codecContext->width, codecContext->height);
  682. destRect.x = destRect.y = 0;
  683. destRect.w = codecContext->width;
  684. destRect.h = codecContext->height;
  685. }
  686. if (overlay == NULL && dest == NULL)
  687. return false;
  688. // Convert the image into YUV format that SDL uses
  689. if (overlay)
  690. {
  691. sws = sws_getContext(codecContext->width, codecContext->height,
  692. codecContext->pix_fmt, codecContext->width, codecContext->height,
  693. PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
  694. }
  695. else
  696. {
  697. PixelFormat screenFormat = PIX_FMT_NONE;
  698. if (screen->format->Bshift > screen->format->Rshift)
  699. {
  700. // this a BGR surface
  701. switch (screen->format->BytesPerPixel)
  702. {
  703. case 2: screenFormat = PIX_FMT_BGR565; break;
  704. case 3: screenFormat = PIX_FMT_BGR24; break;
  705. case 4: screenFormat = PIX_FMT_BGR32; break;
  706. default: return false;
  707. }
  708. }
  709. else
  710. {
  711. // this a RGB surface
  712. switch (screen->format->BytesPerPixel)
  713. {
  714. case 2: screenFormat = PIX_FMT_RGB565; break;
  715. case 3: screenFormat = PIX_FMT_RGB24; break;
  716. case 4: screenFormat = PIX_FMT_RGB32; break;
  717. default: return false;
  718. }
  719. }
  720. sws = sws_getContext(codecContext->width, codecContext->height,
  721. codecContext->pix_fmt, codecContext->width, codecContext->height,
  722. screenFormat, SWS_BICUBIC, NULL, NULL, NULL);
  723. }
  724. if (sws == NULL)
  725. return false;
  726. pos.w = codecContext->width;
  727. pos.h = codecContext->height;
  728. return true;
  729. }
  730. // Read the next frame. Return false on error/end of file.
  731. bool CVideoPlayer::nextFrame()
  732. {
  733. AVPacket packet;
  734. int frameFinished = 0;
  735. bool gotError = false;
  736. if (sws == NULL)
  737. return false;
  738. while(!frameFinished)
  739. {
  740. int ret = av_read_frame(format, &packet);
  741. if (ret < 0)
  742. {
  743. // Error. It's probably an end of file.
  744. if (doLoop && !gotError)
  745. {
  746. // Rewind
  747. if (av_seek_frame(format, stream, 0, 0) < 0)
  748. break;
  749. gotError = true;
  750. }
  751. else
  752. {
  753. break;
  754. }
  755. }
  756. else
  757. {
  758. // Is this a packet from the video stream?
  759. if (packet.stream_index == stream)
  760. {
  761. // Decode video frame
  762. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(52, 25, 0)
  763. avcodec_decode_video(codecContext, frame, &frameFinished, packet.data, packet.size);
  764. #else
  765. avcodec_decode_video2(codecContext, frame, &frameFinished, &packet);
  766. #endif
  767. // Did we get a video frame?
  768. if (frameFinished)
  769. {
  770. AVPicture pict;
  771. if (overlay) {
  772. SDL_LockYUVOverlay(overlay);
  773. pict.data[0] = overlay->pixels[0];
  774. pict.data[1] = overlay->pixels[2];
  775. pict.data[2] = overlay->pixels[1];
  776. pict.linesize[0] = overlay->pitches[0];
  777. pict.linesize[1] = overlay->pitches[2];
  778. pict.linesize[2] = overlay->pitches[1];
  779. sws_scale(sws, frame->data, frame->linesize,
  780. 0, codecContext->height, pict.data, pict.linesize);
  781. SDL_UnlockYUVOverlay(overlay);
  782. }
  783. else
  784. {
  785. pict.data[0] = (ui8 *)dest->pixels;
  786. pict.linesize[0] = dest->pitch;
  787. sws_scale(sws, frame->data, frame->linesize,
  788. 0, codecContext->height, pict.data, pict.linesize);
  789. }
  790. }
  791. }
  792. av_free_packet(&packet);
  793. }
  794. }
  795. return frameFinished != 0;
  796. }
  797. void CVideoPlayer::show( int x, int y, SDL_Surface *dst, bool update )
  798. {
  799. if (sws == NULL)
  800. return;
  801. pos.x = x;
  802. pos.y = y;
  803. CSDL_Ext::blitSurface(dest, &destRect, dst, &pos);
  804. if (update)
  805. SDL_UpdateRect(dst, pos.x, pos.y, pos.w, pos.h);
  806. }
  807. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  808. {
  809. show(x, y, dst, update);
  810. }
  811. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  812. {
  813. if (sws == NULL)
  814. return;
  815. if (refreshCount <= 0)
  816. {
  817. refreshCount = refreshWait;
  818. if (nextFrame())
  819. show(x,y,dst,update);
  820. else
  821. {
  822. open(fname);
  823. nextFrame();
  824. // The y position is wrong at the first frame.
  825. // Note: either the windows player or the linux player is
  826. // broken. Compensate here until the bug is found.
  827. show(x, y--, dst, update);
  828. }
  829. }
  830. else
  831. {
  832. redraw(x, y, dst, update);
  833. }
  834. refreshCount --;
  835. }
  836. void CVideoPlayer::close()
  837. {
  838. fname = "";
  839. if (sws)
  840. {
  841. sws_freeContext(sws);
  842. sws = NULL;
  843. }
  844. if (overlay)
  845. {
  846. SDL_FreeYUVOverlay(overlay);
  847. overlay = NULL;
  848. }
  849. if (dest)
  850. {
  851. SDL_FreeSurface(dest);
  852. dest = NULL;
  853. }
  854. if (frame)
  855. {
  856. av_free(frame);
  857. frame = NULL;
  858. }
  859. if (codec)
  860. {
  861. avcodec_close(codecContext);
  862. codec = NULL;
  863. codecContext = NULL;
  864. }
  865. if (format)
  866. {
  867. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  868. av_close_input_file(format);
  869. format = NULL;
  870. #else
  871. avformat_close_input(&format);
  872. #endif
  873. }
  874. #if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 117, 0)
  875. if (context)
  876. {
  877. av_free(context);
  878. context = nullptr;
  879. }
  880. #endif
  881. }
  882. // Plays a video. Only works for overlays.
  883. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  884. {
  885. // Note: either the windows player or the linux player is
  886. // broken. Compensate here until the bug is found.
  887. y--;
  888. pos.x = x;
  889. pos.y = y;
  890. while(nextFrame())
  891. {
  892. if(stopOnKey && keyDown())
  893. return false;
  894. SDL_DisplayYUVOverlay(overlay, &pos);
  895. // Wait 3 frames
  896. GH.mainFPSmng->framerateDelay();
  897. GH.mainFPSmng->framerateDelay();
  898. GH.mainFPSmng->framerateDelay();
  899. }
  900. return true;
  901. }
  902. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  903. {
  904. open(name, false, true);
  905. bool ret = playVideo(x, y, dst, stopOnKey);
  906. close();
  907. return ret;
  908. }
  909. CVideoPlayer::~CVideoPlayer()
  910. {
  911. close();
  912. }
  913. #endif
  914. #endif