CVideoHandler.cpp 21 KB

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