CVideoHandler.cpp 11 KB

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