CVideoHandler.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. }
  66. bool CVideoPlayer::open(std::string fname, bool scale)
  67. {
  68. return open(fname, true, false);
  69. }
  70. // loop = to loop through the video
  71. // useOverlay = directly write to the screen.
  72. bool CVideoPlayer::open(std::string fname, bool loop, bool useOverlay, bool scale)
  73. {
  74. close();
  75. this->fname = fname;
  76. refreshWait = 3;
  77. refreshCount = -1;
  78. doLoop = loop;
  79. ResourceID resource(std::string("Video/") + fname, EResType::VIDEO);
  80. if (!CResourceHandler::get()->existsResource(resource))
  81. {
  82. logGlobal->error("Error: video %s was not found", resource.getName());
  83. return false;
  84. }
  85. data = CResourceHandler::get()->load(resource);
  86. static const int BUFFER_SIZE = 4096;
  87. unsigned char * buffer = (unsigned char *)av_malloc(BUFFER_SIZE);// will be freed by ffmpeg
  88. context = avio_alloc_context( buffer, BUFFER_SIZE, 0, (void *)this, lodRead, nullptr, lodSeek);
  89. format = avformat_alloc_context();
  90. format->pb = context;
  91. // filename is not needed - file was already open and stored in this->data;
  92. int avfopen = avformat_open_input(&format, "dummyFilename", nullptr, nullptr);
  93. if (avfopen != 0)
  94. {
  95. return false;
  96. }
  97. // Retrieve stream information
  98. if (avformat_find_stream_info(format, nullptr) < 0)
  99. return false;
  100. // Find the first video stream
  101. stream = -1;
  102. for(ui32 i=0; i<format->nb_streams; i++)
  103. {
  104. if (format->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  105. {
  106. stream = i;
  107. break;
  108. }
  109. }
  110. if (stream < 0)
  111. // No video stream in that file
  112. return false;
  113. // Find the decoder for the video stream
  114. codec = avcodec_find_decoder(format->streams[stream]->codecpar->codec_id);
  115. if (codec == nullptr)
  116. {
  117. // Unsupported codec
  118. return false;
  119. }
  120. codecContext = avcodec_alloc_context3(codec);
  121. if(!codecContext)
  122. return false;
  123. // Get a pointer to the codec context for the video stream
  124. int ret = avcodec_parameters_to_context(codecContext, format->streams[stream]->codecpar);
  125. if (ret < 0)
  126. {
  127. //We cannot get codec from parameters
  128. avcodec_free_context(&codecContext);
  129. return false;
  130. }
  131. // Open codec
  132. if ( avcodec_open2(codecContext, codec, nullptr) < 0 )
  133. {
  134. // Could not open codec
  135. codec = nullptr;
  136. return false;
  137. }
  138. // Allocate video frame
  139. frame = av_frame_alloc();
  140. //setup scaling
  141. if(scale)
  142. {
  143. pos.w = screen->w;
  144. pos.h = screen->h;
  145. }
  146. else
  147. {
  148. pos.w = codecContext->width;
  149. pos.h = codecContext->height;
  150. }
  151. // Allocate a place to put our YUV image on that screen
  152. if (useOverlay)
  153. {
  154. texture = SDL_CreateTexture( mainRenderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STATIC, pos.w, pos.h);
  155. }
  156. else
  157. {
  158. dest = CSDL_Ext::newSurface(pos.w, pos.h);
  159. destRect.x = destRect.y = 0;
  160. destRect.w = pos.w;
  161. destRect.h = pos.h;
  162. }
  163. if (texture == nullptr && dest == nullptr)
  164. return false;
  165. if (texture)
  166. { // Convert the image into YUV format that SDL uses
  167. sws = sws_getContext(codecContext->width, codecContext->height, codecContext->pix_fmt,
  168. pos.w, pos.h,
  169. AV_PIX_FMT_YUV420P,
  170. SWS_BICUBIC, nullptr, nullptr, nullptr);
  171. }
  172. else
  173. {
  174. AVPixelFormat screenFormat = AV_PIX_FMT_NONE;
  175. if (screen->format->Bshift > screen->format->Rshift)
  176. {
  177. // this a BGR surface
  178. switch (screen->format->BytesPerPixel)
  179. {
  180. case 2: screenFormat = AV_PIX_FMT_BGR565; break;
  181. case 3: screenFormat = AV_PIX_FMT_BGR24; break;
  182. case 4: screenFormat = AV_PIX_FMT_BGR32; break;
  183. default: return false;
  184. }
  185. }
  186. else
  187. {
  188. // this a RGB surface
  189. switch (screen->format->BytesPerPixel)
  190. {
  191. case 2: screenFormat = AV_PIX_FMT_RGB565; break;
  192. case 3: screenFormat = AV_PIX_FMT_RGB24; break;
  193. case 4: screenFormat = AV_PIX_FMT_RGB32; break;
  194. default: return false;
  195. }
  196. }
  197. sws = sws_getContext(codecContext->width, codecContext->height, codecContext->pix_fmt,
  198. pos.w, pos.h, screenFormat,
  199. SWS_BICUBIC, nullptr, nullptr, nullptr);
  200. }
  201. if (sws == nullptr)
  202. return false;
  203. return true;
  204. }
  205. // Read the next frame. Return false on error/end of file.
  206. bool CVideoPlayer::nextFrame()
  207. {
  208. AVPacket packet;
  209. int frameFinished = 0;
  210. bool gotError = false;
  211. if (sws == nullptr)
  212. return false;
  213. while(!frameFinished)
  214. {
  215. int ret = av_read_frame(format, &packet);
  216. if (ret < 0)
  217. {
  218. // Error. It's probably an end of file.
  219. if (doLoop && !gotError)
  220. {
  221. // Rewind
  222. if (av_seek_frame(format, stream, 0, AVSEEK_FLAG_BYTE) < 0)
  223. break;
  224. gotError = true;
  225. }
  226. else
  227. {
  228. break;
  229. }
  230. }
  231. else
  232. {
  233. // Is this a packet from the video stream?
  234. if (packet.stream_index == stream)
  235. {
  236. // Decode video frame
  237. int rc = avcodec_send_packet(codecContext, &packet);
  238. if (rc >=0)
  239. packet.size = 0;
  240. rc = avcodec_receive_frame(codecContext, frame);
  241. if (rc >= 0)
  242. frameFinished = 1;
  243. // Did we get a video frame?
  244. if (frameFinished)
  245. {
  246. uint8_t *data[4];
  247. int linesize[4];
  248. if (texture) {
  249. av_image_alloc(data, linesize, pos.w, pos.h, AV_PIX_FMT_YUV420P, 1);
  250. sws_scale(sws, frame->data, frame->linesize,
  251. 0, codecContext->height, data, linesize);
  252. SDL_UpdateYUVTexture(texture, NULL, data[0], linesize[0],
  253. data[1], linesize[1],
  254. data[2], linesize[2]);
  255. av_freep(&data[0]);
  256. }
  257. else
  258. {
  259. /* Avoid buffer overflow caused by sws_scale():
  260. * http://trac.ffmpeg.org/ticket/9254
  261. * Currently (ffmpeg-4.4 with SSE3 enabled) sws_scale()
  262. * has a few requirements for target data buffers on rescaling:
  263. * 1. buffer has to be aligned to be usable for SIMD instructions
  264. * 2. buffer has to be padded to allow small overflow by SIMD instructions
  265. * Unfortunately SDL_Surface does not provide these guarantees.
  266. * This means that atempt to rescale directly into SDL surface causes
  267. * memory corruption. Usually it happens on campaign selection screen
  268. * where short video moves start spinning on mouse hover.
  269. *
  270. * To fix [1.] we use av_malloc() for memory allocation.
  271. * To fix [2.] we add an `ffmpeg_pad` that provides plenty of space.
  272. * We have to use intermdiate buffer and then use memcpy() to land it
  273. * to SDL_Surface.
  274. */
  275. size_t pic_bytes = dest->pitch * dest->h;
  276. size_t ffmped_pad = 1024; /* a few bytes of overflow will go here */
  277. void * for_sws = av_malloc (pic_bytes + ffmped_pad);
  278. data[0] = (ui8 *)for_sws;
  279. linesize[0] = dest->pitch;
  280. sws_scale(sws, frame->data, frame->linesize,
  281. 0, codecContext->height, data, linesize);
  282. memcpy(dest->pixels, for_sws, pic_bytes);
  283. av_free(for_sws);
  284. }
  285. }
  286. }
  287. av_packet_unref(&packet);
  288. }
  289. }
  290. return frameFinished != 0;
  291. }
  292. void CVideoPlayer::show( int x, int y, SDL_Surface *dst, bool update )
  293. {
  294. if (sws == nullptr)
  295. return;
  296. pos.x = x;
  297. pos.y = y;
  298. CSDL_Ext::blitSurface(dest, &destRect, dst, &pos);
  299. if (update)
  300. SDL_UpdateRect(dst, pos.x, pos.y, pos.w, pos.h);
  301. }
  302. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  303. {
  304. show(x, y, dst, update);
  305. }
  306. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  307. {
  308. if (sws == nullptr)
  309. return;
  310. if (refreshCount <= 0)
  311. {
  312. refreshCount = refreshWait;
  313. if (nextFrame())
  314. show(x,y,dst,update);
  315. else
  316. {
  317. open(fname);
  318. nextFrame();
  319. // The y position is wrong at the first frame.
  320. // Note: either the windows player or the linux player is
  321. // broken. Compensate here until the bug is found.
  322. show(x, y--, dst, update);
  323. }
  324. }
  325. else
  326. {
  327. redraw(x, y, dst, update);
  328. }
  329. refreshCount --;
  330. }
  331. void CVideoPlayer::close()
  332. {
  333. fname.clear();
  334. if (sws)
  335. {
  336. sws_freeContext(sws);
  337. sws = nullptr;
  338. }
  339. if (texture)
  340. {
  341. SDL_DestroyTexture(texture);
  342. texture = nullptr;
  343. }
  344. if (dest)
  345. {
  346. SDL_FreeSurface(dest);
  347. dest = nullptr;
  348. }
  349. if (frame)
  350. {
  351. av_frame_free(&frame);//will be set to null
  352. }
  353. if (codec)
  354. {
  355. avcodec_close(codecContext);
  356. codec = nullptr;
  357. }
  358. if (codecContext)
  359. {
  360. avcodec_free_context(&codecContext);
  361. }
  362. if (format)
  363. {
  364. avformat_close_input(&format);
  365. }
  366. if (context)
  367. {
  368. av_free(context);
  369. context = nullptr;
  370. }
  371. }
  372. // Plays a video. Only works for overlays.
  373. bool CVideoPlayer::playVideo(int x, int y, bool stopOnKey)
  374. {
  375. // Note: either the windows player or the linux player is
  376. // broken. Compensate here until the bug is found.
  377. y--;
  378. pos.x = x;
  379. pos.y = y;
  380. while(nextFrame())
  381. {
  382. if(stopOnKey && keyDown())
  383. return false;
  384. SDL_RenderCopy(mainRenderer, texture, nullptr, &pos);
  385. SDL_RenderPresent(mainRenderer);
  386. // Wait 3 frames
  387. GH.mainFPSmng->framerateDelay();
  388. GH.mainFPSmng->framerateDelay();
  389. GH.mainFPSmng->framerateDelay();
  390. }
  391. return true;
  392. }
  393. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, bool stopOnKey, bool scale)
  394. {
  395. open(name, false, true, scale);
  396. bool ret = playVideo(x, y, stopOnKey);
  397. close();
  398. return ret;
  399. }
  400. CVideoPlayer::~CVideoPlayer()
  401. {
  402. close();
  403. }
  404. #endif