CVideoHandler.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. #include "StdInc.h"
  2. #include <SDL.h>
  3. #include "CVideoHandler.h"
  4. #include "UIFramework/CGuiHandler.h"
  5. #include "UIFramework/SDL_Extensions.h"
  6. #include "CPlayerInterface.h"
  7. #include "../lib/Filesystem/CResourceLoader.h"
  8. extern CGuiHandler GH; //global gui handler
  9. //reads events and returns true on key down
  10. static bool keyDown()
  11. {
  12. SDL_Event ev;
  13. while(SDL_PollEvent(&ev))
  14. {
  15. if(ev.type == SDL_KEYDOWN || ev.type == SDL_MOUSEBUTTONDOWN)
  16. return true;
  17. }
  18. return false;
  19. }
  20. #ifdef _WIN32
  21. #include <boost/algorithm/string/predicate.hpp>
  22. void checkForError(bool throwing = true)
  23. {
  24. int error = GetLastError();
  25. if(!error)
  26. return;
  27. tlog1 << "Error " << error << " encountered!\n";
  28. std::string msg;
  29. char* pTemp = NULL;
  30. FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
  31. NULL, error, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), (LPSTR)&pTemp, 1, NULL );
  32. tlog1 << "Error: " << pTemp << std::endl;
  33. msg = pTemp;
  34. LocalFree( pTemp );
  35. pTemp = NULL;
  36. if(throwing)
  37. throw std::runtime_error(msg);
  38. }
  39. void blitBuffer(char *buffer, int x, int y, int w, int h, SDL_Surface *dst)
  40. {
  41. const int bpp = dst->format->BytesPerPixel;
  42. char *dest;
  43. for(int i = h; i > 0; i--)
  44. {
  45. dest = (char*)dst->pixels + dst->pitch*(y+h-i) + x*dst->format->BytesPerPixel;
  46. memcpy(dest, buffer, bpp*w);
  47. buffer += bpp*w;
  48. }
  49. }
  50. void DLLHandler::Instantiate(const char *filename)
  51. {
  52. name = filename;
  53. dll = LoadLibraryA(filename);
  54. if(!dll)
  55. {
  56. tlog1 << "Failed loading " << filename << std::endl;
  57. checkForError(true);
  58. }
  59. }
  60. void *DLLHandler::FindAddress(const char *symbol)
  61. {
  62. void *ret;
  63. if(!dll)
  64. {
  65. tlog1 << "Cannot look for " << symbol << " because DLL hasn't been appropriately loaded!\n";
  66. return NULL;
  67. }
  68. ret = (void*) GetProcAddress(dll,symbol);
  69. if(!ret)
  70. {
  71. tlog1 << "Failed to find " << symbol << " in " << name << std::endl;
  72. checkForError();
  73. }
  74. return ret;
  75. }
  76. DLLHandler::~DLLHandler()
  77. {
  78. if(dll)
  79. {
  80. if(!FreeLibrary(dll))
  81. {
  82. tlog1 << "Failed to free " << name << std::endl;
  83. checkForError();
  84. }
  85. }
  86. }
  87. DLLHandler::DLLHandler()
  88. {
  89. dll = NULL;
  90. }
  91. CBIKHandler::CBIKHandler()
  92. {
  93. Instantiate("BINKW32.DLL");
  94. //binkGetError = FindAddress("_BinkGetError@0");
  95. binkOpen = (BinkOpen)FindAddress("_BinkOpen@8");
  96. binkSetSoundSystem = (BinkSetSoundSystem)FindAddress("_BinkSetSoundSystem@8");
  97. //getPalette = (BinkGetPalette)FindAddress("_BinkGetPalette@4");
  98. binkNextFrame = (BinkNextFrame)FindAddress("_BinkNextFrame@4");
  99. binkDoFrame = (BinkDoFrame)FindAddress("_BinkDoFrame@4");
  100. binkCopyToBuffer = (BinkCopyToBuffer)FindAddress("_BinkCopyToBuffer@28");
  101. binkWait = (BinkWait)FindAddress("_BinkWait@4");
  102. binkClose = (BinkClose)FindAddress("_BinkClose@4");
  103. hBinkFile = NULL;
  104. hBink = NULL;
  105. buffer = NULL;
  106. bufferSize = 0;
  107. }
  108. bool CBIKHandler::open(std::string name)
  109. {
  110. hBinkFile = CreateFileA
  111. (
  112. name.c_str(), // file name
  113. GENERIC_READ, // access mode
  114. FILE_SHARE_READ, // share mode
  115. NULL, // Security Descriptor
  116. OPEN_EXISTING, // how to create
  117. FILE_ATTRIBUTE_NORMAL,//FILE_FLAG_SEQUENTIAL_SCAN, // file attributes
  118. 0 // handle to template file
  119. );
  120. if(hBinkFile == INVALID_HANDLE_VALUE)
  121. {
  122. tlog1 << "BIK handler: failed to open " << name << std::endl;
  123. goto checkErrorAndClean;
  124. }
  125. void *waveout = GetProcAddress(dll,"_BinkOpenWaveOut@4");
  126. if(waveout)
  127. binkSetSoundSystem(waveout,NULL);
  128. hBink = binkOpen(hBinkFile, 0x8a800000);
  129. if(!hBink)
  130. {
  131. tlog1 << "bink failed to open " << name << std::endl;
  132. goto checkErrorAndClean;
  133. }
  134. allocBuffer();
  135. return true;
  136. checkErrorAndClean:
  137. CloseHandle(hBinkFile);
  138. hBinkFile = NULL;
  139. checkForError();
  140. throw std::runtime_error("BIK failed opening video!");
  141. }
  142. void CBIKHandler::show( int x, int y, SDL_Surface *dst, bool update )
  143. {
  144. const int w = hBink->width,
  145. h = hBink->height,
  146. Bpp = dst->format->BytesPerPixel;
  147. int mode = -1;
  148. //screen color depth might have changed... (eg. because F4)
  149. if(bufferSize != w * h * Bpp)
  150. {
  151. freeBuffer();
  152. allocBuffer(Bpp);
  153. }
  154. switch(Bpp)
  155. {
  156. case 2:
  157. mode = 3; //565, mode 2 is 555 probably
  158. break;
  159. case 3:
  160. mode = 0;
  161. break;
  162. case 4:
  163. mode = 1;
  164. break;
  165. default:
  166. return; //not supported screen depth
  167. }
  168. binkDoFrame(hBink);
  169. binkCopyToBuffer(hBink, buffer, w*Bpp, h, 0, 0, mode);
  170. blitBuffer(buffer, x, y, w, h, dst);
  171. if(update)
  172. SDL_UpdateRect(dst, x, y, w, h);
  173. }
  174. bool CBIKHandler::nextFrame()
  175. {
  176. binkNextFrame(hBink);
  177. return true;
  178. }
  179. void CBIKHandler::close()
  180. {
  181. binkClose(hBink);
  182. hBink = NULL;
  183. CloseHandle(hBinkFile);
  184. hBinkFile = NULL;
  185. delete [] buffer;
  186. buffer = NULL;
  187. bufferSize = 0;
  188. }
  189. bool CBIKHandler::wait()
  190. {
  191. return binkWait(hBink);
  192. }
  193. int CBIKHandler::curFrame() const
  194. {
  195. return hBink->currentFrame;
  196. }
  197. int CBIKHandler::frameCount() const
  198. {
  199. return hBink->frameCount;
  200. }
  201. void CBIKHandler::redraw( int x, int y, SDL_Surface *dst, bool update )
  202. {
  203. int w = hBink->width, h = hBink->height;
  204. blitBuffer(buffer, x, y, w, h, dst);
  205. if(update)
  206. SDL_UpdateRect(dst, x, y, w, h);
  207. }
  208. void CBIKHandler::allocBuffer(int Bpp)
  209. {
  210. if(!Bpp) Bpp = screen->format->BytesPerPixel;
  211. bufferSize = hBink->width * hBink->height * Bpp;
  212. buffer = new char[bufferSize];
  213. }
  214. void CBIKHandler::freeBuffer()
  215. {
  216. delete [] buffer;
  217. buffer = NULL;
  218. bufferSize = 0;
  219. }
  220. bool CSmackPlayer::nextFrame()
  221. {
  222. ptrSmackNextFrame(data);
  223. return true;
  224. }
  225. bool CSmackPlayer::wait()
  226. {
  227. return ptrSmackWait(data);
  228. }
  229. CSmackPlayer::CSmackPlayer() : data(NULL)
  230. {
  231. Instantiate("smackw32.dll");
  232. ptrSmackNextFrame = (SmackNextFrame)FindAddress("_SmackNextFrame@4");
  233. ptrSmackWait = (SmackWait)FindAddress("_SmackWait@4");
  234. ptrSmackDoFrame = (SmackDoFrame)FindAddress("_SmackDoFrame@4");
  235. ptrSmackToBuffer = (SmackToBuffer)FindAddress("_SmackToBuffer@28");
  236. ptrSmackOpen = (SmackOpen)FindAddress("_SmackOpen@12");
  237. ptrSmackSoundOnOff = (SmackSoundOnOff)FindAddress("_SmackSoundOnOff@8");
  238. ptrSmackClose = (SmackClose)FindAddress("_SmackClose@4");
  239. ptrVolumePan = (SmackVolumePan)FindAddress("_SmackVolumePan@16");
  240. }
  241. CSmackPlayer::~CSmackPlayer()
  242. {
  243. if(data)
  244. close();
  245. }
  246. void CSmackPlayer::close()
  247. {
  248. ptrSmackClose(data);
  249. data = NULL;
  250. }
  251. bool CSmackPlayer::open( std::string name )
  252. {
  253. Uint32 flags[2] = {0xff400, 0xfe400};
  254. data = ptrSmackOpen( (void*)name.c_str(), flags[1], -1);
  255. if (!data)
  256. {
  257. tlog1 << "Smack cannot open " << name << std::endl;
  258. checkForError();
  259. throw std::runtime_error("SMACK failed opening video");
  260. }
  261. buffer = new char[data->width*data->height*2];
  262. buf = buffer+data->width*(data->height-1)*2; // adjust pointer position for later use by 'SmackToBuffer'
  263. //ptrVolumePan(data, 0xfe000, 3640 * GDefaultOptions.musicVolume / 11, 0x8000); //set volume
  264. return true;
  265. }
  266. void CSmackPlayer::show( int x, int y, SDL_Surface *dst, bool update)
  267. {
  268. int w = data->width, h = data->height;
  269. int stripe = (-w*2) & (~3);
  270. //put frame to the buffer
  271. ptrSmackToBuffer(data, 0, 0, stripe, w, buf, 0x80000000);
  272. ptrSmackDoFrame(data);
  273. redraw(x, y, dst, update);
  274. }
  275. int CSmackPlayer::curFrame() const
  276. {
  277. return data->currentFrame;
  278. }
  279. int CSmackPlayer::frameCount() const
  280. {
  281. return data->frameCount;
  282. }
  283. void CSmackPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  284. {
  285. int w = std::min<int>(data->width, dst->w - x), h = std::min<int>(data->height, dst->h - y);
  286. /* Lock the screen for direct access to the pixels */
  287. if ( SDL_MUSTLOCK(dst) )
  288. {
  289. if ( SDL_LockSurface(dst) < 0 )
  290. {
  291. fprintf(stderr, "Can't lock screen: %s\n", SDL_GetError());
  292. return;
  293. }
  294. }
  295. // draw the frame
  296. Uint16* addr = (Uint16*) (buffer+w*(h-1)*2-2);
  297. if(dst->format->BytesPerPixel >= 3)
  298. {
  299. for( int j=0; j<h-1; j++) // why -1 ?
  300. {
  301. for ( int i=w-1; i>=0; i--)
  302. {
  303. Uint16 pixel = *addr;
  304. Uint8 *p = (Uint8 *)dst->pixels + (j+y) * dst->pitch + (i + x) * dst->format->BytesPerPixel;
  305. p[2] = ((pixel & 0x7c00) >> 10) * 8;
  306. p[1] = ((pixel & 0x3e0) >> 5) * 8;
  307. p[0] = ((pixel & 0x1F)) * 8;
  308. addr--;
  309. }
  310. }
  311. }
  312. else if(dst->format->BytesPerPixel == 2)
  313. {
  314. for( int j=0; j<h-1; j++) // why -1 ?
  315. {
  316. for ( int i=w-1; i>=0; i--)
  317. {
  318. //convert rgb 555 to 565
  319. Uint16 pixel = *addr;
  320. Uint16 *p = (Uint16 *)((Uint8 *)dst->pixels + (j+y) * dst->pitch + (i + x) * dst->format->BytesPerPixel);
  321. *p = (pixel & 0x1F)
  322. + ((pixel & 0x3e0) << 1)
  323. + ((pixel & 0x7c00) << 1);
  324. addr--;
  325. }
  326. }
  327. }
  328. if ( SDL_MUSTLOCK(dst) )
  329. {
  330. SDL_UnlockSurface(dst);
  331. }
  332. if(update)
  333. SDL_UpdateRect(dst, x, y, w, h);
  334. }
  335. CVideoPlayer::CVideoPlayer()
  336. {
  337. current = NULL;
  338. }
  339. CVideoPlayer::~CVideoPlayer()
  340. {
  341. }
  342. bool CVideoPlayer::open(std::string name)
  343. {
  344. if(boost::algorithm::ends_with(name, ".BIK"))
  345. current = &bikPlayer;
  346. else
  347. current = &smkPlayer;
  348. fname = name;
  349. first = true;
  350. try
  351. {
  352. // Extract video from video.vid so we can play it.
  353. // We can handle only videos in form of single file, no archive support yet.
  354. {
  355. auto myVideo = CResourceHandler::get()->load(ResourceID("VIDEO/" + name, EResType::VIDEO));
  356. unique_ptr<char[]> data = unique_ptr<char[]>(new char[myVideo->getSize()]);
  357. myVideo->read((ui8*)data.get(), myVideo->getSize());
  358. std::ofstream out(name, std::ofstream::binary);
  359. out.exceptions(std::ifstream::failbit | std::ifstream::badbit);
  360. out.write(data.get(), myVideo->getSize());
  361. }
  362. current->open(name);
  363. return true;
  364. }
  365. catch(std::exception &e)
  366. {
  367. current = nullptr;
  368. tlog3 << "Failed to open video file " << name << ": " << e.what() << std::endl;
  369. }
  370. return false;
  371. }
  372. void CVideoPlayer::close()
  373. {
  374. if(!current)
  375. {
  376. tlog2 << "Closing no opened player...?" << std::endl;
  377. return;
  378. }
  379. current->close();
  380. current = NULL;
  381. if(!DeleteFileA(fname.c_str()))
  382. {
  383. tlog1 << "Cannot remove temporarily extracted video file: " << fname;
  384. checkForError(false);
  385. }
  386. fname.clear();
  387. }
  388. bool CVideoPlayer::nextFrame()
  389. {
  390. if(current)
  391. {
  392. current->nextFrame();
  393. return true;
  394. }
  395. else
  396. return false;
  397. }
  398. void CVideoPlayer::show(int x, int y, SDL_Surface *dst, bool update)
  399. {
  400. if(current)
  401. current->show(x, y, dst, update);
  402. }
  403. bool CVideoPlayer::wait()
  404. {
  405. if(current)
  406. return current->wait();
  407. else
  408. return false;
  409. }
  410. int CVideoPlayer::curFrame() const
  411. {
  412. if(current)
  413. return current->curFrame();
  414. else
  415. return -1;
  416. }
  417. int CVideoPlayer::frameCount() const
  418. {
  419. if(current)
  420. return current->frameCount();
  421. else
  422. return -1;
  423. }
  424. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  425. {
  426. if(!open(name))
  427. return false;
  428. bool ret = playVideo(x, y, dst, stopOnKey);
  429. close();
  430. return ret;
  431. }
  432. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  433. {
  434. if(!current)
  435. return;
  436. bool w = false;
  437. if(!first)
  438. {
  439. w = wait(); //check if should keep current frame
  440. if(!w)
  441. nextFrame();
  442. }
  443. else
  444. {
  445. first = false;
  446. }
  447. if(!w)
  448. {
  449. show(x,y,dst,update);
  450. }
  451. else if (forceRedraw)
  452. {
  453. redraw(x, y, dst, update);
  454. }
  455. }
  456. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  457. {
  458. if(current)
  459. current->redraw(x, y, dst, update);
  460. }
  461. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  462. {
  463. if(!current)
  464. return false;
  465. int frame = 0;
  466. while(frame < frameCount()) //play all frames
  467. {
  468. if(stopOnKey && keyDown())
  469. return false;
  470. if(!wait())
  471. {
  472. show(x, y, dst);
  473. nextFrame();
  474. frame++;
  475. }
  476. SDL_Delay(20);
  477. }
  478. return true;
  479. }
  480. #else
  481. #ifndef DISABLE_VIDEO
  482. //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. ResourceID resource(std::string("Video/") + fname, EResType::VIDEO);
  575. if (CResourceHandler::get()->existsResource(resource))
  576. {
  577. auto extracted = CResourceHandler::get()->loadData(resource);
  578. data = (char *)extracted.first.release();
  579. length = extracted.second;
  580. }
  581. else
  582. {
  583. data = nullptr;
  584. length = 0;
  585. return false;
  586. }
  587. std::string filePath;
  588. filePath.resize(100);
  589. // Create our URL name with the 'lod' protocol as a prefix and a
  590. // back pointer to our object. Should be 32 and 64 bits compatible.
  591. sprintf(&filePath[0], "%s:0x%016llx", protocol_name, (unsigned long long)(uintptr_t)this);
  592. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 0, 0)
  593. int avfopen = av_open_input_file(&format, filePath.c_str(), NULL, 0, NULL);
  594. #else
  595. int avfopen = avformat_open_input(&format, filePath.c_str(), NULL, NULL);
  596. #endif
  597. if (avfopen != 0)
  598. {
  599. return false;
  600. }
  601. // Retrieve stream information
  602. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  603. if (av_find_stream_info(format) < 0)
  604. #else
  605. if (avformat_find_stream_info(format, NULL) < 0)
  606. #endif
  607. return false;
  608. // Find the first video stream
  609. stream = -1;
  610. for(ui32 i=0; i<format->nb_streams; i++)
  611. {
  612. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 0, 0)
  613. if (format->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO)
  614. #else
  615. if (format->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
  616. #endif
  617. {
  618. stream = i;
  619. break;
  620. }
  621. }
  622. if (stream < 0)
  623. // No video stream in that file
  624. return false;
  625. // Get a pointer to the codec context for the video stream
  626. codecContext = format->streams[stream]->codec;
  627. // Find the decoder for the video stream
  628. codec = avcodec_find_decoder(codecContext->codec_id);
  629. if (codec == NULL)
  630. {
  631. // Unsupported codec
  632. return false;
  633. }
  634. // Open codec
  635. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 6, 0)
  636. if ( avcodec_open(codecContext, codec) < 0 )
  637. #else
  638. if ( avcodec_open2(codecContext, codec, NULL) < 0 )
  639. #endif
  640. {
  641. // Could not open codec
  642. codec = NULL;
  643. return false;
  644. }
  645. // Allocate video frame
  646. frame = avcodec_alloc_frame();
  647. // Allocate a place to put our YUV image on that screen
  648. if (useOverlay)
  649. {
  650. overlay = SDL_CreateYUVOverlay(codecContext->width, codecContext->height,
  651. SDL_YV12_OVERLAY, screen);
  652. }
  653. else
  654. {
  655. dest = CSDL_Ext::newSurface(codecContext->width, codecContext->height);
  656. destRect.x = destRect.y = 0;
  657. destRect.w = codecContext->width;
  658. destRect.h = codecContext->height;
  659. }
  660. if (overlay == NULL && dest == NULL)
  661. return false;
  662. // Convert the image into YUV format that SDL uses
  663. if (overlay)
  664. {
  665. sws = sws_getContext(codecContext->width, codecContext->height,
  666. codecContext->pix_fmt, codecContext->width, codecContext->height,
  667. PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
  668. }
  669. else
  670. {
  671. PixelFormat screenFormat = PIX_FMT_NONE;
  672. switch(screen->format->BytesPerPixel)
  673. {
  674. case 2: screenFormat = PIX_FMT_RGB565; break;
  675. case 3: screenFormat = PIX_FMT_RGB24; break;
  676. case 4: screenFormat = PIX_FMT_RGB32; break;
  677. default: return false;
  678. }
  679. sws = sws_getContext(codecContext->width, codecContext->height,
  680. codecContext->pix_fmt, codecContext->width, codecContext->height,
  681. screenFormat, SWS_BICUBIC, NULL, NULL, NULL);
  682. }
  683. if (sws == NULL)
  684. return false;
  685. pos.w = codecContext->width;
  686. pos.h = codecContext->height;
  687. return true;
  688. }
  689. // Read the next frame. Return false on error/end of file.
  690. bool CVideoPlayer::nextFrame()
  691. {
  692. AVPacket packet;
  693. int frameFinished = 0;
  694. bool gotError = false;
  695. if (sws == NULL)
  696. return false;
  697. while(!frameFinished)
  698. {
  699. int ret = av_read_frame(format, &packet);
  700. if (ret < 0)
  701. {
  702. // Error. It's probably an end of file.
  703. if (doLoop && !gotError)
  704. {
  705. // Rewind
  706. if (av_seek_frame(format, stream, 0, 0) < 0)
  707. break;
  708. gotError = true;
  709. }
  710. else
  711. {
  712. break;
  713. }
  714. }
  715. else
  716. {
  717. // Is this a packet from the video stream?
  718. if (packet.stream_index == stream)
  719. {
  720. // Decode video frame
  721. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(52, 25, 0)
  722. avcodec_decode_video(codecContext, frame, &frameFinished, packet.data, packet.size);
  723. #else
  724. avcodec_decode_video2(codecContext, frame, &frameFinished, &packet);
  725. #endif
  726. // Did we get a video frame?
  727. if (frameFinished)
  728. {
  729. AVPicture pict;
  730. if (overlay) {
  731. SDL_LockYUVOverlay(overlay);
  732. pict.data[0] = overlay->pixels[0];
  733. pict.data[1] = overlay->pixels[2];
  734. pict.data[2] = overlay->pixels[1];
  735. pict.linesize[0] = overlay->pitches[0];
  736. pict.linesize[1] = overlay->pitches[2];
  737. pict.linesize[2] = overlay->pitches[1];
  738. sws_scale(sws, frame->data, frame->linesize,
  739. 0, codecContext->height, pict.data, pict.linesize);
  740. SDL_UnlockYUVOverlay(overlay);
  741. }
  742. else
  743. {
  744. pict.data[0] = (ui8 *)dest->pixels;
  745. pict.linesize[0] = dest->pitch;
  746. sws_scale(sws, frame->data, frame->linesize,
  747. 0, codecContext->height, pict.data, pict.linesize);
  748. }
  749. }
  750. }
  751. av_free_packet(&packet);
  752. }
  753. }
  754. return frameFinished != 0;
  755. }
  756. void CVideoPlayer::show( int x, int y, SDL_Surface *dst, bool update )
  757. {
  758. if (sws == NULL)
  759. return;
  760. pos.x = x;
  761. pos.y = y;
  762. CSDL_Ext::blitSurface(dest, &destRect, dst, &pos);
  763. if (update)
  764. SDL_UpdateRect(dst, pos.x, pos.y, pos.w, pos.h);
  765. }
  766. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  767. {
  768. show(x, y, dst, update);
  769. }
  770. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  771. {
  772. if (sws == NULL)
  773. return;
  774. if (refreshCount <= 0)
  775. {
  776. refreshCount = refreshWait;
  777. if (nextFrame())
  778. show(x,y,dst,update);
  779. else
  780. {
  781. open(fname);
  782. nextFrame();
  783. // The y position is wrong at the first frame.
  784. // Note: either the windows player or the linux player is
  785. // broken. Compensate here until the bug is found.
  786. show(x, y--, dst, update);
  787. }
  788. }
  789. else
  790. {
  791. redraw(x, y, dst, update);
  792. }
  793. refreshCount --;
  794. }
  795. void CVideoPlayer::close()
  796. {
  797. fname = "";
  798. if (sws)
  799. {
  800. sws_freeContext(sws);
  801. sws = NULL;
  802. }
  803. if (overlay)
  804. {
  805. SDL_FreeYUVOverlay(overlay);
  806. overlay = NULL;
  807. }
  808. if (dest)
  809. {
  810. SDL_FreeSurface(dest);
  811. dest = NULL;
  812. }
  813. if (frame)
  814. {
  815. av_free(frame);
  816. frame = NULL;
  817. }
  818. if (codec)
  819. {
  820. avcodec_close(codecContext);
  821. codec = NULL;
  822. codecContext = NULL;
  823. }
  824. if (format)
  825. {
  826. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  827. av_close_input_file(format);
  828. format = NULL;
  829. #else
  830. avformat_close_input(&format);
  831. #endif
  832. }
  833. }
  834. // Plays a video. Only works for overlays.
  835. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  836. {
  837. // Note: either the windows player or the linux player is
  838. // broken. Compensate here until the bug is found.
  839. y--;
  840. pos.x = x;
  841. pos.y = y;
  842. while(nextFrame())
  843. {
  844. if(stopOnKey && keyDown())
  845. return false;
  846. SDL_DisplayYUVOverlay(overlay, &pos);
  847. // Wait 3 frames
  848. GH.mainFPSmng->framerateDelay();
  849. GH.mainFPSmng->framerateDelay();
  850. GH.mainFPSmng->framerateDelay();
  851. }
  852. return true;
  853. }
  854. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  855. {
  856. open(name, false, true);
  857. bool ret = playVideo(x, y, dst, stopOnKey);
  858. close();
  859. return ret;
  860. }
  861. CVideoPlayer::~CVideoPlayer()
  862. {
  863. close();
  864. }
  865. #endif
  866. #endif