CVideoHandler.cpp 22 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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. #include "../lib/Filesystem/CResourceLoader.h"
  9. extern CGuiHandler GH; //global gui handler
  10. //reads events and returns true on key down
  11. static bool keyDown()
  12. {
  13. SDL_Event ev;
  14. while(SDL_PollEvent(&ev))
  15. {
  16. if(ev.type == SDL_KEYDOWN || ev.type == SDL_MOUSEBUTTONDOWN)
  17. return true;
  18. }
  19. return false;
  20. }
  21. #ifdef _WIN32
  22. #include <boost/algorithm/string/predicate.hpp>
  23. void checkForError(bool throwing = true)
  24. {
  25. int error = GetLastError();
  26. if(!error)
  27. return;
  28. tlog1 << "Error " << error << " encountered!\n";
  29. std::string msg;
  30. char* pTemp = NULL;
  31. FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
  32. NULL, error, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), (LPSTR)&pTemp, 1, NULL );
  33. tlog1 << "Error: " << pTemp << std::endl;
  34. msg = pTemp;
  35. LocalFree( pTemp );
  36. pTemp = NULL;
  37. if(throwing)
  38. throw std::runtime_error(msg);
  39. }
  40. void blitBuffer(char *buffer, int x, int y, int w, int h, SDL_Surface *dst)
  41. {
  42. const int bpp = dst->format->BytesPerPixel;
  43. char *dest;
  44. for(int i = h; i > 0; i--)
  45. {
  46. dest = (char*)dst->pixels + dst->pitch*(y+h-i) + x*dst->format->BytesPerPixel;
  47. memcpy(dest, buffer, bpp*w);
  48. buffer += bpp*w;
  49. }
  50. }
  51. void DLLHandler::Instantiate(const char *filename)
  52. {
  53. name = filename;
  54. dll = LoadLibraryA(filename);
  55. if(!dll)
  56. {
  57. tlog1 << "Failed loading " << filename << std::endl;
  58. checkForError(true);
  59. }
  60. }
  61. void *DLLHandler::FindAddress(const char *symbol)
  62. {
  63. void *ret;
  64. if(!dll)
  65. {
  66. tlog1 << "Cannot look for " << symbol << " because DLL hasn't been appropriately loaded!\n";
  67. return NULL;
  68. }
  69. ret = (void*) GetProcAddress(dll,symbol);
  70. if(!ret)
  71. {
  72. tlog1 << "Failed to find " << symbol << " in " << name << std::endl;
  73. checkForError();
  74. }
  75. return ret;
  76. }
  77. DLLHandler::~DLLHandler()
  78. {
  79. if(dll)
  80. {
  81. if(!FreeLibrary(dll))
  82. {
  83. tlog1 << "Failed to free " << name << std::endl;
  84. checkForError();
  85. }
  86. }
  87. }
  88. DLLHandler::DLLHandler()
  89. {
  90. dll = NULL;
  91. }
  92. CBIKHandler::CBIKHandler()
  93. {
  94. Instantiate("BINKW32.DLL");
  95. //binkGetError = FindAddress("_BinkGetError@0");
  96. binkOpen = (BinkOpen)FindAddress("_BinkOpen@8");
  97. binkSetSoundSystem = (BinkSetSoundSystem)FindAddress("_BinkSetSoundSystem@8");
  98. //getPalette = (BinkGetPalette)FindAddress("_BinkGetPalette@4");
  99. binkNextFrame = (BinkNextFrame)FindAddress("_BinkNextFrame@4");
  100. binkDoFrame = (BinkDoFrame)FindAddress("_BinkDoFrame@4");
  101. binkCopyToBuffer = (BinkCopyToBuffer)FindAddress("_BinkCopyToBuffer@28");
  102. binkWait = (BinkWait)FindAddress("_BinkWait@4");
  103. binkClose = (BinkClose)FindAddress("_BinkClose@4");
  104. hBinkFile = NULL;
  105. hBink = NULL;
  106. buffer = NULL;
  107. bufferSize = 0;
  108. }
  109. bool CBIKHandler::open(std::string name)
  110. {
  111. hBinkFile = CreateFileA
  112. (
  113. name.c_str(), // file name
  114. GENERIC_READ, // access mode
  115. FILE_SHARE_READ, // share mode
  116. NULL, // Security Descriptor
  117. OPEN_EXISTING, // how to create
  118. FILE_ATTRIBUTE_NORMAL,//FILE_FLAG_SEQUENTIAL_SCAN, // file attributes
  119. 0 // handle to template file
  120. );
  121. if(hBinkFile == INVALID_HANDLE_VALUE)
  122. {
  123. tlog1 << "BIK handler: failed to open " << name << std::endl;
  124. goto checkErrorAndClean;
  125. }
  126. void *waveout = GetProcAddress(dll,"_BinkOpenWaveOut@4");
  127. if(waveout)
  128. binkSetSoundSystem(waveout,NULL);
  129. hBink = binkOpen(hBinkFile, 0x8a800000);
  130. if(!hBink)
  131. {
  132. tlog1 << "bink failed to open " << name << std::endl;
  133. goto checkErrorAndClean;
  134. }
  135. allocBuffer();
  136. return true;
  137. checkErrorAndClean:
  138. CloseHandle(hBinkFile);
  139. hBinkFile = NULL;
  140. checkForError();
  141. throw std::runtime_error("BIK failed opening video!");
  142. }
  143. void CBIKHandler::show( int x, int y, SDL_Surface *dst, bool update )
  144. {
  145. const int w = hBink->width,
  146. h = hBink->height,
  147. Bpp = dst->format->BytesPerPixel;
  148. int mode = -1;
  149. //screen color depth might have changed... (eg. because F4)
  150. if(bufferSize != w * h * Bpp)
  151. {
  152. freeBuffer();
  153. allocBuffer(Bpp);
  154. }
  155. switch(Bpp)
  156. {
  157. case 2:
  158. mode = 3; //565, mode 2 is 555 probably
  159. break;
  160. case 3:
  161. mode = 0;
  162. break;
  163. case 4:
  164. mode = 1;
  165. break;
  166. default:
  167. return; //not supported screen depth
  168. }
  169. binkDoFrame(hBink);
  170. binkCopyToBuffer(hBink, buffer, w*Bpp, h, 0, 0, mode);
  171. blitBuffer(buffer, x, y, w, h, dst);
  172. if(update)
  173. SDL_UpdateRect(dst, x, y, w, h);
  174. }
  175. bool CBIKHandler::nextFrame()
  176. {
  177. binkNextFrame(hBink);
  178. return true;
  179. }
  180. void CBIKHandler::close()
  181. {
  182. binkClose(hBink);
  183. hBink = NULL;
  184. CloseHandle(hBinkFile);
  185. hBinkFile = NULL;
  186. delete [] buffer;
  187. buffer = NULL;
  188. bufferSize = 0;
  189. }
  190. bool CBIKHandler::wait()
  191. {
  192. return binkWait(hBink);
  193. }
  194. int CBIKHandler::curFrame() const
  195. {
  196. return hBink->currentFrame;
  197. }
  198. int CBIKHandler::frameCount() const
  199. {
  200. return hBink->frameCount;
  201. }
  202. void CBIKHandler::redraw( int x, int y, SDL_Surface *dst, bool update )
  203. {
  204. int w = hBink->width, h = hBink->height;
  205. blitBuffer(buffer, x, y, w, h, dst);
  206. if(update)
  207. SDL_UpdateRect(dst, x, y, w, h);
  208. }
  209. void CBIKHandler::allocBuffer(int Bpp)
  210. {
  211. if(!Bpp) Bpp = screen->format->BytesPerPixel;
  212. bufferSize = hBink->width * hBink->height * Bpp;
  213. buffer = new char[bufferSize];
  214. }
  215. void CBIKHandler::freeBuffer()
  216. {
  217. delete [] buffer;
  218. buffer = NULL;
  219. bufferSize = 0;
  220. }
  221. bool CSmackPlayer::nextFrame()
  222. {
  223. ptrSmackNextFrame(data);
  224. return true;
  225. }
  226. bool CSmackPlayer::wait()
  227. {
  228. return ptrSmackWait(data);
  229. }
  230. CSmackPlayer::CSmackPlayer() : data(NULL)
  231. {
  232. Instantiate("smackw32.dll");
  233. ptrSmackNextFrame = (SmackNextFrame)FindAddress("_SmackNextFrame@4");
  234. ptrSmackWait = (SmackWait)FindAddress("_SmackWait@4");
  235. ptrSmackDoFrame = (SmackDoFrame)FindAddress("_SmackDoFrame@4");
  236. ptrSmackToBuffer = (SmackToBuffer)FindAddress("_SmackToBuffer@28");
  237. ptrSmackOpen = (SmackOpen)FindAddress("_SmackOpen@12");
  238. ptrSmackSoundOnOff = (SmackSoundOnOff)FindAddress("_SmackSoundOnOff@8");
  239. ptrSmackClose = (SmackClose)FindAddress("_SmackClose@4");
  240. ptrVolumePan = (SmackVolumePan)FindAddress("_SmackVolumePan@16");
  241. }
  242. CSmackPlayer::~CSmackPlayer()
  243. {
  244. if(data)
  245. close();
  246. }
  247. void CSmackPlayer::close()
  248. {
  249. ptrSmackClose(data);
  250. data = NULL;
  251. }
  252. bool CSmackPlayer::open( std::string name )
  253. {
  254. Uint32 flags[2] = {0xff400, 0xfe400};
  255. data = ptrSmackOpen( (void*)name.c_str(), flags[1], -1);
  256. if (!data)
  257. {
  258. tlog1 << "Smack cannot open " << name << std::endl;
  259. checkForError();
  260. throw std::runtime_error("SMACK failed opening video");
  261. }
  262. buffer = new char[data->width*data->height*2];
  263. buf = buffer+data->width*(data->height-1)*2; // adjust pointer position for later use by 'SmackToBuffer'
  264. //ptrVolumePan(data, 0xfe000, 3640 * GDefaultOptions.musicVolume / 11, 0x8000); //set volume
  265. return true;
  266. }
  267. void CSmackPlayer::show( int x, int y, SDL_Surface *dst, bool update)
  268. {
  269. int w = data->width, h = data->height;
  270. int stripe = (-w*2) & (~3);
  271. //put frame to the buffer
  272. ptrSmackToBuffer(data, 0, 0, stripe, w, buf, 0x80000000);
  273. ptrSmackDoFrame(data);
  274. redraw(x, y, dst, update);
  275. }
  276. int CSmackPlayer::curFrame() const
  277. {
  278. return data->currentFrame;
  279. }
  280. int CSmackPlayer::frameCount() const
  281. {
  282. return data->frameCount;
  283. }
  284. void CSmackPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  285. {
  286. int w = std::min<int>(data->width, dst->w - x), h = std::min<int>(data->height, dst->h - y);
  287. /* Lock the screen for direct access to the pixels */
  288. if ( SDL_MUSTLOCK(dst) )
  289. {
  290. if ( SDL_LockSurface(dst) < 0 )
  291. {
  292. fprintf(stderr, "Can't lock screen: %s\n", SDL_GetError());
  293. return;
  294. }
  295. }
  296. // draw the frame
  297. Uint16* addr = (Uint16*) (buffer+w*(h-1)*2-2);
  298. if(dst->format->BytesPerPixel >= 3)
  299. {
  300. for( int j=0; j<h-1; j++) // why -1 ?
  301. {
  302. for ( int i=w-1; i>=0; i--)
  303. {
  304. Uint16 pixel = *addr;
  305. Uint8 *p = (Uint8 *)dst->pixels + (j+y) * dst->pitch + (i + x) * dst->format->BytesPerPixel;
  306. p[2] = ((pixel & 0x7c00) >> 10) * 8;
  307. p[1] = ((pixel & 0x3e0) >> 5) * 8;
  308. p[0] = ((pixel & 0x1F)) * 8;
  309. addr--;
  310. }
  311. }
  312. }
  313. else if(dst->format->BytesPerPixel == 2)
  314. {
  315. for( int j=0; j<h-1; j++) // why -1 ?
  316. {
  317. for ( int i=w-1; i>=0; i--)
  318. {
  319. //convert rgb 555 to 565
  320. Uint16 pixel = *addr;
  321. Uint16 *p = (Uint16 *)((Uint8 *)dst->pixels + (j+y) * dst->pitch + (i + x) * dst->format->BytesPerPixel);
  322. *p = (pixel & 0x1F)
  323. + ((pixel & 0x3e0) << 1)
  324. + ((pixel & 0x7c00) << 1);
  325. addr--;
  326. }
  327. }
  328. }
  329. if ( SDL_MUSTLOCK(dst) )
  330. {
  331. SDL_UnlockSurface(dst);
  332. }
  333. if(update)
  334. SDL_UpdateRect(dst, x, y, w, h);
  335. }
  336. CVideoPlayer::CVideoPlayer()
  337. {
  338. current = NULL;
  339. }
  340. CVideoPlayer::~CVideoPlayer()
  341. {
  342. }
  343. bool CVideoPlayer::open(std::string name)
  344. {
  345. if(boost::algorithm::ends_with(name, ".BIK"))
  346. current = &bikPlayer;
  347. else
  348. current = &smkPlayer;
  349. fname = name;
  350. first = true;
  351. try
  352. {
  353. // Extract video from video.vid so we can play it.
  354. // We can handle only videos in form of single file, no archive support yet.
  355. {
  356. auto myVideo = CResourceHandler::get()->load(ResourceID("VIDEO/" + name, EResType::VIDEO));
  357. unique_ptr<char[]> data = unique_ptr<char[]>(new char[myVideo->getSize()]);
  358. myVideo->read((ui8*)data.get(), myVideo->getSize());
  359. std::ofstream out(name, std::ofstream::binary);
  360. out.exceptions(std::ifstream::failbit | std::ifstream::badbit);
  361. out.write(data.get(), myVideo->getSize());
  362. }
  363. current->open(name);
  364. return true;
  365. }
  366. catch(std::exception &e)
  367. {
  368. current = nullptr;
  369. tlog3 << "Failed to open video file " << name << ": " << e.what() << std::endl;
  370. }
  371. return false;
  372. }
  373. void CVideoPlayer::close()
  374. {
  375. if(!current)
  376. {
  377. tlog2 << "Closing no opened player...?" << std::endl;
  378. return;
  379. }
  380. current->close();
  381. current = NULL;
  382. if(!DeleteFileA(fname.c_str()))
  383. {
  384. tlog1 << "Cannot remove temporarily extracted video file: " << fname;
  385. checkForError(false);
  386. }
  387. fname.clear();
  388. }
  389. bool CVideoPlayer::nextFrame()
  390. {
  391. if(current)
  392. {
  393. current->nextFrame();
  394. return true;
  395. }
  396. else
  397. return false;
  398. }
  399. void CVideoPlayer::show(int x, int y, SDL_Surface *dst, bool update)
  400. {
  401. if(current)
  402. current->show(x, y, dst, update);
  403. }
  404. bool CVideoPlayer::wait()
  405. {
  406. if(current)
  407. return current->wait();
  408. else
  409. return false;
  410. }
  411. int CVideoPlayer::curFrame() const
  412. {
  413. if(current)
  414. return current->curFrame();
  415. else
  416. return -1;
  417. }
  418. int CVideoPlayer::frameCount() const
  419. {
  420. if(current)
  421. return current->frameCount();
  422. else
  423. return -1;
  424. }
  425. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  426. {
  427. if(!open(name))
  428. return false;
  429. bool ret = playVideo(x, y, dst, stopOnKey);
  430. close();
  431. return ret;
  432. }
  433. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  434. {
  435. if(!current)
  436. return;
  437. bool w = false;
  438. if(!first)
  439. {
  440. w = wait(); //check if should keep current frame
  441. if(!w)
  442. nextFrame();
  443. }
  444. else
  445. {
  446. first = false;
  447. }
  448. if(!w)
  449. {
  450. show(x,y,dst,update);
  451. }
  452. else if (forceRedraw)
  453. {
  454. redraw(x, y, dst, update);
  455. }
  456. }
  457. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  458. {
  459. if(current)
  460. current->redraw(x, y, dst, update);
  461. }
  462. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  463. {
  464. if(!current)
  465. return false;
  466. int frame = 0;
  467. while(frame < frameCount()) //play all frames
  468. {
  469. if(stopOnKey && keyDown())
  470. return false;
  471. if(!wait())
  472. {
  473. show(x, y, dst);
  474. nextFrame();
  475. frame++;
  476. }
  477. SDL_Delay(20);
  478. }
  479. return true;
  480. }
  481. #else
  482. //Workaround for compile error in ffmpeg (UINT_64C was not declared)
  483. #define __STDC_CONSTANT_MACROS
  484. #ifdef _STDINT_H
  485. #undef _STDINT_H
  486. #endif
  487. #include <stdint.h>
  488. extern "C" {
  489. #include <libavformat/avformat.h>
  490. #include <libswscale/swscale.h>
  491. }
  492. static const char *protocol_name = "lod";
  493. // Open a pseudo file. Name is something like 'lod:0x56432ab6c43df8fe'
  494. static int lod_open(URLContext *context, const char *filename, int flags)
  495. {
  496. CVideoPlayer *video;
  497. // Retrieve pointer to CVideoPlayer object
  498. filename += strlen(protocol_name) + 1;
  499. video = (CVideoPlayer *)(uintptr_t)strtoull(filename, NULL, 16);
  500. // TODO: check flags ?
  501. context->priv_data = video;
  502. return 0;
  503. }
  504. static int lod_close(URLContext* h)
  505. {
  506. return 0;
  507. }
  508. // Define a set of functions to read data
  509. static int lod_read(URLContext *context, ui8 *buf, int size)
  510. {
  511. CVideoPlayer *video = (CVideoPlayer *)context->priv_data;
  512. vstd::amin(size, video->length - video->offset);
  513. if (size < 0)
  514. return -1;
  515. // TODO: can we avoid that copy ?
  516. memcpy(buf, video->data + video->offset, size);
  517. video->offset += size;
  518. return size;
  519. }
  520. static si64 lod_seek(URLContext *context, si64 pos, int whence)
  521. {
  522. CVideoPlayer *video = (CVideoPlayer *)context->priv_data;
  523. if (whence & AVSEEK_SIZE)
  524. return video->length;
  525. video->offset = pos;
  526. vstd::amin(video->offset, video->length);
  527. return -1;//video->offset;
  528. }
  529. static URLProtocol lod_protocol =
  530. {
  531. protocol_name,
  532. lod_open,
  533. lod_read,
  534. NULL, // no write
  535. lod_seek,
  536. lod_close
  537. };
  538. CVideoPlayer::CVideoPlayer()
  539. {
  540. format = NULL;
  541. frame = NULL;
  542. codec = NULL;
  543. sws = NULL;
  544. overlay = NULL;
  545. dest = NULL;
  546. // Register codecs. TODO: May be overkill. Should call a
  547. // combination of av_register_input_format() /
  548. // av_register_output_format() / av_register_protocol() instead.
  549. av_register_all();
  550. // Register our protocol 'lod' so we can directly read from mmaped memory
  551. // TODO: URL protocol marked as deprecated in favor of avioContext
  552. // VCMI should to it if URL protocol will be removed from ffmpeg or
  553. // when new avioContext will be available in all distros (ETA: late 2012)
  554. #if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 69, 0)
  555. av_register_protocol2(&lod_protocol, sizeof(lod_protocol));
  556. #else
  557. av_register_protocol(&lod_protocol);
  558. #endif
  559. }
  560. bool CVideoPlayer::open(std::string fname)
  561. {
  562. return open(fname, true, false);
  563. }
  564. // loop = to loop through the video
  565. // useOverlay = directly write to the screen.
  566. bool CVideoPlayer::open(std::string fname, bool loop, bool useOverlay)
  567. {
  568. close();
  569. this->fname = fname;
  570. offset = 0;
  571. refreshWait = 3;
  572. refreshCount = -1;
  573. doLoop = loop;
  574. auto extracted = CResourceHandler::get()->loadData(ResourceID(std::string("Video/") + fname, EResType::VIDEO));
  575. data = (char *)extracted.first.release();
  576. length = extracted.second;
  577. if (!data)
  578. return false;
  579. std::string filePath;
  580. filePath.resize(100);
  581. // Create our URL name with the 'lod' protocol as a prefix and a
  582. // back pointer to our object. Should be 32 and 64 bits compatible.
  583. sprintf(&filePath[0], "%s:0x%016llx", protocol_name, (unsigned long long)(uintptr_t)this);
  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