CVideoHandler.cpp 21 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. #include "StdInc.h"
  2. #include <SDL.h>
  3. #include "CSndHandler.h"
  4. #include "CVideoHandler.h"
  5. #include "UIFramework/CGuiHandler.h"
  6. #include "UIFramework/SDL_Extensions.h"
  7. #include "CPlayerInterface.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 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(false);
  140. return false;
  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(false);
  259. return false;
  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. vidh.add_file(std::string(GameConstants::DATA_DIR + "/Data/VIDEO.VID"));
  338. vidh.add_file(std::string(GameConstants::DATA_DIR + "/Data/H3ab_ahd.vid"));
  339. current = NULL;
  340. }
  341. CVideoPlayer::~CVideoPlayer()
  342. {
  343. }
  344. bool CVideoPlayer::open(std::string name)
  345. {
  346. if(boost::algorithm::ends_with(name, ".BIK"))
  347. current = &bikPlayer;
  348. else
  349. current = &smkPlayer;
  350. fname = name;
  351. first = true;
  352. //extract video from video.vid so we can play it
  353. bool opened = false;
  354. vidh.extract(name, name);
  355. if (boost::filesystem::exists(name))
  356. opened = current->open(name);
  357. else // couldn't load video then load from ab resource file
  358. {
  359. vidh.extract(name, name);
  360. if (boost::filesystem::exists(name))
  361. opened = current->open(name);
  362. }
  363. if(!opened) // check if video could be loaded
  364. {
  365. current = NULL;
  366. tlog3 << "Failed to open video file " << name << std::endl;
  367. }
  368. return opened;
  369. }
  370. void CVideoPlayer::close()
  371. {
  372. if(!current)
  373. {
  374. tlog2 << "Closing no opened player...?" << std::endl;
  375. return;
  376. }
  377. current->close();
  378. current = NULL;
  379. if(!DeleteFileA(fname.c_str()))
  380. {
  381. tlog1 << "Cannot remove temporarily extracted video file: " << fname;
  382. checkForError(false);
  383. }
  384. fname.clear();
  385. }
  386. bool CVideoPlayer::nextFrame()
  387. {
  388. if(current)
  389. {
  390. current->nextFrame();
  391. return true;
  392. }
  393. else
  394. return false;
  395. }
  396. void CVideoPlayer::show(int x, int y, SDL_Surface *dst, bool update)
  397. {
  398. if(current)
  399. current->show(x, y, dst, update);
  400. }
  401. bool CVideoPlayer::wait()
  402. {
  403. if(current)
  404. return current->wait();
  405. else
  406. return false;
  407. }
  408. int CVideoPlayer::curFrame() const
  409. {
  410. if(current)
  411. return current->curFrame();
  412. else
  413. return -1;
  414. }
  415. int CVideoPlayer::frameCount() const
  416. {
  417. if(current)
  418. return current->frameCount();
  419. else
  420. return -1;
  421. }
  422. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  423. {
  424. if(!open(name))
  425. return false;
  426. bool ret = playVideo(x, y, dst, stopOnKey);
  427. close();
  428. return ret;
  429. }
  430. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  431. {
  432. if(!current)
  433. return;
  434. bool w = false;
  435. if(!first)
  436. {
  437. w = wait(); //check if should keep current frame
  438. if(!w)
  439. nextFrame();
  440. }
  441. else
  442. {
  443. first = false;
  444. }
  445. if(!w)
  446. {
  447. show(x,y,dst,update);
  448. }
  449. else if (forceRedraw)
  450. {
  451. redraw(x, y, dst, update);
  452. }
  453. }
  454. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  455. {
  456. if(current)
  457. current->redraw(x, y, dst, update);
  458. }
  459. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  460. {
  461. if(!current)
  462. return false;
  463. int frame = 0;
  464. while(frame < frameCount()) //play all frames
  465. {
  466. if(stopOnKey && keyDown())
  467. return false;
  468. if(!wait())
  469. {
  470. show(x, y, dst);
  471. nextFrame();
  472. frame++;
  473. }
  474. SDL_Delay(20);
  475. }
  476. return true;
  477. }
  478. #else
  479. //Workaround for compile error in ffmpeg (UINT_64C was not declared)
  480. #define __STDC_CONSTANT_MACROS
  481. #ifdef _STDINT_H
  482. #undef _STDINT_H
  483. #endif
  484. #include <stdint.h>
  485. extern "C" {
  486. #include <libavformat/avformat.h>
  487. #include <libswscale/swscale.h>
  488. }
  489. static const char *protocol_name = "lod";
  490. // Open a pseudo file. Name is something like 'lod:0x56432ab6c43df8fe'
  491. static int lod_open(URLContext *context, const char *filename, int flags)
  492. {
  493. CVideoPlayer *video;
  494. // Retrieve pointer to CVideoPlayer object
  495. filename += strlen(protocol_name) + 1;
  496. video = (CVideoPlayer *)(uintptr_t)strtoull(filename, NULL, 16);
  497. // TODO: check flags ?
  498. context->priv_data = video;
  499. return 0;
  500. }
  501. static int lod_close(URLContext* h)
  502. {
  503. return 0;
  504. }
  505. // Define a set of functions to read data
  506. static int lod_read(URLContext *context, ui8 *buf, int size)
  507. {
  508. CVideoPlayer *video = (CVideoPlayer *)context->priv_data;
  509. vstd::amin(size, video->length - video->offset);
  510. if (size < 0)
  511. return -1;
  512. // TODO: can we avoid that copy ?
  513. memcpy(buf, video->data + video->offset, size);
  514. video->offset += size;
  515. return size;
  516. }
  517. static si64 lod_seek(URLContext *context, si64 pos, int whence)
  518. {
  519. CVideoPlayer *video = (CVideoPlayer *)context->priv_data;
  520. // Not sure what the parameter whence is. Assuming it always
  521. // indicates an absolute value;
  522. video->offset = pos;
  523. vstd::amin(video->offset, video->length);
  524. return -1;//video->offset;
  525. }
  526. static URLProtocol lod_protocol =
  527. {
  528. protocol_name,
  529. lod_open,
  530. lod_read,
  531. NULL, // no write
  532. lod_seek,
  533. lod_close
  534. };
  535. CVideoPlayer::CVideoPlayer()
  536. {
  537. format = NULL;
  538. frame = NULL;
  539. codec = NULL;
  540. sws = NULL;
  541. overlay = NULL;
  542. dest = NULL;
  543. // Register codecs. TODO: May be overkill. Should call a
  544. // combination of av_register_input_format() /
  545. // av_register_output_format() / av_register_protocol() instead.
  546. av_register_all();
  547. // Register our protocol 'lod' so we can directly read from mmaped memory
  548. // TODO: URL protocol marked as deprecated in favor of avioContext
  549. // VCMI should to it if URL protocol will be removed from ffmpeg or
  550. // when new avioContext will be available in all distros (ETA: late 2012)
  551. #ifdef WITH_AV_REGISTER_PROTOCOL2
  552. av_register_protocol2(&lod_protocol, sizeof(lod_protocol));
  553. #else
  554. av_register_protocol(&lod_protocol);
  555. #endif
  556. vidh.add_file(GameConstants::DATA_DIR + "/Data/VIDEO.VID");
  557. vidh.add_file(GameConstants::DATA_DIR + "/Data/H3ab_ahd.vid");
  558. }
  559. bool CVideoPlayer::open(std::string fname)
  560. {
  561. return open(fname, true, false);
  562. }
  563. // loop = to loop through the video
  564. // useOverlay = directly write to the screen.
  565. bool CVideoPlayer::open(std::string fname, bool loop, bool useOverlay)
  566. {
  567. close();
  568. this->fname = fname;
  569. offset = 0;
  570. refreshWait = 3;
  571. refreshCount = -1;
  572. doLoop = loop;
  573. data = vidh.extract(fname, length);
  574. std::string filePath;
  575. if (data)
  576. {
  577. filePath.resize(100);
  578. // Create our URL name with the 'lod' protocol as a prefix and a
  579. // back pointer to our object. Should be 32 and 64 bits compatible.
  580. sprintf(&filePath[0], "%s:0x%016llx", protocol_name, (unsigned long long)(uintptr_t)this);
  581. }
  582. else
  583. filePath = GameConstants::DATA_DIR + "/Data/video/" + fname;
  584. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 0, 0)
  585. int avfopen = av_open_input_file(&format, filePath.c_str(), NULL, 0, NULL);
  586. #else
  587. int avfopen = avformat_open_input(&format, filePath.c_str(), NULL, NULL);
  588. #endif
  589. if (avfopen != 0)
  590. {
  591. return false;
  592. }
  593. // Retrieve stream information
  594. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  595. if (av_find_stream_info(format) < 0)
  596. #else
  597. if (avformat_find_stream_info(format, NULL) < 0)
  598. #endif
  599. return false;
  600. // Find the first video stream
  601. stream = -1;
  602. for(ui32 i=0; i<format->nb_streams; i++)
  603. {
  604. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 0, 0)
  605. if (format->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO)
  606. #else
  607. if (format->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
  608. #endif
  609. {
  610. stream = i;
  611. break;
  612. }
  613. }
  614. if (stream < 0)
  615. // No video stream in that file
  616. return false;
  617. // Get a pointer to the codec context for the video stream
  618. codecContext = format->streams[stream]->codec;
  619. // Find the decoder for the video stream
  620. codec = avcodec_find_decoder(codecContext->codec_id);
  621. if (codec == NULL)
  622. {
  623. // Unsupported codec
  624. return false;
  625. }
  626. // Open codec
  627. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  628. if ( avcodec_open(codecContext, codec) < 0 )
  629. #else
  630. if ( avcodec_open2(codecContext, codec, NULL) < 0 )
  631. #endif
  632. {
  633. // Could not open codec
  634. codec = NULL;
  635. return false;
  636. }
  637. // Allocate video frame
  638. frame = avcodec_alloc_frame();
  639. // Allocate a place to put our YUV image on that screen
  640. if (useOverlay)
  641. {
  642. overlay = SDL_CreateYUVOverlay(codecContext->width, codecContext->height,
  643. SDL_YV12_OVERLAY, screen);
  644. }
  645. else
  646. {
  647. dest = CSDL_Ext::newSurface(codecContext->width, codecContext->height);
  648. destRect.x = destRect.y = 0;
  649. destRect.w = codecContext->width;
  650. destRect.h = codecContext->height;
  651. }
  652. if (overlay == NULL && dest == NULL)
  653. return false;
  654. // Convert the image into YUV format that SDL uses
  655. if (overlay)
  656. {
  657. sws = sws_getContext(codecContext->width, codecContext->height,
  658. codecContext->pix_fmt, codecContext->width, codecContext->height,
  659. PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
  660. }
  661. else
  662. {
  663. PixelFormat screenFormat = PIX_FMT_NONE;
  664. switch(screen->format->BytesPerPixel)
  665. {
  666. case 2: screenFormat = PIX_FMT_RGB565; break;
  667. case 3: screenFormat = PIX_FMT_RGB24; break;
  668. case 4: screenFormat = PIX_FMT_RGB32; break;
  669. default: return false;
  670. }
  671. sws = sws_getContext(codecContext->width, codecContext->height,
  672. codecContext->pix_fmt, codecContext->width, codecContext->height,
  673. screenFormat, SWS_BICUBIC, NULL, NULL, NULL);
  674. }
  675. if (sws == NULL)
  676. return false;
  677. pos.w = codecContext->width;
  678. pos.h = codecContext->height;
  679. return true;
  680. }
  681. // Read the next frame. Return false on error/end of file.
  682. bool CVideoPlayer::nextFrame()
  683. {
  684. AVPacket packet;
  685. int frameFinished = 0;
  686. bool gotError = false;
  687. if (sws == NULL)
  688. return false;
  689. while(!frameFinished)
  690. {
  691. int ret = av_read_frame(format, &packet);
  692. if (ret < 0)
  693. {
  694. // Error. It's probably an end of file.
  695. if (doLoop && !gotError)
  696. {
  697. // Rewind
  698. if (av_seek_frame(format, stream, 0, 0) < 0)
  699. break;
  700. gotError = true;
  701. }
  702. else
  703. {
  704. break;
  705. }
  706. }
  707. else
  708. {
  709. // Is this a packet from the video stream?
  710. if (packet.stream_index == stream)
  711. {
  712. // Decode video frame
  713. avcodec_decode_video2(codecContext, frame, &frameFinished, &packet);
  714. // Did we get a video frame?
  715. if (frameFinished)
  716. {
  717. AVPicture pict;
  718. if (overlay) {
  719. SDL_LockYUVOverlay(overlay);
  720. pict.data[0] = overlay->pixels[0];
  721. pict.data[1] = overlay->pixels[2];
  722. pict.data[2] = overlay->pixels[1];
  723. pict.linesize[0] = overlay->pitches[0];
  724. pict.linesize[1] = overlay->pitches[2];
  725. pict.linesize[2] = overlay->pitches[1];
  726. sws_scale(sws, frame->data, frame->linesize,
  727. 0, codecContext->height, pict.data, pict.linesize);
  728. SDL_UnlockYUVOverlay(overlay);
  729. }
  730. else
  731. {
  732. pict.data[0] = (ui8 *)dest->pixels;
  733. pict.linesize[0] = dest->pitch;
  734. sws_scale(sws, frame->data, frame->linesize,
  735. 0, codecContext->height, pict.data, pict.linesize);
  736. }
  737. }
  738. }
  739. av_free_packet(&packet);
  740. }
  741. }
  742. return frameFinished != 0;
  743. }
  744. void CVideoPlayer::show( int x, int y, SDL_Surface *dst, bool update )
  745. {
  746. if (sws == NULL)
  747. return;
  748. pos.x = x;
  749. pos.y = y;
  750. CSDL_Ext::blitSurface(dest, &destRect, dst, &pos);
  751. if (update)
  752. SDL_UpdateRect(dst, pos.x, pos.y, pos.w, pos.h);
  753. }
  754. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  755. {
  756. show(x, y, dst, update);
  757. }
  758. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  759. {
  760. if (sws == NULL)
  761. return;
  762. if (refreshCount <= 0)
  763. {
  764. refreshCount = refreshWait;
  765. if (nextFrame())
  766. show(x,y,dst,update);
  767. else
  768. {
  769. open(fname);
  770. nextFrame();
  771. // The y position is wrong at the first frame.
  772. // Note: either the windows player or the linux player is
  773. // broken. Compensate here until the bug is found.
  774. show(x, y--, dst, update);
  775. }
  776. }
  777. else
  778. {
  779. redraw(x, y, dst, update);
  780. }
  781. refreshCount --;
  782. }
  783. void CVideoPlayer::close()
  784. {
  785. fname = "";
  786. if (sws)
  787. {
  788. sws_freeContext(sws);
  789. sws = NULL;
  790. }
  791. if (overlay)
  792. {
  793. SDL_FreeYUVOverlay(overlay);
  794. overlay = NULL;
  795. }
  796. if (dest)
  797. {
  798. SDL_FreeSurface(dest);
  799. dest = NULL;
  800. }
  801. if (frame)
  802. {
  803. av_free(frame);
  804. frame = NULL;
  805. }
  806. if (codec)
  807. {
  808. avcodec_close(codecContext);
  809. codec = NULL;
  810. codecContext = NULL;
  811. }
  812. if (format)
  813. {
  814. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  815. av_close_input_file(format);
  816. format = NULL;
  817. #else
  818. avformat_close_input(&format);
  819. #endif
  820. }
  821. }
  822. // Plays a video. Only works for overlays.
  823. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  824. {
  825. // Note: either the windows player or the linux player is
  826. // broken. Compensate here until the bug is found.
  827. y--;
  828. pos.x = x;
  829. pos.y = y;
  830. while(nextFrame())
  831. {
  832. if(stopOnKey && keyDown())
  833. return false;
  834. SDL_DisplayYUVOverlay(overlay, &pos);
  835. // Wait 3 frames
  836. GH.mainFPSmng->framerateDelay();
  837. GH.mainFPSmng->framerateDelay();
  838. GH.mainFPSmng->framerateDelay();
  839. }
  840. return true;
  841. }
  842. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  843. {
  844. open(name, false, true);
  845. bool ret = playVideo(x, y, dst, stopOnKey);
  846. close();
  847. return ret;
  848. }
  849. CVideoPlayer::~CVideoPlayer()
  850. {
  851. close();
  852. }
  853. #endif