CVideoHandler.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  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. 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 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(false);
  141. return false;
  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(false);
  260. return false;
  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. vidh.add_file(std::string(DATA_DIR "/Data/VIDEO.VID"));
  339. vidh.add_file(std::string(DATA_DIR "/Data/H3ab_ahd.vid"));
  340. current = NULL;
  341. }
  342. CVideoPlayer::~CVideoPlayer()
  343. {
  344. }
  345. bool CVideoPlayer::open(std::string name)
  346. {
  347. if(boost::algorithm::ends_with(name, ".BIK"))
  348. current = &bikPlayer;
  349. else
  350. current = &smkPlayer;
  351. fname = name;
  352. first = true;
  353. //extract video from video.vid so we can play it
  354. bool opened = false;
  355. vidh.extract(name, name);
  356. if (boost::filesystem::exists(name))
  357. opened = current->open(name);
  358. else // couldn't load video then load from ab resource file
  359. {
  360. vidh.extract(name, name);
  361. if (boost::filesystem::exists(name))
  362. opened = current->open(name);
  363. }
  364. if(!opened) // check if video could be loaded
  365. {
  366. current = NULL;
  367. tlog3 << "Failed to open video file " << name << std::endl;
  368. }
  369. return opened;
  370. }
  371. void CVideoPlayer::close()
  372. {
  373. if(!current)
  374. {
  375. tlog2 << "Closing no opened player...?" << std::endl;
  376. return;
  377. }
  378. current->close();
  379. current = NULL;
  380. if(!DeleteFileA(fname.c_str()))
  381. {
  382. tlog1 << "Cannot remove temporarily extracted video file: " << fname;
  383. checkForError(false);
  384. }
  385. fname.clear();
  386. }
  387. bool CVideoPlayer::nextFrame()
  388. {
  389. if(current)
  390. {
  391. current->nextFrame();
  392. return true;
  393. }
  394. else
  395. return false;
  396. }
  397. void CVideoPlayer::show(int x, int y, SDL_Surface *dst, bool update)
  398. {
  399. if(current)
  400. current->show(x, y, dst, update);
  401. }
  402. bool CVideoPlayer::wait()
  403. {
  404. if(current)
  405. return current->wait();
  406. else
  407. return false;
  408. }
  409. int CVideoPlayer::curFrame() const
  410. {
  411. if(current)
  412. return current->curFrame();
  413. else
  414. return -1;
  415. }
  416. int CVideoPlayer::frameCount() const
  417. {
  418. if(current)
  419. return current->frameCount();
  420. else
  421. return -1;
  422. }
  423. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  424. {
  425. if(!open(name))
  426. return false;
  427. bool ret = playVideo(x, y, dst, stopOnKey);
  428. close();
  429. return ret;
  430. }
  431. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  432. {
  433. if(!current)
  434. return;
  435. bool w = false;
  436. if(!first)
  437. {
  438. w = wait(); //check if should keep current frame
  439. if(!w)
  440. nextFrame();
  441. }
  442. else
  443. {
  444. first = false;
  445. }
  446. if(!w)
  447. {
  448. show(x,y,dst,update);
  449. }
  450. else if (forceRedraw)
  451. {
  452. redraw(x, y, dst, update);
  453. }
  454. }
  455. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  456. {
  457. if(current)
  458. current->redraw(x, y, dst, update);
  459. }
  460. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  461. {
  462. if(!current)
  463. return false;
  464. int frame = 0;
  465. while(frame < frameCount()) //play all frames
  466. {
  467. if(stopOnKey && keyDown())
  468. return false;
  469. if(!wait())
  470. {
  471. show(x, y, dst);
  472. nextFrame();
  473. frame++;
  474. }
  475. SDL_Delay(20);
  476. }
  477. return true;
  478. }
  479. #else
  480. //Workaround for compile error in ffmpeg (UINT_64C was not declared)
  481. #define __STDC_CONSTANT_MACROS
  482. #ifdef _STDINT_H
  483. #undef _STDINT_H
  484. #endif
  485. #include <stdint.h>
  486. #include "SDL_framerate.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, unsigned char *buf, int size)
  509. {
  510. CVideoPlayer *video = (CVideoPlayer *)context->priv_data;
  511. 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 int64_t lod_seek(URLContext *context, int64_t pos, int whence)
  520. {
  521. CVideoPlayer *video = (CVideoPlayer *)context->priv_data;
  522. // Not sure what the parameter whence is. Assuming it always
  523. // indicates an absolute value;
  524. video->offset = pos;
  525. amin(video->offset, video->length);
  526. return -1;//video->offset;
  527. }
  528. static URLProtocol lod_protocol = {
  529. protocol_name,
  530. lod_open,
  531. lod_read,
  532. NULL, // no write
  533. lod_seek,
  534. lod_close
  535. };
  536. CVideoPlayer::CVideoPlayer()
  537. {
  538. format = NULL;
  539. frame = NULL;
  540. codec = NULL;
  541. sws = NULL;
  542. overlay = NULL;
  543. dest = NULL;
  544. // Register codecs. TODO: May be overkill. Should call a
  545. // combination of av_register_input_format() /
  546. // av_register_output_format() / av_register_protocol() instead.
  547. av_register_all();
  548. // Register our protocol 'lod' so we can directly read from mmaped memory
  549. #ifdef WITH_AV_REGISTER_PROTOCOL2
  550. av_register_protocol2(&lod_protocol, sizeof(lod_protocol));
  551. #else
  552. av_register_protocol(&lod_protocol);
  553. #endif
  554. vidh.add_file(std::string(DATA_DIR "/Data/VIDEO.VID"));
  555. vidh.add_file(std::string(DATA_DIR "/Data/H3ab_ahd.vid"));
  556. }
  557. bool CVideoPlayer::open(std::string fname)
  558. {
  559. return open(fname, true, false);
  560. }
  561. // loop = to loop through the video
  562. // useOverlay = directly write to the screen.
  563. bool CVideoPlayer::open(std::string fname, bool loop, bool useOverlay)
  564. {
  565. close();
  566. this->fname = fname;
  567. offset = 0;
  568. refreshWait = 3;
  569. refreshCount = -1;
  570. doLoop = loop;
  571. data = vidh.extract(fname, length);
  572. if (data) {
  573. // Create our URL name with the 'lod' protocol as a prefix and a
  574. // back pointer to our object. Should be 32 and 64 bits compatible.
  575. char url[100];
  576. sprintf(url, "%s:0x%016llx", protocol_name, (unsigned long long)(uintptr_t)this);
  577. #if LIBAVFORMAT_VERSION_MAJOR < 54
  578. int avfopen = av_open_input_file(&format, url, NULL, 0, NULL);
  579. #else
  580. int avfopen = avformat_open_input(&format, url, NULL, NULL);
  581. #endif
  582. if (avfopen != 0) {
  583. return false;
  584. }
  585. } else {
  586. // File is not in a container
  587. #if LIBAVFORMAT_VERSION_MAJOR < 54
  588. int avfopen = av_open_input_file(&format, (DATA_DIR "/Data/video/" + fname).c_str(), NULL, 0, NULL);
  589. #else
  590. int avfopen = avformat_open_input(&format, (DATA_DIR "/Data/video/" + fname).c_str(), NULL, NULL);
  591. #endif
  592. if (avfopen != 0) {
  593. // tlog1 << "Video file not found: " DATA_DIR "/Data/video/" + fname << std::endl;
  594. return false;
  595. }
  596. }
  597. // Retrieve stream information
  598. if (av_find_stream_info(format) < 0)
  599. return false;
  600. // Find the first video stream
  601. stream = -1;
  602. for(unsigned int i=0; i<format->nb_streams; i++) {
  603. #if LIBAVCODEC_VERSION_MAJOR < 53
  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. // Unsupported codec
  622. return false;
  623. }
  624. // Open codec
  625. if (avcodec_open(codecContext, codec) <0 ) {
  626. // Could not open codec
  627. codec = NULL;
  628. return false;
  629. }
  630. // Allocate video frame
  631. frame = avcodec_alloc_frame();
  632. // Allocate a place to put our YUV image on that screen
  633. if (useOverlay) {
  634. overlay = SDL_CreateYUVOverlay(codecContext->width, codecContext->height,
  635. SDL_YV12_OVERLAY, screen);
  636. } else {
  637. dest = CSDL_Ext::newSurface(codecContext->width, codecContext->height);
  638. destRect.x = destRect.y = 0;
  639. destRect.w = codecContext->width;
  640. destRect.h = codecContext->height;
  641. }
  642. if (overlay == NULL && dest == NULL)
  643. return false;
  644. // Convert the image into YUV format that SDL uses
  645. if (overlay) {
  646. sws = sws_getContext(codecContext->width, codecContext->height,
  647. codecContext->pix_fmt, codecContext->width, codecContext->height,
  648. PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
  649. } else {
  650. PixelFormat screenFormat = PIX_FMT_NONE;
  651. switch(screen->format->BytesPerPixel)
  652. {
  653. case 2: screenFormat = PIX_FMT_RGB565; break;
  654. case 3: screenFormat = PIX_FMT_RGB24; break;
  655. case 4: screenFormat = PIX_FMT_RGB32; break;
  656. default: return false;
  657. }
  658. sws = sws_getContext(codecContext->width, codecContext->height,
  659. codecContext->pix_fmt, codecContext->width, codecContext->height,
  660. screenFormat, SWS_BICUBIC, NULL, NULL, NULL);
  661. }
  662. if (sws == NULL)
  663. return false;
  664. pos.w = codecContext->width;
  665. pos.h = codecContext->height;
  666. return true;
  667. }
  668. // Read the next frame. Return false on error/end of file.
  669. bool CVideoPlayer::nextFrame()
  670. {
  671. AVPacket packet;
  672. int frameFinished = 0;
  673. bool gotError = false;
  674. if (sws == NULL)
  675. return false;
  676. while(!frameFinished) {
  677. int ret = av_read_frame(format, &packet);
  678. if (ret < 0) {
  679. // Error. It's probably an end of file.
  680. if (doLoop && !gotError) {
  681. // Rewind
  682. if (av_seek_frame(format, stream, 0, 0) < 0)
  683. break;
  684. gotError = true;
  685. } else {
  686. break;
  687. }
  688. } else {
  689. // Is this a packet from the video stream?
  690. if (packet.stream_index == stream) {
  691. // Decode video frame
  692. #ifdef WITH_AVCODEC_DECODE_VIDEO2
  693. avcodec_decode_video2(codecContext, frame, &frameFinished, &packet);
  694. #else
  695. avcodec_decode_video(codecContext, frame, &frameFinished,
  696. packet.data, packet.size);
  697. #endif
  698. // Did we get a video frame?
  699. if (frameFinished) {
  700. AVPicture pict;
  701. if (overlay) {
  702. SDL_LockYUVOverlay(overlay);
  703. pict.data[0] = overlay->pixels[0];
  704. pict.data[1] = overlay->pixels[2];
  705. pict.data[2] = overlay->pixels[1];
  706. pict.linesize[0] = overlay->pitches[0];
  707. pict.linesize[1] = overlay->pitches[2];
  708. pict.linesize[2] = overlay->pitches[1];
  709. sws_scale(sws, frame->data, frame->linesize,
  710. 0, codecContext->height, pict.data, pict.linesize);
  711. SDL_UnlockYUVOverlay(overlay);
  712. } else {
  713. pict.data[0] = (uint8_t *)dest->pixels;
  714. pict.linesize[0] = dest->pitch;
  715. sws_scale(sws, frame->data, frame->linesize,
  716. 0, codecContext->height, pict.data, pict.linesize);
  717. }
  718. }
  719. }
  720. av_free_packet(&packet);
  721. }
  722. }
  723. return frameFinished != 0;
  724. }
  725. void CVideoPlayer::show( int x, int y, SDL_Surface *dst, bool update )
  726. {
  727. if (sws == NULL)
  728. return;
  729. pos.x = x;
  730. pos.y = y;
  731. CSDL_Ext::blitSurface(dest, &destRect, dst, &pos);
  732. if (update)
  733. SDL_UpdateRect(dst, pos.x, pos.y, pos.w, pos.h);
  734. }
  735. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  736. {
  737. show(x, y, dst, update);
  738. }
  739. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  740. {
  741. if (sws == NULL)
  742. return;
  743. if (refreshCount <= 0)
  744. {
  745. refreshCount = refreshWait;
  746. if (nextFrame())
  747. show(x,y,dst,update);
  748. else {
  749. open(fname);
  750. nextFrame();
  751. // The y position is wrong at the first frame.
  752. // Note: either the windows player or the linux player is
  753. // broken. Compensate here until the bug is found.
  754. show(x, y--, dst, update);
  755. }
  756. }
  757. else {
  758. redraw(x, y, dst, update);
  759. }
  760. refreshCount --;
  761. }
  762. void CVideoPlayer::close()
  763. {
  764. fname = "";
  765. if (sws) {
  766. sws_freeContext(sws);
  767. sws = NULL;
  768. }
  769. if (overlay) {
  770. SDL_FreeYUVOverlay(overlay);
  771. overlay = NULL;
  772. }
  773. if (dest) {
  774. SDL_FreeSurface(dest);
  775. dest = NULL;
  776. }
  777. if (frame) {
  778. av_free(frame);
  779. frame = NULL;
  780. }
  781. if (codec) {
  782. avcodec_close(codecContext);
  783. codec = NULL;
  784. codecContext = NULL;
  785. }
  786. if (format) {
  787. av_close_input_file(format);
  788. format = NULL;
  789. }
  790. }
  791. // Plays a video. Only works for overlays.
  792. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  793. {
  794. // Note: either the windows player or the linux player is
  795. // broken. Compensate here until the bug is found.
  796. y--;
  797. pos.x = x;
  798. pos.y = y;
  799. while(nextFrame()) {
  800. if(stopOnKey && keyDown())
  801. return false;
  802. SDL_DisplayYUVOverlay(overlay, &pos);
  803. // Wait 3 frames
  804. GH.mainFPSmng->framerateDelay();
  805. GH.mainFPSmng->framerateDelay();
  806. GH.mainFPSmng->framerateDelay();
  807. }
  808. return true;
  809. }
  810. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  811. {
  812. open(name, false, true);
  813. bool ret = playVideo(x, y, dst, stopOnKey);
  814. close();
  815. return ret;
  816. }
  817. CVideoPlayer::~CVideoPlayer()
  818. {
  819. close();
  820. }
  821. #endif