CVideoHandler.cpp 11 KB

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