2
0

CVideoHandler.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  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. auto extracted = CResourceHandler::get()->loadData(ResourceID(std::string("Video/") + fname, EResType::VIDEO));
  574. data = (char *)extracted.first.release();
  575. length = extracted.second;
  576. if (!data)
  577. return false;
  578. std::string filePath;
  579. filePath.resize(100);
  580. // Create our URL name with the 'lod' protocol as a prefix and a
  581. // back pointer to our object. Should be 32 and 64 bits compatible.
  582. sprintf(&filePath[0], "%s:0x%016llx", protocol_name, (unsigned long long)(uintptr_t)this);
  583. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 0, 0)
  584. int avfopen = av_open_input_file(&format, filePath.c_str(), NULL, 0, NULL);
  585. #else
  586. int avfopen = avformat_open_input(&format, filePath.c_str(), NULL, NULL);
  587. #endif
  588. if (avfopen != 0)
  589. {
  590. return false;
  591. }
  592. // Retrieve stream information
  593. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  594. if (av_find_stream_info(format) < 0)
  595. #else
  596. if (avformat_find_stream_info(format, NULL) < 0)
  597. #endif
  598. return false;
  599. // Find the first video stream
  600. stream = -1;
  601. for(ui32 i=0; i<format->nb_streams; i++)
  602. {
  603. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 0, 0)
  604. if (format->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO)
  605. #else
  606. if (format->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
  607. #endif
  608. {
  609. stream = i;
  610. break;
  611. }
  612. }
  613. if (stream < 0)
  614. // No video stream in that file
  615. return false;
  616. // Get a pointer to the codec context for the video stream
  617. codecContext = format->streams[stream]->codec;
  618. // Find the decoder for the video stream
  619. codec = avcodec_find_decoder(codecContext->codec_id);
  620. if (codec == NULL)
  621. {
  622. // Unsupported codec
  623. return false;
  624. }
  625. // Open codec
  626. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  627. if ( avcodec_open(codecContext, codec) < 0 )
  628. #else
  629. if ( avcodec_open2(codecContext, codec, NULL) < 0 )
  630. #endif
  631. {
  632. // Could not open codec
  633. codec = NULL;
  634. return false;
  635. }
  636. // Allocate video frame
  637. frame = avcodec_alloc_frame();
  638. // Allocate a place to put our YUV image on that screen
  639. if (useOverlay)
  640. {
  641. overlay = SDL_CreateYUVOverlay(codecContext->width, codecContext->height,
  642. SDL_YV12_OVERLAY, screen);
  643. }
  644. else
  645. {
  646. dest = CSDL_Ext::newSurface(codecContext->width, codecContext->height);
  647. destRect.x = destRect.y = 0;
  648. destRect.w = codecContext->width;
  649. destRect.h = codecContext->height;
  650. }
  651. if (overlay == NULL && dest == NULL)
  652. return false;
  653. // Convert the image into YUV format that SDL uses
  654. if (overlay)
  655. {
  656. sws = sws_getContext(codecContext->width, codecContext->height,
  657. codecContext->pix_fmt, codecContext->width, codecContext->height,
  658. PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
  659. }
  660. else
  661. {
  662. PixelFormat screenFormat = PIX_FMT_NONE;
  663. switch(screen->format->BytesPerPixel)
  664. {
  665. case 2: screenFormat = PIX_FMT_RGB565; break;
  666. case 3: screenFormat = PIX_FMT_RGB24; break;
  667. case 4: screenFormat = PIX_FMT_RGB32; break;
  668. default: return false;
  669. }
  670. sws = sws_getContext(codecContext->width, codecContext->height,
  671. codecContext->pix_fmt, codecContext->width, codecContext->height,
  672. screenFormat, SWS_BICUBIC, NULL, NULL, NULL);
  673. }
  674. if (sws == NULL)
  675. return false;
  676. pos.w = codecContext->width;
  677. pos.h = codecContext->height;
  678. return true;
  679. }
  680. // Read the next frame. Return false on error/end of file.
  681. bool CVideoPlayer::nextFrame()
  682. {
  683. AVPacket packet;
  684. int frameFinished = 0;
  685. bool gotError = false;
  686. if (sws == NULL)
  687. return false;
  688. while(!frameFinished)
  689. {
  690. int ret = av_read_frame(format, &packet);
  691. if (ret < 0)
  692. {
  693. // Error. It's probably an end of file.
  694. if (doLoop && !gotError)
  695. {
  696. // Rewind
  697. if (av_seek_frame(format, stream, 0, 0) < 0)
  698. break;
  699. gotError = true;
  700. }
  701. else
  702. {
  703. break;
  704. }
  705. }
  706. else
  707. {
  708. // Is this a packet from the video stream?
  709. if (packet.stream_index == stream)
  710. {
  711. // Decode video frame
  712. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(52, 25, 0)
  713. avcodec_decode_video(codecContext, frame, &frameFinished, packet.data, packet.size);
  714. #else
  715. avcodec_decode_video2(codecContext, frame, &frameFinished, &packet);
  716. #endif
  717. // Did we get a video frame?
  718. if (frameFinished)
  719. {
  720. AVPicture pict;
  721. if (overlay) {
  722. SDL_LockYUVOverlay(overlay);
  723. pict.data[0] = overlay->pixels[0];
  724. pict.data[1] = overlay->pixels[2];
  725. pict.data[2] = overlay->pixels[1];
  726. pict.linesize[0] = overlay->pitches[0];
  727. pict.linesize[1] = overlay->pitches[2];
  728. pict.linesize[2] = overlay->pitches[1];
  729. sws_scale(sws, frame->data, frame->linesize,
  730. 0, codecContext->height, pict.data, pict.linesize);
  731. SDL_UnlockYUVOverlay(overlay);
  732. }
  733. else
  734. {
  735. pict.data[0] = (ui8 *)dest->pixels;
  736. pict.linesize[0] = dest->pitch;
  737. sws_scale(sws, frame->data, frame->linesize,
  738. 0, codecContext->height, pict.data, pict.linesize);
  739. }
  740. }
  741. }
  742. av_free_packet(&packet);
  743. }
  744. }
  745. return frameFinished != 0;
  746. }
  747. void CVideoPlayer::show( int x, int y, SDL_Surface *dst, bool update )
  748. {
  749. if (sws == NULL)
  750. return;
  751. pos.x = x;
  752. pos.y = y;
  753. CSDL_Ext::blitSurface(dest, &destRect, dst, &pos);
  754. if (update)
  755. SDL_UpdateRect(dst, pos.x, pos.y, pos.w, pos.h);
  756. }
  757. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  758. {
  759. show(x, y, dst, update);
  760. }
  761. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  762. {
  763. if (sws == NULL)
  764. return;
  765. if (refreshCount <= 0)
  766. {
  767. refreshCount = refreshWait;
  768. if (nextFrame())
  769. show(x,y,dst,update);
  770. else
  771. {
  772. open(fname);
  773. nextFrame();
  774. // The y position is wrong at the first frame.
  775. // Note: either the windows player or the linux player is
  776. // broken. Compensate here until the bug is found.
  777. show(x, y--, dst, update);
  778. }
  779. }
  780. else
  781. {
  782. redraw(x, y, dst, update);
  783. }
  784. refreshCount --;
  785. }
  786. void CVideoPlayer::close()
  787. {
  788. fname = "";
  789. if (sws)
  790. {
  791. sws_freeContext(sws);
  792. sws = NULL;
  793. }
  794. if (overlay)
  795. {
  796. SDL_FreeYUVOverlay(overlay);
  797. overlay = NULL;
  798. }
  799. if (dest)
  800. {
  801. SDL_FreeSurface(dest);
  802. dest = NULL;
  803. }
  804. if (frame)
  805. {
  806. av_free(frame);
  807. frame = NULL;
  808. }
  809. if (codec)
  810. {
  811. avcodec_close(codecContext);
  812. codec = NULL;
  813. codecContext = NULL;
  814. }
  815. if (format)
  816. {
  817. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 17, 0)
  818. av_close_input_file(format);
  819. format = NULL;
  820. #else
  821. avformat_close_input(&format);
  822. #endif
  823. }
  824. }
  825. // Plays a video. Only works for overlays.
  826. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  827. {
  828. // Note: either the windows player or the linux player is
  829. // broken. Compensate here until the bug is found.
  830. y--;
  831. pos.x = x;
  832. pos.y = y;
  833. while(nextFrame())
  834. {
  835. if(stopOnKey && keyDown())
  836. return false;
  837. SDL_DisplayYUVOverlay(overlay, &pos);
  838. // Wait 3 frames
  839. GH.mainFPSmng->framerateDelay();
  840. GH.mainFPSmng->framerateDelay();
  841. GH.mainFPSmng->framerateDelay();
  842. }
  843. return true;
  844. }
  845. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  846. {
  847. open(name, false, true);
  848. bool ret = playVideo(x, y, dst, stopOnKey);
  849. close();
  850. return ret;
  851. }
  852. CVideoPlayer::~CVideoPlayer()
  853. {
  854. close();
  855. }
  856. #endif