CVideoHandler.cpp 20 KB

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