CVideoHandler.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. /*
  2. * CVideoHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include <SDL.h>
  12. #include "CVideoHandler.h"
  13. #include "gui/CGuiHandler.h"
  14. #include "gui/SDL_Extensions.h"
  15. #include "CPlayerInterface.h"
  16. #include "../lib/filesystem/Filesystem.h"
  17. extern CGuiHandler GH; //global gui handler
  18. #ifndef DISABLE_VIDEO
  19. //reads events and returns true on key down
  20. static bool keyDown()
  21. {
  22. SDL_Event ev;
  23. while(SDL_PollEvent(&ev))
  24. {
  25. if(ev.type == SDL_KEYDOWN || ev.type == SDL_MOUSEBUTTONDOWN)
  26. return true;
  27. }
  28. return false;
  29. }
  30. #ifdef _MSC_VER
  31. #pragma comment(lib, "avcodec.lib")
  32. #pragma comment(lib, "avutil.lib")
  33. #pragma comment(lib, "avformat.lib")
  34. #pragma comment(lib, "swscale.lib")
  35. #endif // _MSC_VER
  36. // Define a set of functions to read data
  37. static int lodRead(void * opaque, uint8_t * buf, int size)
  38. {
  39. auto video = reinterpret_cast<CVideoPlayer *>(opaque);
  40. return video->data->read(buf, size);
  41. }
  42. static si64 lodSeek(void * opaque, si64 pos, int whence)
  43. {
  44. auto video = reinterpret_cast<CVideoPlayer *>(opaque);
  45. if(whence & AVSEEK_SIZE)
  46. return video->data->getSize();
  47. return video->data->seek(pos);
  48. }
  49. CVideoPlayer::CVideoPlayer()
  50. {
  51. stream = -1;
  52. format = nullptr;
  53. codecContext = nullptr;
  54. codec = nullptr;
  55. frame = nullptr;
  56. sws = nullptr;
  57. context = nullptr;
  58. texture = nullptr;
  59. dest = nullptr;
  60. destRect = genRect(0, 0, 0, 0);
  61. pos = genRect(0, 0, 0, 0);
  62. refreshWait = 0;
  63. refreshCount = 0;
  64. doLoop = false;
  65. // Register codecs. TODO: May be overkill. Should call a
  66. // combination of av_register_input_format() /
  67. // av_register_output_format() / av_register_protocol() instead.
  68. av_register_all();
  69. }
  70. bool CVideoPlayer::open(std::string fname, bool scale)
  71. {
  72. return open(fname, true, false);
  73. }
  74. // loop = to loop through the video
  75. // useOverlay = directly write to the screen.
  76. bool CVideoPlayer::open(std::string fname, bool loop, bool useOverlay, bool scale)
  77. {
  78. close();
  79. this->fname = fname;
  80. refreshWait = 3;
  81. refreshCount = -1;
  82. doLoop = loop;
  83. ResourceID resource(std::string("Video/") + fname, EResType::VIDEO);
  84. if(!CResourceHandler::get()->existsResource(resource))
  85. {
  86. logGlobal->errorStream() << "Error: video " << resource.getName() << " was not found";
  87. return false;
  88. }
  89. data = CResourceHandler::get()->load(resource);
  90. static const int BUFFER_SIZE = 4096;
  91. unsigned char * buffer = (unsigned char *)av_malloc(BUFFER_SIZE); // will be freed by ffmpeg
  92. context = avio_alloc_context(buffer, BUFFER_SIZE, 0, (void *)this, lodRead, nullptr, lodSeek);
  93. format = avformat_alloc_context();
  94. format->pb = context;
  95. // filename is not needed - file was already open and stored in this->data;
  96. int avfopen = avformat_open_input(&format, "dummyFilename", nullptr, nullptr);
  97. if(avfopen != 0)
  98. {
  99. return false;
  100. }
  101. // Retrieve stream information
  102. if(avformat_find_stream_info(format, nullptr) < 0)
  103. return false;
  104. // Find the first video stream
  105. stream = -1;
  106. for(ui32 i = 0; i < format->nb_streams; i++)
  107. {
  108. if(format->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  109. {
  110. stream = i;
  111. break;
  112. }
  113. }
  114. if(stream < 0)
  115. // No video stream in that file
  116. return false;
  117. // Get a pointer to the codec context for the video stream
  118. codecContext = format->streams[stream]->codec;
  119. // Find the decoder for the video stream
  120. codec = avcodec_find_decoder(codecContext->codec_id);
  121. if(codec == nullptr)
  122. {
  123. // Unsupported codec
  124. return false;
  125. }
  126. // Open codec
  127. if(avcodec_open2(codecContext, codec, nullptr) < 0)
  128. {
  129. // Could not open codec
  130. codec = nullptr;
  131. return false;
  132. }
  133. // Allocate video frame
  134. frame = av_frame_alloc();
  135. //setup scaling
  136. if(scale)
  137. {
  138. pos.w = screen->w;
  139. pos.h = screen->h;
  140. }
  141. else
  142. {
  143. pos.w = codecContext->width;
  144. pos.h = codecContext->height;
  145. }
  146. // Allocate a place to put our YUV image on that screen
  147. if(useOverlay)
  148. {
  149. texture = SDL_CreateTexture(mainRenderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STATIC, pos.w, pos.h);
  150. }
  151. else
  152. {
  153. dest = CSDL_Ext::newSurface(pos.w, pos.h);
  154. destRect.x = destRect.y = 0;
  155. destRect.w = pos.w;
  156. destRect.h = pos.h;
  157. }
  158. if(texture == nullptr && dest == nullptr)
  159. return false;
  160. if(texture)
  161. { // Convert the image into YUV format that SDL uses
  162. sws = sws_getContext(codecContext->width, codecContext->height, codecContext->pix_fmt,
  163. pos.w, pos.h,
  164. AV_PIX_FMT_YUV420P,
  165. SWS_BICUBIC, nullptr, nullptr, nullptr);
  166. }
  167. else
  168. {
  169. AVPixelFormat screenFormat = AV_PIX_FMT_NONE;
  170. if(screen->format->Bshift > screen->format->Rshift)
  171. {
  172. // this a BGR surface
  173. switch(screen->format->BytesPerPixel)
  174. {
  175. case 2:
  176. screenFormat = AV_PIX_FMT_BGR565;
  177. break;
  178. case 3:
  179. screenFormat = AV_PIX_FMT_BGR24;
  180. break;
  181. case 4:
  182. screenFormat = AV_PIX_FMT_BGR32;
  183. break;
  184. default:
  185. return false;
  186. }
  187. }
  188. else
  189. {
  190. // this a RGB surface
  191. switch(screen->format->BytesPerPixel)
  192. {
  193. case 2:
  194. screenFormat = AV_PIX_FMT_RGB565;
  195. break;
  196. case 3:
  197. screenFormat = AV_PIX_FMT_RGB24;
  198. break;
  199. case 4:
  200. screenFormat = AV_PIX_FMT_RGB32;
  201. break;
  202. default:
  203. return false;
  204. }
  205. }
  206. sws = sws_getContext(codecContext->width, codecContext->height, codecContext->pix_fmt,
  207. pos.w, pos.h, screenFormat,
  208. SWS_BICUBIC, nullptr, nullptr, nullptr);
  209. }
  210. if(sws == nullptr)
  211. return false;
  212. return true;
  213. }
  214. // Read the next frame. Return false on error/end of file.
  215. bool CVideoPlayer::nextFrame()
  216. {
  217. AVPacket packet;
  218. int frameFinished = 0;
  219. bool gotError = false;
  220. if(sws == nullptr)
  221. return false;
  222. while(!frameFinished)
  223. {
  224. int ret = av_read_frame(format, &packet);
  225. if(ret < 0)
  226. {
  227. // Error. It's probably an end of file.
  228. if(doLoop && !gotError)
  229. {
  230. // Rewind
  231. if(av_seek_frame(format, stream, 0, AVSEEK_FLAG_BYTE) < 0)
  232. break;
  233. gotError = true;
  234. }
  235. else
  236. {
  237. break;
  238. }
  239. }
  240. else
  241. {
  242. // Is this a packet from the video stream?
  243. if(packet.stream_index == stream)
  244. {
  245. // Decode video frame
  246. avcodec_decode_video2(codecContext, frame, &frameFinished, &packet);
  247. // Did we get a video frame?
  248. if(frameFinished)
  249. {
  250. AVPicture pict;
  251. if(texture)
  252. {
  253. avpicture_alloc(&pict, AV_PIX_FMT_YUV420P, pos.w, pos.h);
  254. sws_scale(sws, frame->data, frame->linesize,
  255. 0, codecContext->height, pict.data, pict.linesize);
  256. SDL_UpdateYUVTexture(texture, NULL, pict.data[0], pict.linesize[0],
  257. pict.data[1], pict.linesize[1],
  258. pict.data[2], pict.linesize[2]);
  259. avpicture_free(&pict);
  260. }
  261. else
  262. {
  263. pict.data[0] = (ui8 *)dest->pixels;
  264. pict.linesize[0] = dest->pitch;
  265. sws_scale(sws, frame->data, frame->linesize,
  266. 0, codecContext->height, pict.data, pict.linesize);
  267. }
  268. }
  269. }
  270. av_free_packet(&packet);
  271. }
  272. }
  273. return frameFinished != 0;
  274. }
  275. void CVideoPlayer::show(int x, int y, SDL_Surface * dst, bool update)
  276. {
  277. if(sws == nullptr)
  278. return;
  279. pos.x = x;
  280. pos.y = y;
  281. CSDL_Ext::blitSurface(dest, &destRect, dst, &pos);
  282. if(update)
  283. SDL_UpdateRect(dst, pos.x, pos.y, pos.w, pos.h);
  284. }
  285. void CVideoPlayer::redraw(int x, int y, SDL_Surface * dst, bool update)
  286. {
  287. show(x, y, dst, update);
  288. }
  289. void CVideoPlayer::update(int x, int y, SDL_Surface * dst, bool forceRedraw, bool update)
  290. {
  291. if(sws == nullptr)
  292. return;
  293. if(refreshCount <= 0)
  294. {
  295. refreshCount = refreshWait;
  296. if(nextFrame())
  297. show(x, y, dst, update);
  298. else
  299. {
  300. open(fname);
  301. nextFrame();
  302. // The y position is wrong at the first frame.
  303. // Note: either the windows player or the linux player is
  304. // broken. Compensate here until the bug is found.
  305. show(x, y--, dst, update);
  306. }
  307. }
  308. else
  309. {
  310. redraw(x, y, dst, update);
  311. }
  312. refreshCount--;
  313. }
  314. void CVideoPlayer::close()
  315. {
  316. fname = "";
  317. if(sws)
  318. {
  319. sws_freeContext(sws);
  320. sws = nullptr;
  321. }
  322. if(texture)
  323. {
  324. SDL_DestroyTexture(texture);
  325. texture = nullptr;
  326. }
  327. if(dest)
  328. {
  329. SDL_FreeSurface(dest);
  330. dest = nullptr;
  331. }
  332. if(frame)
  333. {
  334. av_frame_free(&frame); //will be set to null
  335. }
  336. if(codec)
  337. {
  338. avcodec_close(codecContext);
  339. codec = nullptr;
  340. codecContext = nullptr;
  341. }
  342. if(format)
  343. {
  344. avformat_close_input(&format);
  345. }
  346. if(context)
  347. {
  348. av_free(context);
  349. context = nullptr;
  350. }
  351. }
  352. // Plays a video. Only works for overlays.
  353. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface * dst, bool stopOnKey)
  354. {
  355. // Note: either the windows player or the linux player is
  356. // broken. Compensate here until the bug is found.
  357. y--;
  358. pos.x = x;
  359. pos.y = y;
  360. while(nextFrame())
  361. {
  362. if(stopOnKey && keyDown())
  363. return false;
  364. SDL_RenderCopy(mainRenderer, texture, NULL, &pos);
  365. SDL_RenderPresent(mainRenderer);
  366. // Wait 3 frames
  367. GH.mainFPSmng->framerateDelay();
  368. GH.mainFPSmng->framerateDelay();
  369. GH.mainFPSmng->framerateDelay();
  370. }
  371. return true;
  372. }
  373. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface * dst, bool stopOnKey, bool scale)
  374. {
  375. open(name, false, true, scale);
  376. bool ret = playVideo(x, y, dst, stopOnKey);
  377. close();
  378. return ret;
  379. }
  380. CVideoPlayer::~CVideoPlayer()
  381. {
  382. close();
  383. }
  384. #endif