CVideoHandler.cpp 23 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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. void *waveout = GetProcAddress(dll,"_BinkOpenWaveOut@4");
  126. if(waveout)
  127. binkSetSoundSystem(waveout,NULL);
  128. hBink = binkOpen(hBinkFile, 0x8a800000);
  129. if(!hBink)
  130. {
  131. tlog1 << "bink failed to open " << name << std::endl;
  132. goto checkErrorAndClean;
  133. }
  134. allocBuffer();
  135. return true;
  136. checkErrorAndClean:
  137. CloseHandle(hBinkFile);
  138. hBinkFile = NULL;
  139. checkForError();
  140. throw std::runtime_error("BIK failed opening video!");
  141. }
  142. void CBIKHandler::show( int x, int y, SDL_Surface *dst, bool update )
  143. {
  144. const int w = hBink->width,
  145. h = hBink->height,
  146. Bpp = dst->format->BytesPerPixel;
  147. int mode = -1;
  148. //screen color depth might have changed... (eg. because F4)
  149. if(bufferSize != w * h * Bpp)
  150. {
  151. freeBuffer();
  152. allocBuffer(Bpp);
  153. }
  154. switch(Bpp)
  155. {
  156. case 2:
  157. mode = 3; //565, mode 2 is 555 probably
  158. break;
  159. case 3:
  160. mode = 0;
  161. break;
  162. case 4:
  163. mode = 1;
  164. break;
  165. default:
  166. return; //not supported screen depth
  167. }
  168. binkDoFrame(hBink);
  169. binkCopyToBuffer(hBink, buffer, w*Bpp, h, 0, 0, mode);
  170. blitBuffer(buffer, x, y, w, h, dst);
  171. if(update)
  172. SDL_UpdateRect(dst, x, y, w, h);
  173. }
  174. bool CBIKHandler::nextFrame()
  175. {
  176. binkNextFrame(hBink);
  177. return true;
  178. }
  179. void CBIKHandler::close()
  180. {
  181. binkClose(hBink);
  182. hBink = NULL;
  183. CloseHandle(hBinkFile);
  184. hBinkFile = NULL;
  185. delete [] buffer;
  186. buffer = NULL;
  187. bufferSize = 0;
  188. }
  189. bool CBIKHandler::wait()
  190. {
  191. return binkWait(hBink);
  192. }
  193. int CBIKHandler::curFrame() const
  194. {
  195. return hBink->currentFrame;
  196. }
  197. int CBIKHandler::frameCount() const
  198. {
  199. return hBink->frameCount;
  200. }
  201. void CBIKHandler::redraw( int x, int y, SDL_Surface *dst, bool update )
  202. {
  203. int w = hBink->width, h = hBink->height;
  204. blitBuffer(buffer, x, y, w, h, dst);
  205. if(update)
  206. SDL_UpdateRect(dst, x, y, w, h);
  207. }
  208. void CBIKHandler::allocBuffer(int Bpp)
  209. {
  210. if(!Bpp) Bpp = screen->format->BytesPerPixel;
  211. bufferSize = hBink->width * hBink->height * Bpp;
  212. buffer = new char[bufferSize];
  213. }
  214. void CBIKHandler::freeBuffer()
  215. {
  216. delete [] buffer;
  217. buffer = NULL;
  218. bufferSize = 0;
  219. }
  220. bool CSmackPlayer::nextFrame()
  221. {
  222. ptrSmackNextFrame(data);
  223. return true;
  224. }
  225. bool CSmackPlayer::wait()
  226. {
  227. return ptrSmackWait(data);
  228. }
  229. CSmackPlayer::CSmackPlayer() : data(NULL)
  230. {
  231. Instantiate("smackw32.dll");
  232. ptrSmackNextFrame = (SmackNextFrame)FindAddress("_SmackNextFrame@4");
  233. ptrSmackWait = (SmackWait)FindAddress("_SmackWait@4");
  234. ptrSmackDoFrame = (SmackDoFrame)FindAddress("_SmackDoFrame@4");
  235. ptrSmackToBuffer = (SmackToBuffer)FindAddress("_SmackToBuffer@28");
  236. ptrSmackOpen = (SmackOpen)FindAddress("_SmackOpen@12");
  237. ptrSmackSoundOnOff = (SmackSoundOnOff)FindAddress("_SmackSoundOnOff@8");
  238. ptrSmackClose = (SmackClose)FindAddress("_SmackClose@4");
  239. ptrVolumePan = (SmackVolumePan)FindAddress("_SmackVolumePan@16");
  240. }
  241. CSmackPlayer::~CSmackPlayer()
  242. {
  243. if(data)
  244. close();
  245. }
  246. void CSmackPlayer::close()
  247. {
  248. ptrSmackClose(data);
  249. data = NULL;
  250. }
  251. bool CSmackPlayer::open( std::string name )
  252. {
  253. Uint32 flags[2] = {0xff400, 0xfe400};
  254. data = ptrSmackOpen( (void*)name.c_str(), flags[1], -1);
  255. if (!data)
  256. {
  257. tlog1 << "Smack cannot open " << name << std::endl;
  258. checkForError();
  259. throw std::runtime_error("SMACK failed opening video");
  260. }
  261. buffer = new char[data->width*data->height*2];
  262. buf = buffer+data->width*(data->height-1)*2; // adjust pointer position for later use by 'SmackToBuffer'
  263. //ptrVolumePan(data, 0xfe000, 3640 * GDefaultOptions.musicVolume / 11, 0x8000); //set volume
  264. return true;
  265. }
  266. void CSmackPlayer::show( int x, int y, SDL_Surface *dst, bool update)
  267. {
  268. int w = data->width, h = data->height;
  269. int stripe = (-w*2) & (~3);
  270. //put frame to the buffer
  271. ptrSmackToBuffer(data, 0, 0, stripe, w, buf, 0x80000000);
  272. ptrSmackDoFrame(data);
  273. redraw(x, y, dst, update);
  274. }
  275. int CSmackPlayer::curFrame() const
  276. {
  277. return data->currentFrame;
  278. }
  279. int CSmackPlayer::frameCount() const
  280. {
  281. return data->frameCount;
  282. }
  283. void CSmackPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  284. {
  285. int w = std::min<int>(data->width, dst->w - x), h = std::min<int>(data->height, dst->h - y);
  286. /* Lock the screen for direct access to the pixels */
  287. if ( SDL_MUSTLOCK(dst) )
  288. {
  289. if ( SDL_LockSurface(dst) < 0 )
  290. {
  291. fprintf(stderr, "Can't lock screen: %s\n", SDL_GetError());
  292. return;
  293. }
  294. }
  295. // draw the frame
  296. Uint16* addr = (Uint16*) (buffer+w*(h-1)*2-2);
  297. if(dst->format->BytesPerPixel >= 3)
  298. {
  299. for( int j=0; j<h-1; j++) // why -1 ?
  300. {
  301. for ( int i=w-1; i>=0; i--)
  302. {
  303. Uint16 pixel = *addr;
  304. Uint8 *p = (Uint8 *)dst->pixels + (j+y) * dst->pitch + (i + x) * dst->format->BytesPerPixel;
  305. p[2] = ((pixel & 0x7c00) >> 10) * 8;
  306. p[1] = ((pixel & 0x3e0) >> 5) * 8;
  307. p[0] = ((pixel & 0x1F)) * 8;
  308. addr--;
  309. }
  310. }
  311. }
  312. else if(dst->format->BytesPerPixel == 2)
  313. {
  314. for( int j=0; j<h-1; j++) // why -1 ?
  315. {
  316. for ( int i=w-1; i>=0; i--)
  317. {
  318. //convert rgb 555 to 565
  319. Uint16 pixel = *addr;
  320. Uint16 *p = (Uint16 *)((Uint8 *)dst->pixels + (j+y) * dst->pitch + (i + x) * dst->format->BytesPerPixel);
  321. *p = (pixel & 0x1F)
  322. + ((pixel & 0x3e0) << 1)
  323. + ((pixel & 0x7c00) << 1);
  324. addr--;
  325. }
  326. }
  327. }
  328. if ( SDL_MUSTLOCK(dst) )
  329. {
  330. SDL_UnlockSurface(dst);
  331. }
  332. if(update)
  333. SDL_UpdateRect(dst, x, y, w, h);
  334. }
  335. CVideoPlayer::CVideoPlayer()
  336. {
  337. current = NULL;
  338. }
  339. CVideoPlayer::~CVideoPlayer()
  340. {
  341. }
  342. bool CVideoPlayer::open(std::string name)
  343. {
  344. if(boost::algorithm::ends_with(name, ".BIK"))
  345. current = &bikPlayer;
  346. else
  347. current = &smkPlayer;
  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. auto myVideo = CResourceHandler::get()->load(ResourceID("VIDEO/" + name, EResType::VIDEO));
  356. unique_ptr<char[]> data = unique_ptr<char[]>(new char[myVideo->getSize()]);
  357. myVideo->read((ui8*)data.get(), myVideo->getSize());
  358. std::ofstream out(name, std::ofstream::binary);
  359. out.exceptions(std::ifstream::failbit | std::ifstream::badbit);
  360. out.write(data.get(), myVideo->getSize());
  361. }
  362. current->open(name);
  363. return true;
  364. }
  365. catch(std::exception &e)
  366. {
  367. current = nullptr;
  368. tlog3 << "Failed to open video file " << name << ": " << e.what() << std::endl;
  369. }
  370. return false;
  371. }
  372. void CVideoPlayer::close()
  373. {
  374. if(!current)
  375. {
  376. tlog2 << "Closing no opened player...?" << std::endl;
  377. return;
  378. }
  379. current->close();
  380. current = NULL;
  381. if(!DeleteFileA(fname.c_str()))
  382. {
  383. tlog1 << "Cannot remove temporarily extracted video file: " << fname;
  384. checkForError(false);
  385. }
  386. fname.clear();
  387. }
  388. bool CVideoPlayer::nextFrame()
  389. {
  390. if(current)
  391. {
  392. current->nextFrame();
  393. return true;
  394. }
  395. else
  396. return false;
  397. }
  398. void CVideoPlayer::show(int x, int y, SDL_Surface *dst, bool update)
  399. {
  400. if(current)
  401. current->show(x, y, dst, update);
  402. }
  403. bool CVideoPlayer::wait()
  404. {
  405. if(current)
  406. return current->wait();
  407. else
  408. return false;
  409. }
  410. int CVideoPlayer::curFrame() const
  411. {
  412. if(current)
  413. return current->curFrame();
  414. else
  415. return -1;
  416. }
  417. int CVideoPlayer::frameCount() const
  418. {
  419. if(current)
  420. return current->frameCount();
  421. else
  422. return -1;
  423. }
  424. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  425. {
  426. if(!open(name))
  427. return false;
  428. bool ret = playVideo(x, y, dst, stopOnKey);
  429. close();
  430. return ret;
  431. }
  432. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  433. {
  434. if(!current)
  435. return;
  436. bool w = false;
  437. if(!first)
  438. {
  439. w = wait(); //check if should keep current frame
  440. if(!w)
  441. nextFrame();
  442. }
  443. else
  444. {
  445. first = false;
  446. }
  447. if(!w)
  448. {
  449. show(x,y,dst,update);
  450. }
  451. else if (forceRedraw)
  452. {
  453. redraw(x, y, dst, update);
  454. }
  455. }
  456. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  457. {
  458. if(current)
  459. current->redraw(x, y, dst, update);
  460. }
  461. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  462. {
  463. if(!current)
  464. return false;
  465. int frame = 0;
  466. while(frame < frameCount()) //play all frames
  467. {
  468. if(stopOnKey && keyDown())
  469. return false;
  470. if(!wait())
  471. {
  472. show(x, y, dst);
  473. nextFrame();
  474. frame++;
  475. }
  476. SDL_Delay(20);
  477. }
  478. return true;
  479. }
  480. #else
  481. #ifndef DISABLE_VIDEO
  482. #if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 117, 0)
  483. // Define a set of functions to read data
  484. static int lodRead(void* opaque, uint8_t* buf, int size)
  485. {
  486. auto video = reinterpret_cast<CVideoPlayer *>(opaque);
  487. vstd::amin(size, video->length - video->offset);
  488. if (size < 0)
  489. return -1;
  490. memcpy(buf, video->data + video->offset, size);
  491. video->offset += size;
  492. return size;
  493. }
  494. static si64 lodSeek(void * opaque, si64 pos, int whence)
  495. {
  496. auto video = reinterpret_cast<CVideoPlayer *>(opaque);
  497. if (whence & AVSEEK_SIZE)
  498. return video->length;
  499. video->offset = pos;
  500. vstd::amin(video->offset, video->length);
  501. return video->offset;
  502. }
  503. #else
  504. static const char *protocol_name = "lod";
  505. // Open a pseudo file. Name is something like 'lod:0x56432ab6c43df8fe'
  506. static int lodOpen(URLContext *context, const char *filename, int flags)
  507. {
  508. CVideoPlayer *video;
  509. // Retrieve pointer to CVideoPlayer object
  510. filename += strlen(protocol_name) + 1;
  511. video = (CVideoPlayer *)(uintptr_t)strtoull(filename, NULL, 16);
  512. // TODO: check flags ?
  513. context->priv_data = video;
  514. return 0;
  515. }
  516. static int lodClose(URLContext* h)
  517. {
  518. return 0;
  519. }
  520. // Define a set of functions to read data
  521. static int lodRead(URLContext *context, ui8 *buf, int size)
  522. {
  523. CVideoPlayer *video = (CVideoPlayer *)context->priv_data;
  524. vstd::amin(size, video->length - video->offset);
  525. if (size < 0)
  526. return -1;
  527. // TODO: can we avoid that copy ?
  528. memcpy(buf, video->data + video->offset, size);
  529. video->offset += size;
  530. return size;
  531. }
  532. static si64 lodSeek(URLContext *context, si64 pos, int whence)
  533. {
  534. CVideoPlayer *video = (CVideoPlayer *)context->priv_data;
  535. if (whence & AVSEEK_SIZE)
  536. return video->length;
  537. video->offset = pos;
  538. vstd::amin(video->offset, video->length);
  539. return video->offset;
  540. }
  541. static URLProtocol lod_protocol =
  542. {
  543. protocol_name,
  544. lodOpen,
  545. lodRead,
  546. NULL, // no write
  547. lodSeek,
  548. lodClose
  549. };
  550. #endif
  551. CVideoPlayer::CVideoPlayer()
  552. {
  553. format = NULL;
  554. frame = NULL;
  555. codec = NULL;
  556. sws = NULL;
  557. overlay = NULL;
  558. dest = NULL;
  559. context = nullptr;
  560. buffer = nullptr;
  561. // Register codecs. TODO: May be overkill. Should call a
  562. // combination of av_register_input_format() /
  563. // av_register_output_format() / av_register_protocol() instead.
  564. av_register_all();
  565. #if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 117, 0)
  566. #elif LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 69, 0)
  567. // Register our protocol 'lod' so we can directly read from mmaped memory
  568. av_register_protocol2(&lod_protocol, sizeof(lod_protocol));
  569. #else
  570. av_register_protocol(&lod_protocol);
  571. #endif
  572. }
  573. bool CVideoPlayer::open(std::string fname)
  574. {
  575. return open(fname, true, false);
  576. }
  577. // loop = to loop through the video
  578. // useOverlay = directly write to the screen.
  579. bool CVideoPlayer::open(std::string fname, bool loop, bool useOverlay)
  580. {
  581. close();
  582. this->fname = fname;
  583. offset = 0;
  584. refreshWait = 3;
  585. refreshCount = -1;
  586. doLoop = loop;
  587. ResourceID resource(std::string("Video/") + fname, EResType::VIDEO);
  588. if (CResourceHandler::get()->existsResource(resource))
  589. {
  590. auto extracted = CResourceHandler::get()->loadData(resource);
  591. data = (char *)extracted.first.release();
  592. length = extracted.second;
  593. }
  594. else
  595. {
  596. data = nullptr;
  597. length = 0;
  598. return false;
  599. }
  600. #if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 117, 0)
  601. static const int BUFFER_SIZE = 4096;
  602. buffer = (unsigned char *)av_malloc(BUFFER_SIZE);// will be freed by ffmpeg
  603. context = avio_alloc_context( buffer, BUFFER_SIZE, 0, (void *)this, lodRead, NULL, lodSeek);
  604. format = avformat_alloc_context();
  605. format->pb = context;
  606. // filename is not needed - file was already open and stored in this->data;
  607. int avfopen = avformat_open_input(&format, "dummyFilename", nullptr, nullptr);
  608. #else
  609. std::string filePath;
  610. filePath.resize(100);
  611. // Create our URL name with the 'lod' protocol as a prefix and a
  612. // back pointer to our object. Should be 32 and 64 bits compatible.
  613. sprintf(&filePath[0], "%s:0x%016llx", protocol_name, (unsigned long long)(uintptr_t)this);
  614. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 0, 0)
  615. int avfopen = av_open_input_file(&format, filePath.c_str(), NULL, 0, NULL);
  616. #else
  617. int avfopen = avformat_open_input(&format, filePath.c_str(), NULL, NULL);
  618. #endif
  619. #endif
  620. if (avfopen != 0)
  621. {
  622. return false;
  623. }
  624. // Retrieve stream information
  625. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  626. if (av_find_stream_info(format) < 0)
  627. #else
  628. if (avformat_find_stream_info(format, NULL) < 0)
  629. #endif
  630. return false;
  631. // Find the first video stream
  632. stream = -1;
  633. for(ui32 i=0; i<format->nb_streams; i++)
  634. {
  635. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 0, 0)
  636. if (format->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO)
  637. #else
  638. if (format->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
  639. #endif
  640. {
  641. stream = i;
  642. break;
  643. }
  644. }
  645. if (stream < 0)
  646. // No video stream in that file
  647. return false;
  648. // Get a pointer to the codec context for the video stream
  649. codecContext = format->streams[stream]->codec;
  650. // Find the decoder for the video stream
  651. codec = avcodec_find_decoder(codecContext->codec_id);
  652. if (codec == NULL)
  653. {
  654. // Unsupported codec
  655. return false;
  656. }
  657. // Open codec
  658. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 6, 0)
  659. if ( avcodec_open(codecContext, codec) < 0 )
  660. #else
  661. if ( avcodec_open2(codecContext, codec, NULL) < 0 )
  662. #endif
  663. {
  664. // Could not open codec
  665. codec = NULL;
  666. return false;
  667. }
  668. // Allocate video frame
  669. frame = avcodec_alloc_frame();
  670. // Allocate a place to put our YUV image on that screen
  671. if (useOverlay)
  672. {
  673. overlay = SDL_CreateYUVOverlay(codecContext->width, codecContext->height,
  674. SDL_YV12_OVERLAY, screen);
  675. }
  676. else
  677. {
  678. dest = CSDL_Ext::newSurface(codecContext->width, codecContext->height);
  679. destRect.x = destRect.y = 0;
  680. destRect.w = codecContext->width;
  681. destRect.h = codecContext->height;
  682. }
  683. if (overlay == NULL && dest == NULL)
  684. return false;
  685. // Convert the image into YUV format that SDL uses
  686. if (overlay)
  687. {
  688. sws = sws_getContext(codecContext->width, codecContext->height,
  689. codecContext->pix_fmt, codecContext->width, codecContext->height,
  690. PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
  691. }
  692. else
  693. {
  694. PixelFormat screenFormat = PIX_FMT_NONE;
  695. switch(screen->format->BytesPerPixel)
  696. {
  697. case 2: screenFormat = PIX_FMT_RGB565; break;
  698. case 3: screenFormat = PIX_FMT_RGB24; break;
  699. case 4: screenFormat = PIX_FMT_RGB32; break;
  700. default: return false;
  701. }
  702. sws = sws_getContext(codecContext->width, codecContext->height,
  703. codecContext->pix_fmt, codecContext->width, codecContext->height,
  704. screenFormat, SWS_BICUBIC, NULL, NULL, NULL);
  705. }
  706. if (sws == NULL)
  707. return false;
  708. pos.w = codecContext->width;
  709. pos.h = codecContext->height;
  710. return true;
  711. }
  712. // Read the next frame. Return false on error/end of file.
  713. bool CVideoPlayer::nextFrame()
  714. {
  715. AVPacket packet;
  716. int frameFinished = 0;
  717. bool gotError = false;
  718. if (sws == NULL)
  719. return false;
  720. while(!frameFinished)
  721. {
  722. int ret = av_read_frame(format, &packet);
  723. if (ret < 0)
  724. {
  725. // Error. It's probably an end of file.
  726. if (doLoop && !gotError)
  727. {
  728. // Rewind
  729. if (av_seek_frame(format, stream, 0, 0) < 0)
  730. break;
  731. gotError = true;
  732. }
  733. else
  734. {
  735. break;
  736. }
  737. }
  738. else
  739. {
  740. // Is this a packet from the video stream?
  741. if (packet.stream_index == stream)
  742. {
  743. // Decode video frame
  744. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(52, 25, 0)
  745. avcodec_decode_video(codecContext, frame, &frameFinished, packet.data, packet.size);
  746. #else
  747. avcodec_decode_video2(codecContext, frame, &frameFinished, &packet);
  748. #endif
  749. // Did we get a video frame?
  750. if (frameFinished)
  751. {
  752. AVPicture pict;
  753. if (overlay) {
  754. SDL_LockYUVOverlay(overlay);
  755. pict.data[0] = overlay->pixels[0];
  756. pict.data[1] = overlay->pixels[2];
  757. pict.data[2] = overlay->pixels[1];
  758. pict.linesize[0] = overlay->pitches[0];
  759. pict.linesize[1] = overlay->pitches[2];
  760. pict.linesize[2] = overlay->pitches[1];
  761. sws_scale(sws, frame->data, frame->linesize,
  762. 0, codecContext->height, pict.data, pict.linesize);
  763. SDL_UnlockYUVOverlay(overlay);
  764. }
  765. else
  766. {
  767. pict.data[0] = (ui8 *)dest->pixels;
  768. pict.linesize[0] = dest->pitch;
  769. sws_scale(sws, frame->data, frame->linesize,
  770. 0, codecContext->height, pict.data, pict.linesize);
  771. }
  772. }
  773. }
  774. av_free_packet(&packet);
  775. }
  776. }
  777. return frameFinished != 0;
  778. }
  779. void CVideoPlayer::show( int x, int y, SDL_Surface *dst, bool update )
  780. {
  781. if (sws == NULL)
  782. return;
  783. pos.x = x;
  784. pos.y = y;
  785. CSDL_Ext::blitSurface(dest, &destRect, dst, &pos);
  786. if (update)
  787. SDL_UpdateRect(dst, pos.x, pos.y, pos.w, pos.h);
  788. }
  789. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  790. {
  791. show(x, y, dst, update);
  792. }
  793. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  794. {
  795. if (sws == NULL)
  796. return;
  797. if (refreshCount <= 0)
  798. {
  799. refreshCount = refreshWait;
  800. if (nextFrame())
  801. show(x,y,dst,update);
  802. else
  803. {
  804. open(fname);
  805. nextFrame();
  806. // The y position is wrong at the first frame.
  807. // Note: either the windows player or the linux player is
  808. // broken. Compensate here until the bug is found.
  809. show(x, y--, dst, update);
  810. }
  811. }
  812. else
  813. {
  814. redraw(x, y, dst, update);
  815. }
  816. refreshCount --;
  817. }
  818. void CVideoPlayer::close()
  819. {
  820. fname = "";
  821. if (sws)
  822. {
  823. sws_freeContext(sws);
  824. sws = NULL;
  825. }
  826. if (overlay)
  827. {
  828. SDL_FreeYUVOverlay(overlay);
  829. overlay = NULL;
  830. }
  831. if (dest)
  832. {
  833. SDL_FreeSurface(dest);
  834. dest = NULL;
  835. }
  836. if (frame)
  837. {
  838. av_free(frame);
  839. frame = NULL;
  840. }
  841. if (codec)
  842. {
  843. avcodec_close(codecContext);
  844. codec = NULL;
  845. codecContext = NULL;
  846. }
  847. if (format)
  848. {
  849. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  850. av_close_input_file(format);
  851. format = NULL;
  852. #else
  853. avformat_close_input(&format);
  854. #endif
  855. }
  856. #if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 117, 0)
  857. if (context)
  858. {
  859. av_free(context);
  860. context = nullptr;
  861. }
  862. #endif
  863. }
  864. // Plays a video. Only works for overlays.
  865. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  866. {
  867. // Note: either the windows player or the linux player is
  868. // broken. Compensate here until the bug is found.
  869. y--;
  870. pos.x = x;
  871. pos.y = y;
  872. while(nextFrame())
  873. {
  874. if(stopOnKey && keyDown())
  875. return false;
  876. SDL_DisplayYUVOverlay(overlay, &pos);
  877. // Wait 3 frames
  878. GH.mainFPSmng->framerateDelay();
  879. GH.mainFPSmng->framerateDelay();
  880. GH.mainFPSmng->framerateDelay();
  881. }
  882. return true;
  883. }
  884. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  885. {
  886. open(name, false, true);
  887. bool ret = playVideo(x, y, dst, stopOnKey);
  888. close();
  889. return ret;
  890. }
  891. CVideoPlayer::~CVideoPlayer()
  892. {
  893. close();
  894. }
  895. #endif
  896. #endif