CVideoHandler.cpp 21 KB

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