CVideoHandler.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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 static_cast<int>(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->error("Error: video %s was not found", resource.getName());
  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: screenFormat = AV_PIX_FMT_BGR565; break;
  176. case 3: screenFormat = AV_PIX_FMT_BGR24; break;
  177. case 4: screenFormat = AV_PIX_FMT_BGR32; break;
  178. default: return false;
  179. }
  180. }
  181. else
  182. {
  183. // this a RGB surface
  184. switch (screen->format->BytesPerPixel)
  185. {
  186. case 2: screenFormat = AV_PIX_FMT_RGB565; break;
  187. case 3: screenFormat = AV_PIX_FMT_RGB24; break;
  188. case 4: screenFormat = AV_PIX_FMT_RGB32; break;
  189. default: return false;
  190. }
  191. }
  192. sws = sws_getContext(codecContext->width, codecContext->height, codecContext->pix_fmt,
  193. pos.w, pos.h, screenFormat,
  194. SWS_BICUBIC, nullptr, nullptr, nullptr);
  195. }
  196. if (sws == nullptr)
  197. return false;
  198. return true;
  199. }
  200. // Read the next frame. Return false on error/end of file.
  201. bool CVideoPlayer::nextFrame()
  202. {
  203. AVPacket packet;
  204. int frameFinished = 0;
  205. bool gotError = false;
  206. if (sws == nullptr)
  207. return false;
  208. while(!frameFinished)
  209. {
  210. int ret = av_read_frame(format, &packet);
  211. if (ret < 0)
  212. {
  213. // Error. It's probably an end of file.
  214. if (doLoop && !gotError)
  215. {
  216. // Rewind
  217. if (av_seek_frame(format, stream, 0, AVSEEK_FLAG_BYTE) < 0)
  218. break;
  219. gotError = true;
  220. }
  221. else
  222. {
  223. break;
  224. }
  225. }
  226. else
  227. {
  228. // Is this a packet from the video stream?
  229. if (packet.stream_index == stream)
  230. {
  231. // Decode video frame
  232. avcodec_decode_video2(codecContext, frame, &frameFinished, &packet);
  233. // Did we get a video frame?
  234. if (frameFinished)
  235. {
  236. AVPicture pict;
  237. if (texture) {
  238. avpicture_alloc(&pict, AV_PIX_FMT_YUV420P, pos.w, pos.h);
  239. sws_scale(sws, frame->data, frame->linesize,
  240. 0, codecContext->height, pict.data, pict.linesize);
  241. SDL_UpdateYUVTexture(texture, NULL, pict.data[0], pict.linesize[0],
  242. pict.data[1], pict.linesize[1],
  243. pict.data[2], pict.linesize[2]);
  244. avpicture_free(&pict);
  245. }
  246. else
  247. {
  248. pict.data[0] = (ui8 *)dest->pixels;
  249. pict.linesize[0] = dest->pitch;
  250. sws_scale(sws, frame->data, frame->linesize,
  251. 0, codecContext->height, pict.data, pict.linesize);
  252. }
  253. }
  254. }
  255. av_free_packet(&packet);
  256. }
  257. }
  258. return frameFinished != 0;
  259. }
  260. void CVideoPlayer::show( int x, int y, SDL_Surface *dst, bool update )
  261. {
  262. if (sws == nullptr)
  263. return;
  264. pos.x = x;
  265. pos.y = y;
  266. CSDL_Ext::blitSurface(dest, &destRect, dst, &pos);
  267. if (update)
  268. SDL_UpdateRect(dst, pos.x, pos.y, pos.w, pos.h);
  269. }
  270. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  271. {
  272. show(x, y, dst, update);
  273. }
  274. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  275. {
  276. if (sws == nullptr)
  277. return;
  278. if (refreshCount <= 0)
  279. {
  280. refreshCount = refreshWait;
  281. if (nextFrame())
  282. show(x,y,dst,update);
  283. else
  284. {
  285. open(fname);
  286. nextFrame();
  287. // The y position is wrong at the first frame.
  288. // Note: either the windows player or the linux player is
  289. // broken. Compensate here until the bug is found.
  290. show(x, y--, dst, update);
  291. }
  292. }
  293. else
  294. {
  295. redraw(x, y, dst, update);
  296. }
  297. refreshCount --;
  298. }
  299. void CVideoPlayer::close()
  300. {
  301. fname = "";
  302. if (sws)
  303. {
  304. sws_freeContext(sws);
  305. sws = nullptr;
  306. }
  307. if (texture)
  308. {
  309. SDL_DestroyTexture(texture);
  310. texture = nullptr;
  311. }
  312. if (dest)
  313. {
  314. SDL_FreeSurface(dest);
  315. dest = nullptr;
  316. }
  317. if (frame)
  318. {
  319. av_frame_free(&frame);//will be set to null
  320. }
  321. if (codec)
  322. {
  323. avcodec_close(codecContext);
  324. codec = nullptr;
  325. codecContext = nullptr;
  326. }
  327. if (format)
  328. {
  329. avformat_close_input(&format);
  330. }
  331. if (context)
  332. {
  333. av_free(context);
  334. context = nullptr;
  335. }
  336. }
  337. // Plays a video. Only works for overlays.
  338. bool CVideoPlayer::playVideo(int x, int y, bool stopOnKey)
  339. {
  340. // Note: either the windows player or the linux player is
  341. // broken. Compensate here until the bug is found.
  342. y--;
  343. pos.x = x;
  344. pos.y = y;
  345. while(nextFrame())
  346. {
  347. if(stopOnKey && keyDown())
  348. return false;
  349. SDL_RenderCopy(mainRenderer, texture, nullptr, &pos);
  350. SDL_RenderPresent(mainRenderer);
  351. // Wait 3 frames
  352. GH.mainFPSmng->framerateDelay();
  353. GH.mainFPSmng->framerateDelay();
  354. GH.mainFPSmng->framerateDelay();
  355. }
  356. return true;
  357. }
  358. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, bool stopOnKey, bool scale)
  359. {
  360. open(name, false, true, scale);
  361. bool ret = playVideo(x, y, stopOnKey);
  362. close();
  363. return ret;
  364. }
  365. CVideoPlayer::~CVideoPlayer()
  366. {
  367. close();
  368. }
  369. #endif