CVideoHandler.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  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. void CBIKHandler::nextFrame()
  190. {
  191. binkNextFrame(hBink);
  192. }
  193. void CBIKHandler::close()
  194. {
  195. binkClose(hBink);
  196. hBink = NULL;
  197. CloseHandle(hBinkFile);
  198. hBinkFile = NULL;
  199. delete [] buffer;
  200. buffer = NULL;
  201. bufferSize = 0;
  202. }
  203. bool CBIKHandler::wait()
  204. {
  205. return binkWait(hBink);
  206. }
  207. int CBIKHandler::curFrame() const
  208. {
  209. return hBink->currentFrame;
  210. }
  211. int CBIKHandler::frameCount() const
  212. {
  213. return hBink->frameCount;
  214. }
  215. void CBIKHandler::redraw( int x, int y, SDL_Surface *dst, bool update )
  216. {
  217. int w = hBink->width, h = hBink->height;
  218. blitBuffer(buffer, x, y, w, h, dst);
  219. if(update)
  220. SDL_UpdateRect(dst, x, y, w, h);
  221. }
  222. void CBIKHandler::allocBuffer(int Bpp)
  223. {
  224. if(!Bpp) Bpp = screen->format->BytesPerPixel;
  225. bufferSize = hBink->width * hBink->height * Bpp;
  226. buffer = new char[bufferSize];
  227. }
  228. void CBIKHandler::freeBuffer()
  229. {
  230. delete [] buffer;
  231. buffer = NULL;
  232. bufferSize = 0;
  233. }
  234. void CSmackPlayer::nextFrame()
  235. {
  236. ptrSmackNextFrame(data);
  237. }
  238. bool CSmackPlayer::wait()
  239. {
  240. return ptrSmackWait(data);
  241. }
  242. CSmackPlayer::CSmackPlayer() : data(NULL)
  243. {
  244. Instantiate("smackw32.dll");
  245. ptrSmackNextFrame = (SmackNextFrame)FindAddress("_SmackNextFrame@4");
  246. ptrSmackWait = (SmackWait)FindAddress("_SmackWait@4");
  247. ptrSmackDoFrame = (SmackDoFrame)FindAddress("_SmackDoFrame@4");
  248. ptrSmackToBuffer = (SmackToBuffer)FindAddress("_SmackToBuffer@28");
  249. ptrSmackOpen = (SmackOpen)FindAddress("_SmackOpen@12");
  250. ptrSmackSoundOnOff = (SmackSoundOnOff)FindAddress("_SmackSoundOnOff@8");
  251. ptrSmackClose = (SmackClose)FindAddress("_SmackClose@4");
  252. ptrVolumePan = (SmackVolumePan)FindAddress("_SmackVolumePan@16");
  253. }
  254. CSmackPlayer::~CSmackPlayer()
  255. {
  256. if(data)
  257. close();
  258. }
  259. void CSmackPlayer::close()
  260. {
  261. ptrSmackClose(data);
  262. data = NULL;
  263. }
  264. bool CSmackPlayer::open( std::string name )
  265. {
  266. Uint32 flags[2] = {0xff400, 0xfe400};
  267. data = ptrSmackOpen( (void*)name.c_str(), flags[1], -1);
  268. if (!data)
  269. {
  270. tlog1 << "Smack cannot open " << name << std::endl;
  271. checkForError(false);
  272. return false;
  273. }
  274. buffer = new char[data->width*data->height*2];
  275. buf = buffer+data->width*(data->height-1)*2; // adjust pointer position for later use by 'SmackToBuffer'
  276. //ptrVolumePan(data, 0xfe000, 3640 * GDefaultOptions.musicVolume / 11, 0x8000); //set volume
  277. return true;
  278. }
  279. void CSmackPlayer::show( int x, int y, SDL_Surface *dst, bool update)
  280. {
  281. int w = data->width, h = data->height;
  282. int stripe = (-w*2) & (~3);
  283. //put frame to the buffer
  284. ptrSmackToBuffer(data, 0, 0, stripe, w, buf, 0x80000000);
  285. ptrSmackDoFrame(data);
  286. redraw(x, y, dst, update);
  287. }
  288. int CSmackPlayer::curFrame() const
  289. {
  290. return data->currentFrame;
  291. }
  292. int CSmackPlayer::frameCount() const
  293. {
  294. return data->frameCount;
  295. }
  296. void CSmackPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  297. {
  298. int w = std::min<int>(data->width, dst->w - x), h = std::min<int>(data->height, dst->h - y);
  299. /* Lock the screen for direct access to the pixels */
  300. if ( SDL_MUSTLOCK(dst) )
  301. {
  302. if ( SDL_LockSurface(dst) < 0 )
  303. {
  304. fprintf(stderr, "Can't lock screen: %s\n", SDL_GetError());
  305. return;
  306. }
  307. }
  308. // draw the frame
  309. Uint16* addr = (Uint16*) (buffer+w*(h-1)*2-2);
  310. if(dst->format->BytesPerPixel >= 3)
  311. {
  312. for( int j=0; j<h-1; j++) // why -1 ?
  313. {
  314. for ( int i=w-1; i>=0; i--)
  315. {
  316. Uint16 pixel = *addr;
  317. Uint8 *p = (Uint8 *)dst->pixels + (j+y) * dst->pitch + (i + x) * dst->format->BytesPerPixel;
  318. p[2] = ((pixel & 0x7c00) >> 10) * 8;
  319. p[1] = ((pixel & 0x3e0) >> 5) * 8;
  320. p[0] = ((pixel & 0x1F)) * 8;
  321. addr--;
  322. }
  323. }
  324. }
  325. else if(dst->format->BytesPerPixel == 2)
  326. {
  327. for( int j=0; j<h-1; j++) // why -1 ?
  328. {
  329. for ( int i=w-1; i>=0; i--)
  330. {
  331. //convert rgb 555 to 565
  332. Uint16 pixel = *addr;
  333. Uint16 *p = (Uint16 *)((Uint8 *)dst->pixels + (j+y) * dst->pitch + (i + x) * dst->format->BytesPerPixel);
  334. *p = (pixel & 0x1F)
  335. + ((pixel & 0x3e0) << 1)
  336. + ((pixel & 0x7c00) << 1);
  337. addr--;
  338. }
  339. }
  340. }
  341. if ( SDL_MUSTLOCK(dst) )
  342. {
  343. SDL_UnlockSurface(dst);
  344. }
  345. if(update)
  346. SDL_UpdateRect(dst, x, y, w, h);
  347. }
  348. CVideoPlayer::CVideoPlayer()
  349. {
  350. vidh.add_file(std::string(DATA_DIR "/Data/VIDEO.VID"));
  351. vidh.add_file(std::string(DATA_DIR "/Data/H3ab_ahd.vid"));
  352. current = NULL;
  353. }
  354. CVideoPlayer::~CVideoPlayer()
  355. {
  356. }
  357. bool CVideoPlayer::open(std::string name)
  358. {
  359. if(boost::algorithm::ends_with(name, ".BIK"))
  360. current = &bikPlayer;
  361. else
  362. current = &smkPlayer;
  363. fname = name;
  364. first = true;
  365. //extract video from video.vid so we can play it
  366. bool opened = false;
  367. vidh.extract(name, name);
  368. if (boost::filesystem::exists(name))
  369. opened = current->open(name);
  370. else // couldn't load video then load from ab resource file
  371. {
  372. vidh.extract(name, name);
  373. if (boost::filesystem::exists(name))
  374. opened = current->open(name);
  375. }
  376. if(!opened) // check if video could be loaded
  377. {
  378. current = NULL;
  379. tlog3 << "Failed to open video file " << name << std::endl;
  380. }
  381. return opened;
  382. }
  383. void CVideoPlayer::close()
  384. {
  385. if(!current)
  386. {
  387. tlog2 << "Closing no opened player...?" << std::endl;
  388. return;
  389. }
  390. current->close();
  391. current = NULL;
  392. if(!DeleteFileA(fname.c_str()))
  393. {
  394. tlog1 << "Cannot remove temporarily extracted video file: " << fname;
  395. checkForError(false);
  396. }
  397. fname.clear();
  398. }
  399. void CVideoPlayer::nextFrame()
  400. {
  401. if(current)
  402. current->nextFrame();
  403. }
  404. void CVideoPlayer::show(int x, int y, SDL_Surface *dst, bool update)
  405. {
  406. if(current)
  407. current->show(x, y, dst, update);
  408. }
  409. bool CVideoPlayer::wait()
  410. {
  411. if(current)
  412. return current->wait();
  413. else
  414. return false;
  415. }
  416. int CVideoPlayer::curFrame() const
  417. {
  418. if(current)
  419. return current->curFrame();
  420. else
  421. return -1;
  422. }
  423. int CVideoPlayer::frameCount() const
  424. {
  425. if(current)
  426. return current->frameCount();
  427. else
  428. return -1;
  429. }
  430. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  431. {
  432. if(!open(name))
  433. return false;
  434. bool ret = playVideo(x, y, dst, stopOnKey);
  435. close();
  436. return ret;
  437. }
  438. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  439. {
  440. if(!current)
  441. return;
  442. bool w = false;
  443. if(!first)
  444. {
  445. w = wait(); //check if should keep current frame
  446. if(!w)
  447. nextFrame();
  448. }
  449. else
  450. {
  451. first = false;
  452. }
  453. if(!w)
  454. {
  455. show(x,y,dst,update);
  456. }
  457. else if (forceRedraw)
  458. {
  459. redraw(x, y, dst, update);
  460. }
  461. }
  462. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  463. {
  464. if(current)
  465. current->redraw(x, y, dst, update);
  466. }
  467. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  468. {
  469. if(!current)
  470. return false;
  471. int frame = 0;
  472. while(frame < frameCount()) //play all frames
  473. {
  474. if(stopOnKey && keyDown())
  475. return false;
  476. if(!wait())
  477. {
  478. show(x, y, dst);
  479. nextFrame();
  480. frame++;
  481. }
  482. SDL_Delay(20);
  483. }
  484. return true;
  485. }
  486. #else
  487. //Workaround for compile error in ffmpeg (UINT_64C was not declared)
  488. #define __STDC_CONSTANT_MACROS
  489. #ifdef _STDINT_H
  490. #undef _STDINT_H
  491. #endif
  492. #include <stdint.h>
  493. #include "SDL_framerate.h"
  494. extern "C" {
  495. #include <libavformat/avformat.h>
  496. #include <libswscale/swscale.h>
  497. }
  498. static const char *protocol_name = "lod";
  499. // Open a pseudo file. Name is something like 'lod:0x56432ab6c43df8fe'
  500. static int lod_open(URLContext *context, const char *filename, int flags)
  501. {
  502. CVideoPlayer *video;
  503. // Retrieve pointer to CVideoPlayer object
  504. filename += strlen(protocol_name) + 1;
  505. video = (CVideoPlayer *)(uintptr_t)strtoull(filename, NULL, 16);
  506. // TODO: check flags ?
  507. context->priv_data = video;
  508. return 0;
  509. }
  510. static int lod_close(URLContext* h)
  511. {
  512. return 0;
  513. }
  514. // Define a set of functions to read data
  515. static int lod_read(URLContext *context, unsigned char *buf, int size)
  516. {
  517. CVideoPlayer *video = (CVideoPlayer *)context->priv_data;
  518. amin(size, video->length - video->offset);
  519. if (size < 0)
  520. return -1;
  521. // TODO: can we avoid that copy ?
  522. memcpy(buf, video->data + video->offset, size);
  523. video->offset += size;
  524. return size;
  525. }
  526. static int64_t lod_seek(URLContext *context, int64_t pos, int whence)
  527. {
  528. CVideoPlayer *video = (CVideoPlayer *)context->priv_data;
  529. // Not sure what the parameter whence is. Assuming it always
  530. // indicates an absolute value;
  531. video->offset = pos;
  532. amin(video->offset, video->length);
  533. return -1;//video->offset;
  534. }
  535. static URLProtocol lod_protocol = {
  536. protocol_name,
  537. lod_open,
  538. lod_read,
  539. NULL, // no write
  540. lod_seek,
  541. lod_close
  542. };
  543. CVideoPlayer::CVideoPlayer()
  544. {
  545. format = NULL;
  546. frame = NULL;
  547. codec = NULL;
  548. sws = NULL;
  549. overlay = NULL;
  550. dest = NULL;
  551. // Register codecs. TODO: May be overkill. Should call a
  552. // combination of av_register_input_format() /
  553. // av_register_output_format() / av_register_protocol() instead.
  554. av_register_all();
  555. // Register our protocol 'lod' so we can directly read from mmaped memory
  556. #ifdef WITH_AV_REGISTER_PROTOCOL2
  557. av_register_protocol2(&lod_protocol, sizeof(lod_protocol));
  558. #else
  559. av_register_protocol(&lod_protocol);
  560. #endif
  561. vidh.add_file(std::string(DATA_DIR "/Data/VIDEO.VID"));
  562. vidh.add_file(std::string(DATA_DIR "/Data/H3ab_ahd.vid"));
  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. data = vidh.extract(fname, length);
  575. if (data) {
  576. // Create our URL name with the 'lod' protocol as a prefix and a
  577. // back pointer to our object. Should be 32 and 64 bits compatible.
  578. char url[100];
  579. sprintf(url, "%s:0x%016llx", protocol_name, (unsigned long long)(uintptr_t)this);
  580. #if LIBAVFORMAT_VERSION_MAJOR < 54
  581. int avfopen = av_open_input_file(&format, url, NULL, 0, NULL);
  582. #else
  583. int avfopen = avformat_open_input(&format, url, NULL, NULL);
  584. #endif
  585. if (avfopen != 0) {
  586. return false;
  587. }
  588. } else {
  589. // File is not in a container
  590. #if LIBAVFORMAT_VERSION_MAJOR < 54
  591. int avfopen = av_open_input_file(&format, (DATA_DIR "/Data/video/" + fname).c_str(), NULL, 0, NULL);
  592. #else
  593. int avfopen = avformat_open_input(&format, (DATA_DIR "/Data/video/" + fname).c_str(), NULL, NULL);
  594. #endif
  595. if (avfopen != 0) {
  596. // tlog1 << "Video file not found: " DATA_DIR "/Data/video/" + fname << std::endl;
  597. return false;
  598. }
  599. }
  600. // Retrieve stream information
  601. if (av_find_stream_info(format) < 0)
  602. return false;
  603. // Find the first video stream
  604. stream = -1;
  605. for(unsigned int i=0; i<format->nb_streams; i++) {
  606. #if LIBAVCODEC_VERSION_MAJOR < 53
  607. if (format->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO)
  608. #else
  609. if (format->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
  610. #endif
  611. {
  612. stream = i;
  613. break;
  614. }
  615. }
  616. if (stream < 0)
  617. // No video stream in that file
  618. return false;
  619. // Get a pointer to the codec context for the video stream
  620. codecContext = format->streams[stream]->codec;
  621. // Find the decoder for the video stream
  622. codec = avcodec_find_decoder(codecContext->codec_id);
  623. if (codec == NULL) {
  624. // Unsupported codec
  625. return false;
  626. }
  627. // Open codec
  628. if (avcodec_open(codecContext, codec) <0 ) {
  629. // Could not open codec
  630. codec = NULL;
  631. return false;
  632. }
  633. // Allocate video frame
  634. frame = avcodec_alloc_frame();
  635. // Allocate a place to put our YUV image on that screen
  636. if (useOverlay) {
  637. overlay = SDL_CreateYUVOverlay(codecContext->width, codecContext->height,
  638. SDL_YV12_OVERLAY, screen);
  639. } else {
  640. dest = CSDL_Ext::newSurface(codecContext->width, codecContext->height);
  641. destRect.x = destRect.y = 0;
  642. destRect.w = codecContext->width;
  643. destRect.h = codecContext->height;
  644. }
  645. if (overlay == NULL && dest == NULL)
  646. return false;
  647. // Convert the image into YUV format that SDL uses
  648. if (overlay) {
  649. sws = sws_getContext(codecContext->width, codecContext->height,
  650. codecContext->pix_fmt, codecContext->width, codecContext->height,
  651. PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
  652. } else {
  653. PixelFormat screenFormat = PIX_FMT_NONE;
  654. switch(screen->format->BytesPerPixel)
  655. {
  656. case 2: screenFormat = PIX_FMT_RGB565; break;
  657. case 3: screenFormat = PIX_FMT_RGB24; break;
  658. case 4: screenFormat = PIX_FMT_RGB32; break;
  659. default: return false;
  660. }
  661. sws = sws_getContext(codecContext->width, codecContext->height,
  662. codecContext->pix_fmt, codecContext->width, codecContext->height,
  663. screenFormat, SWS_BICUBIC, NULL, NULL, NULL);
  664. }
  665. if (sws == NULL)
  666. return false;
  667. pos.w = codecContext->width;
  668. pos.h = codecContext->height;
  669. return true;
  670. }
  671. // Read the next frame. Return false on error/end of file.
  672. bool CVideoPlayer::nextFrame()
  673. {
  674. AVPacket packet;
  675. int frameFinished = 0;
  676. bool gotError = false;
  677. if (sws == NULL)
  678. return false;
  679. while(!frameFinished) {
  680. int ret = av_read_frame(format, &packet);
  681. if (ret < 0) {
  682. // Error. It's probably an end of file.
  683. if (doLoop && !gotError) {
  684. // Rewind
  685. if (av_seek_frame(format, stream, 0, 0) < 0)
  686. break;
  687. gotError = true;
  688. } else {
  689. break;
  690. }
  691. } else {
  692. // Is this a packet from the video stream?
  693. if (packet.stream_index == stream) {
  694. // Decode video frame
  695. #ifdef WITH_AVCODEC_DECODE_VIDEO2
  696. avcodec_decode_video2(codecContext, frame, &frameFinished, &packet);
  697. #else
  698. avcodec_decode_video(codecContext, frame, &frameFinished,
  699. packet.data, packet.size);
  700. #endif
  701. // Did we get a video frame?
  702. if (frameFinished) {
  703. AVPicture pict;
  704. if (overlay) {
  705. SDL_LockYUVOverlay(overlay);
  706. pict.data[0] = overlay->pixels[0];
  707. pict.data[1] = overlay->pixels[2];
  708. pict.data[2] = overlay->pixels[1];
  709. pict.linesize[0] = overlay->pitches[0];
  710. pict.linesize[1] = overlay->pitches[2];
  711. pict.linesize[2] = overlay->pitches[1];
  712. sws_scale(sws, frame->data, frame->linesize,
  713. 0, codecContext->height, pict.data, pict.linesize);
  714. SDL_UnlockYUVOverlay(overlay);
  715. } else {
  716. pict.data[0] = (uint8_t *)dest->pixels;
  717. pict.linesize[0] = dest->pitch;
  718. sws_scale(sws, frame->data, frame->linesize,
  719. 0, codecContext->height, pict.data, pict.linesize);
  720. }
  721. }
  722. }
  723. av_free_packet(&packet);
  724. }
  725. }
  726. return frameFinished != 0;
  727. }
  728. void CVideoPlayer::show( int x, int y, SDL_Surface *dst, bool update )
  729. {
  730. if (sws == NULL)
  731. return;
  732. pos.x = x;
  733. pos.y = y;
  734. CSDL_Ext::blitSurface(dest, &destRect, dst, &pos);
  735. if (update)
  736. SDL_UpdateRect(dst, pos.x, pos.y, pos.w, pos.h);
  737. }
  738. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  739. {
  740. show(x, y, dst, update);
  741. }
  742. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  743. {
  744. if (sws == NULL)
  745. return;
  746. if (refreshCount <= 0)
  747. {
  748. refreshCount = refreshWait;
  749. if (nextFrame())
  750. show(x,y,dst,update);
  751. else {
  752. open(fname);
  753. nextFrame();
  754. // The y position is wrong at the first frame.
  755. // Note: either the windows player or the linux player is
  756. // broken. Compensate here until the bug is found.
  757. show(x, y--, dst, update);
  758. }
  759. }
  760. else {
  761. redraw(x, y, dst, update);
  762. }
  763. refreshCount --;
  764. }
  765. void CVideoPlayer::close()
  766. {
  767. fname = "";
  768. if (sws) {
  769. sws_freeContext(sws);
  770. sws = NULL;
  771. }
  772. if (overlay) {
  773. SDL_FreeYUVOverlay(overlay);
  774. overlay = NULL;
  775. }
  776. if (dest) {
  777. SDL_FreeSurface(dest);
  778. dest = NULL;
  779. }
  780. if (frame) {
  781. av_free(frame);
  782. frame = NULL;
  783. }
  784. if (codec) {
  785. avcodec_close(codecContext);
  786. codec = NULL;
  787. codecContext = NULL;
  788. }
  789. if (format) {
  790. av_close_input_file(format);
  791. format = NULL;
  792. }
  793. }
  794. // Plays a video. Only works for overlays.
  795. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  796. {
  797. // Note: either the windows player or the linux player is
  798. // broken. Compensate here until the bug is found.
  799. y--;
  800. pos.x = x;
  801. pos.y = y;
  802. while(nextFrame()) {
  803. if(stopOnKey && keyDown())
  804. return false;
  805. SDL_DisplayYUVOverlay(overlay, &pos);
  806. // Wait 3 frames
  807. GH.mainFPSmng->framerateDelay();
  808. GH.mainFPSmng->framerateDelay();
  809. GH.mainFPSmng->framerateDelay();
  810. }
  811. return true;
  812. }
  813. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  814. {
  815. open(name, false, true);
  816. bool ret = playVideo(x, y, dst, stopOnKey);
  817. close();
  818. return ret;
  819. }
  820. CVideoPlayer::~CVideoPlayer()
  821. {
  822. close();
  823. }
  824. #endif