CVideoHandler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. #include "../stdafx.h"
  2. #include <iostream>
  3. #include "CSndHandler.h"
  4. #include "CVideoHandler.h"
  5. #include <SDL.h>
  6. #ifdef _WIN32
  7. #include "../client/SDL_Extensions.h"
  8. #include <boost/algorithm/string/predicate.hpp>
  9. void checkForError(bool throwing = true)
  10. {
  11. #ifdef _WIN32
  12. int error = GetLastError();
  13. if(!error)
  14. return;
  15. tlog1 << "Error " << error << " encountered!\n";
  16. std::string msg;
  17. char* pTemp = NULL;
  18. FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
  19. NULL, error, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), (LPSTR)&pTemp, 1, NULL );
  20. tlog1 << "Error: " << pTemp << std::endl;
  21. msg = pTemp;
  22. LocalFree( pTemp );
  23. pTemp = NULL;
  24. if(throwing)
  25. throw msg;
  26. #endif
  27. }
  28. void blitBuffer(char *buffer, int x, int y, int w, int h, SDL_Surface *dst)
  29. {
  30. const int bpp = dst->format->BytesPerPixel;
  31. char *dest;
  32. for(int i = h; i > 0; i--)
  33. {
  34. dest = (char*)dst->pixels + dst->pitch*(y+h-i) + x*dst->format->BytesPerPixel;
  35. memcpy(dest, buffer, bpp*w);
  36. buffer += bpp*w;
  37. }
  38. }
  39. void DLLHandler::Instantiate(const char *filename)
  40. {
  41. name = filename;
  42. #ifdef _WIN32
  43. dll = LoadLibraryA(filename);
  44. if(!dll)
  45. {
  46. tlog1 << "Failed loading " << filename << std::endl;
  47. checkForError();
  48. }
  49. #else
  50. dll = dlopen(filename,RTLD_LOCAL | RTLD_LAZY);
  51. #endif
  52. }
  53. void *DLLHandler::FindAddress(const char *symbol)
  54. {
  55. void *ret;
  56. #ifdef _WIN32
  57. ret = (void*) GetProcAddress(dll,symbol);
  58. if(!ret)
  59. {
  60. tlog1 << "Failed to find " << symbol << " in " << name << std::endl;
  61. checkForError();
  62. }
  63. #else
  64. ret = (void *)dlsym(dll, symbol);
  65. #endif
  66. return ret;
  67. }
  68. DLLHandler::~DLLHandler()
  69. {
  70. if(dll)
  71. {
  72. #ifdef _WIN32
  73. if(!FreeLibrary(dll))
  74. {
  75. tlog1 << "Failed to free " << name << std::endl;
  76. checkForError();
  77. }
  78. #else
  79. dlclose(dll);
  80. #endif
  81. }
  82. }
  83. DLLHandler::DLLHandler()
  84. {
  85. dll = NULL;
  86. }
  87. CBIKHandler::CBIKHandler()
  88. {
  89. Instantiate("BINKW32.DLL");
  90. //binkGetError = FindAddress("_BinkGetError@0");
  91. binkOpen = (BinkOpen)FindAddress("_BinkOpen@8");
  92. binkSetSoundSystem = (BinkSetSoundSystem)FindAddress("_BinkSetSoundSystem@8");
  93. //getPalette = (BinkGetPalette)FindAddress("_BinkGetPalette@4");
  94. binkNextFrame = (BinkNextFrame)FindAddress("_BinkNextFrame@4");
  95. binkDoFrame = (BinkDoFrame)FindAddress("_BinkDoFrame@4");
  96. binkCopyToBuffer = (BinkCopyToBuffer)FindAddress("_BinkCopyToBuffer@28");
  97. binkWait = (BinkWait)FindAddress("_BinkWait@4");
  98. binkClose = (BinkClose)FindAddress("_BinkClose@4");
  99. hBinkFile = NULL;
  100. hBink = NULL;
  101. }
  102. void CBIKHandler::open(std::string name)
  103. {
  104. hBinkFile = CreateFileA
  105. (
  106. name.c_str(), // file name
  107. GENERIC_READ, // access mode
  108. FILE_SHARE_READ, // share mode
  109. NULL, // Security Descriptor
  110. OPEN_EXISTING, // how to create
  111. FILE_ATTRIBUTE_NORMAL,//FILE_FLAG_SEQUENTIAL_SCAN, // file attributes
  112. 0 // handle to template file
  113. );
  114. if(hBinkFile == INVALID_HANDLE_VALUE)
  115. {
  116. tlog1 << "BIK handler: failed to open " << name << std::endl;
  117. checkForError();
  118. return;
  119. }
  120. void *waveout = GetProcAddress(dll,"_BinkOpenWaveOut@4");
  121. if(waveout)
  122. binkSetSoundSystem(waveout,NULL);
  123. hBink = binkOpen(hBinkFile, 0x8a800000);
  124. buffer = new char[hBink->width * hBink->width * 3];
  125. }
  126. void CBIKHandler::show( int x, int y, SDL_Surface *dst, bool update )
  127. {
  128. int w = hBink->width, h = hBink->height;
  129. binkDoFrame(hBink);
  130. binkCopyToBuffer(hBink, buffer, w*3, h, 0, 0, 0);
  131. blitBuffer(buffer, x, y, w, h, dst);
  132. if(update)
  133. SDL_UpdateRect(dst, x, y, w, h);
  134. }
  135. void CBIKHandler::nextFrame()
  136. {
  137. binkNextFrame(hBink);
  138. }
  139. void CBIKHandler::close()
  140. {
  141. binkClose(hBink);
  142. hBink = NULL;
  143. CloseHandle(hBinkFile);
  144. hBinkFile = NULL;
  145. delete [] buffer;
  146. }
  147. bool CBIKHandler::wait()
  148. {
  149. return binkWait(hBink);
  150. }
  151. int CBIKHandler::curFrame() const
  152. {
  153. return hBink->currentFrame;
  154. }
  155. int CBIKHandler::frameCount() const
  156. {
  157. return hBink->frameCount;
  158. }
  159. void CSmackPlayer::nextFrame()
  160. {
  161. ptrSmackNextFrame(data);
  162. }
  163. bool CSmackPlayer::wait()
  164. {
  165. return ptrSmackWait(data);
  166. }
  167. CSmackPlayer::CSmackPlayer()
  168. {
  169. Instantiate("smackw32.dll");
  170. ptrSmackNextFrame = (SmackNextFrame)FindAddress("_SmackNextFrame@4");
  171. ptrSmackWait = (SmackWait)FindAddress("_SmackWait@4");
  172. ptrSmackDoFrame = (SmackDoFrame)FindAddress("_SmackDoFrame@4");
  173. ptrSmackToBuffer = (SmackToBuffer)FindAddress("_SmackToBuffer@28");
  174. ptrSmackOpen = (SmackOpen)FindAddress("_SmackOpen@12");
  175. ptrSmackSoundOnOff = (SmackSoundOnOff)FindAddress("_SmackSoundOnOff@8");
  176. ptrSmackClose = (SmackClose)FindAddress("_SmackClose@4");
  177. }
  178. CSmackPlayer::~CSmackPlayer()
  179. {
  180. if(data)
  181. close();
  182. }
  183. void CSmackPlayer::close()
  184. {
  185. ptrSmackClose(data);
  186. data = NULL;
  187. delete [] buffer;
  188. buffer = NULL;
  189. }
  190. void CSmackPlayer::open( std::string name )
  191. {
  192. Uint32 flags[2] = {0xff400, 0xfe400};
  193. data = ptrSmackOpen( (void*)name.c_str(), flags[1], -1);
  194. if (!data)
  195. {
  196. tlog1 << "Smack cannot open " << name << std::endl;
  197. return;
  198. }
  199. buffer = new char[data->width*data->height*2];
  200. buf = buffer+data->width*(data->height-1)*2; // adjust pointer position for later use by 'SmackToBuffer'
  201. }
  202. void CSmackPlayer::show( int x, int y, SDL_Surface *dst, bool update)
  203. {
  204. int w = data->width, h = data->height;
  205. int stripe = (-w*2) & (~3);
  206. //put frame to the buffer
  207. ptrSmackToBuffer(data, 0, 0, stripe, w, buf, 0x80000000);
  208. ptrSmackDoFrame(data);
  209. /* Lock the screen for direct access to the pixels */
  210. if ( SDL_MUSTLOCK(dst) )
  211. {
  212. if ( SDL_LockSurface(dst) < 0 )
  213. {
  214. fprintf(stderr, "Can't lock screen: %s\n", SDL_GetError());
  215. return;
  216. }
  217. }
  218. // draw the frame
  219. Uint16* addr = (Uint16*) (buffer+w*(h-1)*2-2);
  220. for( int j=0; j<h-1; j++) // why -1 ?
  221. {
  222. for ( int i=w-1; i>=0; i--)
  223. {
  224. Uint16 pixel = *addr;
  225. Uint8 *p = (Uint8 *)dst->pixels + (j+y) * dst->pitch + (i + x) * dst->format->BytesPerPixel;
  226. p[2] = ((pixel & 0x7c00) >> 10) * 8;
  227. p[1] = ((pixel & 0x3e0) >> 5) * 8;
  228. p[0] = ((pixel & 0x1F)) * 8;
  229. addr--;
  230. }
  231. }
  232. if ( SDL_MUSTLOCK(dst) )
  233. {
  234. SDL_UnlockSurface(dst);
  235. }
  236. if(update)
  237. SDL_UpdateRect(dst, x, y, w, h);
  238. }
  239. int CSmackPlayer::curFrame() const
  240. {
  241. return data->currentFrame;
  242. }
  243. int CSmackPlayer::frameCount() const
  244. {
  245. return data->frameCount;
  246. }
  247. CVideoPlayer::CVideoPlayer()
  248. {
  249. vidh = new CVidHandler(std::string(DATA_DIR "Data" PATHSEPARATOR "VIDEO.VID"));
  250. current = NULL;
  251. }
  252. CVideoPlayer::~CVideoPlayer()
  253. {
  254. delete vidh;
  255. }
  256. void CVideoPlayer::open(std::string name)
  257. {
  258. if(boost::algorithm::ends_with(name, ".BIK"))
  259. current = &bikPlayer;
  260. else
  261. current = &smkPlayer;
  262. fname = name;
  263. //extract video from video.vid so we can play it
  264. vidh->extract(name, name);
  265. current->open(name);
  266. }
  267. void CVideoPlayer::close()
  268. {
  269. if(!current)
  270. {
  271. tlog2 << "Closing no opened player...?" << std::endl;
  272. return;
  273. }
  274. current->close();
  275. current = NULL;
  276. if(!DeleteFileA(fname.c_str()))
  277. {
  278. tlog1 << "Cannot remove temporarily extracted video file: " << fname;
  279. checkForError(false);
  280. }
  281. fname.clear();
  282. }
  283. void CVideoPlayer::nextFrame()
  284. {
  285. current->nextFrame();
  286. }
  287. void CVideoPlayer::show(int x, int y, SDL_Surface *dst, bool update)
  288. {
  289. current->show(x, y, dst, update);
  290. }
  291. bool CVideoPlayer::wait()
  292. {
  293. return current->wait();
  294. }
  295. int CVideoPlayer::curFrame() const
  296. {
  297. return current->curFrame();
  298. }
  299. int CVideoPlayer::frameCount() const
  300. {
  301. return current->frameCount();
  302. }
  303. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  304. {
  305. open(name);
  306. bool ret = playVideo(x, y, dst, stopOnKey);
  307. close();
  308. return ret;
  309. }
  310. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool redraw, bool update )
  311. {
  312. bool w = wait(); //check if should keep current frame
  313. if(!w)
  314. nextFrame();
  315. if(!w || redraw) //redraw if changed frame or we was told to
  316. show(x,y,dst,update);
  317. }
  318. //reads events and throws on key down
  319. bool keyDown()
  320. {
  321. SDL_Event ev;
  322. while(SDL_PollEvent(&ev))
  323. {
  324. if(ev.type == SDL_KEYDOWN || ev.type == SDL_MOUSEBUTTONDOWN)
  325. return true;
  326. }
  327. return false;
  328. }
  329. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  330. {
  331. int frame = 0;
  332. while(frame < frameCount()) //play all frames
  333. {
  334. if(stopOnKey && keyDown())
  335. return false;
  336. if(!wait())
  337. {
  338. show(x, y, dst);
  339. nextFrame();
  340. frame++;
  341. }
  342. SDL_Delay(20);
  343. }
  344. return true;
  345. }
  346. #else
  347. #include "../client/SDL_Extensions.h"
  348. extern "C" {
  349. #include <libavformat/avformat.h>
  350. #include <libswscale/swscale.h>
  351. }
  352. static const char *protocol_name = "lod";
  353. // Open a pseudo file. Name is something like 'lod:0x56432ab6c43df8fe'
  354. static int lod_open(URLContext *context, const char *filename, int flags)
  355. {
  356. CVideoPlayer *video;
  357. // Retrieve pointer to CVideoPlayer object
  358. filename += strlen(protocol_name) + 1;
  359. video = (CVideoPlayer *)(uintptr_t)strtoull(filename, NULL, 16);
  360. // TODO: check flags ?
  361. context->priv_data = video;
  362. return 0;
  363. }
  364. static int lod_close(URLContext* h)
  365. {
  366. return 0;
  367. }
  368. // Define a set of functions to read data
  369. static int lod_read(URLContext *context, unsigned char *buf, int size)
  370. {
  371. CVideoPlayer *video = (CVideoPlayer *)context->priv_data;
  372. amin(size, video->length - video->offset);
  373. if (size < 0)
  374. return -1;
  375. // TODO: can we avoid that copy ?
  376. memcpy(buf, video->data + video->offset, size);
  377. video->offset += size;
  378. return size;
  379. }
  380. static URLProtocol lod_protocol = {
  381. protocol_name,
  382. lod_open,
  383. lod_read,
  384. NULL, // no write
  385. NULL, // no seek
  386. lod_close
  387. };
  388. CVideoPlayer::CVideoPlayer()
  389. {
  390. format = NULL;
  391. frame = NULL;
  392. codec = NULL;
  393. sws = NULL;
  394. overlay = NULL;
  395. // Register codecs. TODO: May be overkill. Should call a
  396. // combination of av_register_input_format() /
  397. // av_register_output_format() / av_register_protocol() instead.
  398. av_register_all();
  399. // Register our protocol 'lod' so we can directly read from mmaped memory
  400. av_register_protocol(&lod_protocol);
  401. vidh = new CVidHandler(std::string(DATA_DIR "Data" PATHSEPARATOR "VIDEO.VID"));
  402. }
  403. bool CVideoPlayer::open(std::string fname, int x, int y)
  404. {
  405. char url[100];
  406. close();
  407. data = vidh->extract(fname, length);
  408. if (data == NULL)
  409. return false;
  410. offset = 0;
  411. // Create our URL name with the 'lod' protocol as a prefix and a
  412. // back pointer to our object. Should be 32 and 64 bits compatible.
  413. sprintf(url, "%s:0x%016llx", protocol_name, (unsigned long long)(uintptr_t)this);
  414. if (av_open_input_file(&format, url, NULL, 0, NULL)!=0)
  415. return false;
  416. // Retrieve stream information
  417. if (av_find_stream_info(format) < 0)
  418. return false;
  419. #if 0
  420. // Dump information about file onto standard error
  421. dump_format(format, 0, url, 0);
  422. #endif
  423. // Find the first video stream
  424. stream = -1;
  425. for(unsigned int i=0; i<format->nb_streams; i++) {
  426. if (format->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO) {
  427. stream = i;
  428. break;
  429. }
  430. }
  431. if (stream < 0)
  432. // No video stream in that file
  433. return false;
  434. // Get a pointer to the codec context for the video stream
  435. codecContext = format->streams[stream]->codec;
  436. // Find the decoder for the video stream
  437. codec = avcodec_find_decoder(codecContext->codec_id);
  438. if (codec == NULL) {
  439. // Unsupported codec
  440. return false;
  441. }
  442. // Open codec
  443. if (avcodec_open(codecContext, codec) <0 ) {
  444. // Could not open codec
  445. codec = NULL;
  446. return false;
  447. }
  448. // Allocate video frame
  449. frame = avcodec_alloc_frame();
  450. // Allocate a place to put our YUV image on that screen
  451. overlay = SDL_CreateYUVOverlay(codecContext->width, codecContext->height,
  452. SDL_YV12_OVERLAY, screen);
  453. // Convert the image into YUV format that SDL uses
  454. sws = sws_getContext(codecContext->width, codecContext->height,
  455. codecContext->pix_fmt, codecContext->width, codecContext->height,
  456. PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
  457. if (sws == NULL)
  458. return false;
  459. pos.x = x;
  460. pos.y = y;
  461. pos.w = codecContext->width;
  462. pos.h = codecContext->height;
  463. return true;
  464. }
  465. // Display the next frame. Return false on error/end of file.
  466. bool CVideoPlayer::nextFrame()
  467. {
  468. AVPacket packet;
  469. int frameFinished = 0;
  470. while(!frameFinished && av_read_frame(format, &packet)>=0) {
  471. // Is this a packet from the video stream?
  472. if (packet.stream_index == stream) {
  473. // Decode video frame
  474. avcodec_decode_video(codecContext, frame, &frameFinished,
  475. packet.data, packet.size);
  476. // Did we get a video frame?
  477. if (frameFinished) {
  478. SDL_LockYUVOverlay(overlay);
  479. AVPicture pict;
  480. pict.data[0] = overlay->pixels[0];
  481. pict.data[1] = overlay->pixels[2];
  482. pict.data[2] = overlay->pixels[1];
  483. pict.linesize[0] = overlay->pitches[0];
  484. pict.linesize[1] = overlay->pitches[2];
  485. pict.linesize[2] = overlay->pitches[1];
  486. sws_scale(sws, frame->data, frame->linesize,
  487. 0, codecContext->height, pict.data, pict.linesize);
  488. SDL_UnlockYUVOverlay(overlay);
  489. SDL_DisplayYUVOverlay(overlay, &pos);
  490. }
  491. }
  492. av_free_packet(&packet);
  493. }
  494. return frameFinished != 0;
  495. }
  496. void CVideoPlayer::close()
  497. {
  498. if (sws) {
  499. sws_freeContext(sws);
  500. sws = NULL;
  501. }
  502. if (overlay) {
  503. SDL_FreeYUVOverlay(overlay);
  504. overlay = NULL;
  505. }
  506. if (frame) {
  507. av_free(frame);
  508. frame = NULL;
  509. }
  510. if (codec) {
  511. avcodec_close(codecContext);
  512. codec = NULL;
  513. codecContext = NULL;
  514. }
  515. if (format) {
  516. av_close_input_file(format);
  517. format = NULL;
  518. }
  519. }
  520. CVideoPlayer::~CVideoPlayer()
  521. {
  522. close();
  523. }
  524. #endif