CVideoHandler.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  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 CBIKHandler::redraw( int x, int y, SDL_Surface *dst, bool update )
  160. {
  161. int w = hBink->width, h = hBink->height;
  162. blitBuffer(buffer, x, y, w, h, dst);
  163. if(update)
  164. SDL_UpdateRect(dst, x, y, w, h);
  165. }
  166. void CSmackPlayer::nextFrame()
  167. {
  168. ptrSmackNextFrame(data);
  169. }
  170. bool CSmackPlayer::wait()
  171. {
  172. return ptrSmackWait(data);
  173. }
  174. CSmackPlayer::CSmackPlayer()
  175. {
  176. Instantiate("smackw32.dll");
  177. ptrSmackNextFrame = (SmackNextFrame)FindAddress("_SmackNextFrame@4");
  178. ptrSmackWait = (SmackWait)FindAddress("_SmackWait@4");
  179. ptrSmackDoFrame = (SmackDoFrame)FindAddress("_SmackDoFrame@4");
  180. ptrSmackToBuffer = (SmackToBuffer)FindAddress("_SmackToBuffer@28");
  181. ptrSmackOpen = (SmackOpen)FindAddress("_SmackOpen@12");
  182. ptrSmackSoundOnOff = (SmackSoundOnOff)FindAddress("_SmackSoundOnOff@8");
  183. ptrSmackClose = (SmackClose)FindAddress("_SmackClose@4");
  184. }
  185. CSmackPlayer::~CSmackPlayer()
  186. {
  187. if(data)
  188. close();
  189. }
  190. void CSmackPlayer::close()
  191. {
  192. ptrSmackClose(data);
  193. data = NULL;
  194. delete [] buffer;
  195. buffer = NULL;
  196. }
  197. void CSmackPlayer::open( std::string name )
  198. {
  199. Uint32 flags[2] = {0xff400, 0xfe400};
  200. data = ptrSmackOpen( (void*)name.c_str(), flags[1], -1);
  201. if (!data)
  202. {
  203. tlog1 << "Smack cannot open " << name << std::endl;
  204. return;
  205. }
  206. buffer = new char[data->width*data->height*2];
  207. buf = buffer+data->width*(data->height-1)*2; // adjust pointer position for later use by 'SmackToBuffer'
  208. }
  209. void CSmackPlayer::show( int x, int y, SDL_Surface *dst, bool update)
  210. {
  211. int w = data->width, h = data->height;
  212. int stripe = (-w*2) & (~3);
  213. //put frame to the buffer
  214. ptrSmackToBuffer(data, 0, 0, stripe, w, buf, 0x80000000);
  215. ptrSmackDoFrame(data);
  216. redraw(x, y, dst, update);
  217. }
  218. int CSmackPlayer::curFrame() const
  219. {
  220. return data->currentFrame;
  221. }
  222. int CSmackPlayer::frameCount() const
  223. {
  224. return data->frameCount;
  225. }
  226. void CSmackPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  227. {
  228. int w = data->width, h = data->height;
  229. /* Lock the screen for direct access to the pixels */
  230. if ( SDL_MUSTLOCK(dst) )
  231. {
  232. if ( SDL_LockSurface(dst) < 0 )
  233. {
  234. fprintf(stderr, "Can't lock screen: %s\n", SDL_GetError());
  235. return;
  236. }
  237. }
  238. // draw the frame
  239. Uint16* addr = (Uint16*) (buffer+w*(h-1)*2-2);
  240. for( int j=0; j<h-1; j++) // why -1 ?
  241. {
  242. for ( int i=w-1; i>=0; i--)
  243. {
  244. Uint16 pixel = *addr;
  245. Uint8 *p = (Uint8 *)dst->pixels + (j+y) * dst->pitch + (i + x) * dst->format->BytesPerPixel;
  246. p[2] = ((pixel & 0x7c00) >> 10) * 8;
  247. p[1] = ((pixel & 0x3e0) >> 5) * 8;
  248. p[0] = ((pixel & 0x1F)) * 8;
  249. addr--;
  250. }
  251. }
  252. if ( SDL_MUSTLOCK(dst) )
  253. {
  254. SDL_UnlockSurface(dst);
  255. }
  256. if(update)
  257. SDL_UpdateRect(dst, x, y, w, h);
  258. }
  259. CVideoPlayer::CVideoPlayer()
  260. {
  261. vidh = new CVidHandler(std::string(DATA_DIR "Data" PATHSEPARATOR "VIDEO.VID"));
  262. current = NULL;
  263. }
  264. CVideoPlayer::~CVideoPlayer()
  265. {
  266. delete vidh;
  267. }
  268. void CVideoPlayer::open(std::string name)
  269. {
  270. if(boost::algorithm::ends_with(name, ".BIK"))
  271. current = &bikPlayer;
  272. else
  273. current = &smkPlayer;
  274. fname = name;
  275. first = true;
  276. //extract video from video.vid so we can play it
  277. vidh->extract(name, name);
  278. current->open(name);
  279. }
  280. void CVideoPlayer::close()
  281. {
  282. if(!current)
  283. {
  284. tlog2 << "Closing no opened player...?" << std::endl;
  285. return;
  286. }
  287. current->close();
  288. current = NULL;
  289. if(!DeleteFileA(fname.c_str()))
  290. {
  291. tlog1 << "Cannot remove temporarily extracted video file: " << fname;
  292. checkForError(false);
  293. }
  294. fname.clear();
  295. }
  296. void CVideoPlayer::nextFrame()
  297. {
  298. current->nextFrame();
  299. }
  300. void CVideoPlayer::show(int x, int y, SDL_Surface *dst, bool update)
  301. {
  302. current->show(x, y, dst, update);
  303. }
  304. bool CVideoPlayer::wait()
  305. {
  306. return current->wait();
  307. }
  308. int CVideoPlayer::curFrame() const
  309. {
  310. return current->curFrame();
  311. }
  312. int CVideoPlayer::frameCount() const
  313. {
  314. return current->frameCount();
  315. }
  316. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey)
  317. {
  318. open(name);
  319. bool ret = playVideo(x, y, dst, stopOnKey);
  320. close();
  321. return ret;
  322. }
  323. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  324. {
  325. bool w = false;
  326. if(!first)
  327. {
  328. w = wait(); //check if should keep current frame
  329. if(!w)
  330. nextFrame();
  331. }
  332. else
  333. {
  334. first = false;
  335. }
  336. if(!w)
  337. {
  338. show(x,y,dst,update);
  339. }
  340. else if (forceRedraw)
  341. {
  342. redraw(x, y, dst, update);
  343. }
  344. }
  345. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  346. {
  347. current->redraw(x, y, dst, update);
  348. }
  349. //reads events and throws on key down
  350. bool keyDown()
  351. {
  352. SDL_Event ev;
  353. while(SDL_PollEvent(&ev))
  354. {
  355. if(ev.type == SDL_KEYDOWN || ev.type == SDL_MOUSEBUTTONDOWN)
  356. return true;
  357. }
  358. return false;
  359. }
  360. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  361. {
  362. int frame = 0;
  363. while(frame < frameCount()) //play all frames
  364. {
  365. if(stopOnKey && keyDown())
  366. return false;
  367. if(!wait())
  368. {
  369. show(x, y, dst);
  370. nextFrame();
  371. frame++;
  372. }
  373. SDL_Delay(20);
  374. }
  375. return true;
  376. }
  377. #else
  378. #include "../client/SDL_Extensions.h"
  379. extern "C" {
  380. #include <libavformat/avformat.h>
  381. #include <libswscale/swscale.h>
  382. }
  383. static const char *protocol_name = "lod";
  384. // Open a pseudo file. Name is something like 'lod:0x56432ab6c43df8fe'
  385. static int lod_open(URLContext *context, const char *filename, int flags)
  386. {
  387. CVideoPlayer *video;
  388. // Retrieve pointer to CVideoPlayer object
  389. filename += strlen(protocol_name) + 1;
  390. video = (CVideoPlayer *)(uintptr_t)strtoull(filename, NULL, 16);
  391. // TODO: check flags ?
  392. context->priv_data = video;
  393. return 0;
  394. }
  395. static int lod_close(URLContext* h)
  396. {
  397. return 0;
  398. }
  399. // Define a set of functions to read data
  400. static int lod_read(URLContext *context, unsigned char *buf, int size)
  401. {
  402. CVideoPlayer *video = (CVideoPlayer *)context->priv_data;
  403. amin(size, video->length - video->offset);
  404. if (size < 0)
  405. return -1;
  406. // TODO: can we avoid that copy ?
  407. memcpy(buf, video->data + video->offset, size);
  408. video->offset += size;
  409. return size;
  410. }
  411. static URLProtocol lod_protocol = {
  412. protocol_name,
  413. lod_open,
  414. lod_read,
  415. NULL, // no write
  416. NULL, // no seek
  417. lod_close
  418. };
  419. CVideoPlayer::CVideoPlayer()
  420. {
  421. format = NULL;
  422. frame = NULL;
  423. codec = NULL;
  424. sws = NULL;
  425. overlay = NULL;
  426. // Register codecs. TODO: May be overkill. Should call a
  427. // combination of av_register_input_format() /
  428. // av_register_output_format() / av_register_protocol() instead.
  429. av_register_all();
  430. // Register our protocol 'lod' so we can directly read from mmaped memory
  431. av_register_protocol(&lod_protocol);
  432. vidh = new CVidHandler(std::string(DATA_DIR "Data" PATHSEPARATOR "VIDEO.VID"));
  433. }
  434. bool CVideoPlayer::open(std::string fname, int x, int y)
  435. {
  436. char url[100];
  437. close();
  438. data = vidh->extract(fname, length);
  439. if (data == NULL)
  440. return false;
  441. offset = 0;
  442. // Create our URL name with the 'lod' protocol as a prefix and a
  443. // back pointer to our object. Should be 32 and 64 bits compatible.
  444. sprintf(url, "%s:0x%016llx", protocol_name, (unsigned long long)(uintptr_t)this);
  445. if (av_open_input_file(&format, url, NULL, 0, NULL)!=0)
  446. return false;
  447. // Retrieve stream information
  448. if (av_find_stream_info(format) < 0)
  449. return false;
  450. #if 0
  451. // Dump information about file onto standard error
  452. dump_format(format, 0, url, 0);
  453. #endif
  454. // Find the first video stream
  455. stream = -1;
  456. for(unsigned int i=0; i<format->nb_streams; i++) {
  457. if (format->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO) {
  458. stream = i;
  459. break;
  460. }
  461. }
  462. if (stream < 0)
  463. // No video stream in that file
  464. return false;
  465. // Get a pointer to the codec context for the video stream
  466. codecContext = format->streams[stream]->codec;
  467. // Find the decoder for the video stream
  468. codec = avcodec_find_decoder(codecContext->codec_id);
  469. if (codec == NULL) {
  470. // Unsupported codec
  471. return false;
  472. }
  473. // Open codec
  474. if (avcodec_open(codecContext, codec) <0 ) {
  475. // Could not open codec
  476. codec = NULL;
  477. return false;
  478. }
  479. // Allocate video frame
  480. frame = avcodec_alloc_frame();
  481. // Allocate a place to put our YUV image on that screen
  482. overlay = SDL_CreateYUVOverlay(codecContext->width, codecContext->height,
  483. SDL_YV12_OVERLAY, screen);
  484. // Convert the image into YUV format that SDL uses
  485. sws = sws_getContext(codecContext->width, codecContext->height,
  486. codecContext->pix_fmt, codecContext->width, codecContext->height,
  487. PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
  488. if (sws == NULL)
  489. return false;
  490. pos.x = x;
  491. pos.y = y;
  492. pos.w = codecContext->width;
  493. pos.h = codecContext->height;
  494. return true;
  495. }
  496. // Display the next frame. Return false on error/end of file.
  497. bool CVideoPlayer::nextFrame()
  498. {
  499. AVPacket packet;
  500. int frameFinished = 0;
  501. while(!frameFinished && av_read_frame(format, &packet)>=0) {
  502. // Is this a packet from the video stream?
  503. if (packet.stream_index == stream) {
  504. // Decode video frame
  505. avcodec_decode_video(codecContext, frame, &frameFinished,
  506. packet.data, packet.size);
  507. // Did we get a video frame?
  508. if (frameFinished) {
  509. SDL_LockYUVOverlay(overlay);
  510. AVPicture pict;
  511. pict.data[0] = overlay->pixels[0];
  512. pict.data[1] = overlay->pixels[2];
  513. pict.data[2] = overlay->pixels[1];
  514. pict.linesize[0] = overlay->pitches[0];
  515. pict.linesize[1] = overlay->pitches[2];
  516. pict.linesize[2] = overlay->pitches[1];
  517. sws_scale(sws, frame->data, frame->linesize,
  518. 0, codecContext->height, pict.data, pict.linesize);
  519. SDL_UnlockYUVOverlay(overlay);
  520. SDL_DisplayYUVOverlay(overlay, &pos);
  521. }
  522. }
  523. av_free_packet(&packet);
  524. }
  525. return frameFinished != 0;
  526. }
  527. void CVideoPlayer::close()
  528. {
  529. if (sws) {
  530. sws_freeContext(sws);
  531. sws = NULL;
  532. }
  533. if (overlay) {
  534. SDL_FreeYUVOverlay(overlay);
  535. overlay = NULL;
  536. }
  537. if (frame) {
  538. av_free(frame);
  539. frame = NULL;
  540. }
  541. if (codec) {
  542. avcodec_close(codecContext);
  543. codec = NULL;
  544. codecContext = NULL;
  545. }
  546. if (format) {
  547. av_close_input_file(format);
  548. format = NULL;
  549. }
  550. }
  551. CVideoPlayer::~CVideoPlayer()
  552. {
  553. close();
  554. }
  555. #endif