CVideoHandler.cpp 21 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  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. #if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 69, 0)
  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. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(52, 25, 0)
  714. avcodec_decode_video(codecContext, frame, &frameFinished, packet.data, packet.size);
  715. #else
  716. avcodec_decode_video2(codecContext, frame, &frameFinished, &packet);
  717. #endif
  718. // Did we get a video frame?
  719. if (frameFinished)
  720. {
  721. AVPicture pict;
  722. if (overlay) {
  723. SDL_LockYUVOverlay(overlay);
  724. pict.data[0] = overlay->pixels[0];
  725. pict.data[1] = overlay->pixels[2];
  726. pict.data[2] = overlay->pixels[1];
  727. pict.linesize[0] = overlay->pitches[0];
  728. pict.linesize[1] = overlay->pitches[2];
  729. pict.linesize[2] = overlay->pitches[1];
  730. sws_scale(sws, frame->data, frame->linesize,
  731. 0, codecContext->height, pict.data, pict.linesize);
  732. SDL_UnlockYUVOverlay(overlay);
  733. }
  734. else
  735. {
  736. pict.data[0] = (ui8 *)dest->pixels;
  737. pict.linesize[0] = dest->pitch;
  738. sws_scale(sws, frame->data, frame->linesize,
  739. 0, codecContext->height, pict.data, pict.linesize);
  740. }
  741. }
  742. }
  743. av_free_packet(&packet);
  744. }
  745. }
  746. return frameFinished != 0;
  747. }
  748. void CVideoPlayer::show( int x, int y, SDL_Surface *dst, bool update )
  749. {
  750. if (sws == NULL)
  751. return;
  752. pos.x = x;
  753. pos.y = y;
  754. CSDL_Ext::blitSurface(dest, &destRect, dst, &pos);
  755. if (update)
  756. SDL_UpdateRect(dst, pos.x, pos.y, pos.w, pos.h);
  757. }
  758. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  759. {
  760. show(x, y, dst, update);
  761. }
  762. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  763. {
  764. if (sws == NULL)
  765. return;
  766. if (refreshCount <= 0)
  767. {
  768. refreshCount = refreshWait;
  769. if (nextFrame())
  770. show(x,y,dst,update);
  771. else
  772. {
  773. open(fname);
  774. nextFrame();
  775. // The y position is wrong at the first frame.
  776. // Note: either the windows player or the linux player is
  777. // broken. Compensate here until the bug is found.
  778. show(x, y--, dst, update);
  779. }
  780. }
  781. else
  782. {
  783. redraw(x, y, dst, update);
  784. }
  785. refreshCount --;
  786. }
  787. void CVideoPlayer::close()
  788. {
  789. fname = "";
  790. if (sws)
  791. {
  792. sws_freeContext(sws);
  793. sws = NULL;
  794. }
  795. if (overlay)
  796. {
  797. SDL_FreeYUVOverlay(overlay);
  798. overlay = NULL;
  799. }
  800. if (dest)
  801. {
  802. SDL_FreeSurface(dest);
  803. dest = NULL;
  804. }
  805. if (frame)
  806. {
  807. av_free(frame);
  808. frame = NULL;
  809. }
  810. if (codec)
  811. {
  812. avcodec_close(codecContext);
  813. codec = NULL;
  814. codecContext = NULL;
  815. }
  816. if (format)
  817. {
  818. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  819. av_close_input_file(format);
  820. format = NULL;
  821. #else
  822. avformat_close_input(&format);
  823. #endif
  824. }
  825. }
  826. // Plays a video. Only works for overlays.
  827. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  828. {
  829. // Note: either the windows player or the linux player is
  830. // broken. Compensate here until the bug is found.
  831. y--;
  832. pos.x = x;
  833. pos.y = y;
  834. while(nextFrame())
  835. {
  836. if(stopOnKey && keyDown())
  837. return false;
  838. SDL_DisplayYUVOverlay(overlay, &pos);
  839. // Wait 3 frames
  840. GH.mainFPSmng->framerateDelay();
  841. GH.mainFPSmng->framerateDelay();
  842. GH.mainFPSmng->framerateDelay();
  843. }
  844. return true;
  845. }
  846. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  847. {
  848. open(name, false, true);
  849. bool ret = playVideo(x, y, dst, stopOnKey);
  850. close();
  851. return ret;
  852. }
  853. CVideoPlayer::~CVideoPlayer()
  854. {
  855. close();
  856. }
  857. #endif