CVideoHandler.cpp 21 KB

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