CVideoHandler.cpp 21 KB

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