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