CVideoHandler.cpp 11 KB

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