CVideoHandler.cpp 22 KB

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