CVideoHandler.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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 & fname, bool loop, bool useOverlay, bool scale)
  68. {
  69. close();
  70. this->fname = fname.addPrefix("VIDEO/");
  71. doLoop = loop;
  72. frameTime = 0;
  73. if (!CResourceHandler::get()->existsResource(fname))
  74. {
  75. logGlobal->error("Error: video %s was not found", fname.getName());
  76. return false;
  77. }
  78. data = CResourceHandler::get()->load(fname);
  79. static const int BUFFER_SIZE = 4096;
  80. unsigned char * buffer = (unsigned char *)av_malloc(BUFFER_SIZE);// will be freed by ffmpeg
  81. context = avio_alloc_context( buffer, BUFFER_SIZE, 0, (void *)this, lodRead, nullptr, lodSeek);
  82. format = avformat_alloc_context();
  83. format->pb = context;
  84. // filename is not needed - file was already open and stored in this->data;
  85. int avfopen = avformat_open_input(&format, "dummyFilename", nullptr, nullptr);
  86. if (avfopen != 0)
  87. {
  88. return false;
  89. }
  90. // Retrieve stream information
  91. if (avformat_find_stream_info(format, nullptr) < 0)
  92. return false;
  93. // Find the first video stream
  94. stream = -1;
  95. for(ui32 i=0; i<format->nb_streams; i++)
  96. {
  97. if (format->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  98. {
  99. stream = i;
  100. break;
  101. }
  102. }
  103. if (stream < 0)
  104. // No video stream in that file
  105. return false;
  106. // Find the decoder for the video stream
  107. codec = avcodec_find_decoder(format->streams[stream]->codecpar->codec_id);
  108. if (codec == nullptr)
  109. {
  110. // Unsupported codec
  111. return false;
  112. }
  113. codecContext = avcodec_alloc_context3(codec);
  114. if(!codecContext)
  115. return false;
  116. // Get a pointer to the codec context for the video stream
  117. int ret = avcodec_parameters_to_context(codecContext, format->streams[stream]->codecpar);
  118. if (ret < 0)
  119. {
  120. //We cannot get codec from parameters
  121. avcodec_free_context(&codecContext);
  122. return false;
  123. }
  124. // Open codec
  125. if ( avcodec_open2(codecContext, codec, nullptr) < 0 )
  126. {
  127. // Could not open codec
  128. codec = nullptr;
  129. return false;
  130. }
  131. // Allocate video frame
  132. frame = av_frame_alloc();
  133. //setup scaling
  134. if(scale)
  135. {
  136. pos.w = screen->w;
  137. pos.h = screen->h;
  138. }
  139. else
  140. {
  141. pos.w = codecContext->width;
  142. pos.h = codecContext->height;
  143. }
  144. // Allocate a place to put our YUV image on that screen
  145. if (useOverlay)
  146. {
  147. texture = SDL_CreateTexture( mainRenderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STATIC, pos.w, pos.h);
  148. }
  149. else
  150. {
  151. dest = CSDL_Ext::newSurface(pos.w, pos.h);
  152. destRect.x = destRect.y = 0;
  153. destRect.w = pos.w;
  154. destRect.h = pos.h;
  155. }
  156. if (texture == nullptr && dest == nullptr)
  157. return false;
  158. if (texture)
  159. { // Convert the image into YUV format that SDL uses
  160. sws = sws_getContext(codecContext->width, codecContext->height, codecContext->pix_fmt,
  161. pos.w, pos.h,
  162. AV_PIX_FMT_YUV420P,
  163. SWS_BICUBIC, nullptr, nullptr, nullptr);
  164. }
  165. else
  166. {
  167. AVPixelFormat screenFormat = AV_PIX_FMT_NONE;
  168. if (screen->format->Bshift > screen->format->Rshift)
  169. {
  170. // this a BGR surface
  171. switch (screen->format->BytesPerPixel)
  172. {
  173. case 2: screenFormat = AV_PIX_FMT_BGR565; break;
  174. case 3: screenFormat = AV_PIX_FMT_BGR24; break;
  175. case 4: screenFormat = AV_PIX_FMT_BGR32; break;
  176. default: return false;
  177. }
  178. }
  179. else
  180. {
  181. // this a RGB surface
  182. switch (screen->format->BytesPerPixel)
  183. {
  184. case 2: screenFormat = AV_PIX_FMT_RGB565; break;
  185. case 3: screenFormat = AV_PIX_FMT_RGB24; break;
  186. case 4: screenFormat = AV_PIX_FMT_RGB32; break;
  187. default: return false;
  188. }
  189. }
  190. sws = sws_getContext(codecContext->width, codecContext->height, codecContext->pix_fmt,
  191. pos.w, pos.h, screenFormat,
  192. SWS_BICUBIC, nullptr, nullptr, nullptr);
  193. }
  194. if (sws == nullptr)
  195. return false;
  196. return true;
  197. }
  198. // Read the next frame. Return false on error/end of file.
  199. bool CVideoPlayer::nextFrame()
  200. {
  201. AVPacket packet;
  202. int frameFinished = 0;
  203. bool gotError = false;
  204. if (sws == nullptr)
  205. return false;
  206. while(!frameFinished)
  207. {
  208. int ret = av_read_frame(format, &packet);
  209. if (ret < 0)
  210. {
  211. // Error. It's probably an end of file.
  212. if (doLoop && !gotError)
  213. {
  214. // Rewind
  215. frameTime = 0;
  216. if (av_seek_frame(format, stream, 0, AVSEEK_FLAG_BYTE) < 0)
  217. break;
  218. gotError = true;
  219. }
  220. else
  221. {
  222. break;
  223. }
  224. }
  225. else
  226. {
  227. // Is this a packet from the video stream?
  228. if (packet.stream_index == stream)
  229. {
  230. // Decode video frame
  231. int rc = avcodec_send_packet(codecContext, &packet);
  232. if (rc >=0)
  233. packet.size = 0;
  234. rc = avcodec_receive_frame(codecContext, frame);
  235. if (rc >= 0)
  236. frameFinished = 1;
  237. // Did we get a video frame?
  238. if (frameFinished)
  239. {
  240. uint8_t *data[4];
  241. int linesize[4];
  242. if (texture) {
  243. av_image_alloc(data, linesize, pos.w, pos.h, AV_PIX_FMT_YUV420P, 1);
  244. sws_scale(sws, frame->data, frame->linesize,
  245. 0, codecContext->height, data, linesize);
  246. SDL_UpdateYUVTexture(texture, NULL, data[0], linesize[0],
  247. data[1], linesize[1],
  248. data[2], linesize[2]);
  249. av_freep(&data[0]);
  250. }
  251. else
  252. {
  253. /* Avoid buffer overflow caused by sws_scale():
  254. * http://trac.ffmpeg.org/ticket/9254
  255. * Currently (ffmpeg-4.4 with SSE3 enabled) sws_scale()
  256. * has a few requirements for target data buffers on rescaling:
  257. * 1. buffer has to be aligned to be usable for SIMD instructions
  258. * 2. buffer has to be padded to allow small overflow by SIMD instructions
  259. * Unfortunately SDL_Surface does not provide these guarantees.
  260. * This means that atempt to rescale directly into SDL surface causes
  261. * memory corruption. Usually it happens on campaign selection screen
  262. * where short video moves start spinning on mouse hover.
  263. *
  264. * To fix [1.] we use av_malloc() for memory allocation.
  265. * To fix [2.] we add an `ffmpeg_pad` that provides plenty of space.
  266. * We have to use intermdiate buffer and then use memcpy() to land it
  267. * to SDL_Surface.
  268. */
  269. size_t pic_bytes = dest->pitch * dest->h;
  270. size_t ffmped_pad = 1024; /* a few bytes of overflow will go here */
  271. void * for_sws = av_malloc (pic_bytes + ffmped_pad);
  272. data[0] = (ui8 *)for_sws;
  273. linesize[0] = dest->pitch;
  274. sws_scale(sws, frame->data, frame->linesize,
  275. 0, codecContext->height, data, linesize);
  276. memcpy(dest->pixels, for_sws, pic_bytes);
  277. av_free(for_sws);
  278. }
  279. }
  280. }
  281. av_packet_unref(&packet);
  282. }
  283. }
  284. return frameFinished != 0;
  285. }
  286. void CVideoPlayer::show( int x, int y, SDL_Surface *dst, bool update )
  287. {
  288. if (sws == nullptr)
  289. return;
  290. pos.x = x;
  291. pos.y = y;
  292. CSDL_Ext::blitSurface(dest, destRect, dst, pos.topLeft());
  293. if (update)
  294. CSDL_Ext::updateRect(dst, pos);
  295. }
  296. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  297. {
  298. show(x, y, dst, update);
  299. }
  300. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  301. {
  302. if (sws == nullptr)
  303. return;
  304. #if (LIBAVUTIL_VERSION_MAJOR < 58)
  305. auto packet_duration = frame->pkt_duration;
  306. #else
  307. auto packet_duration = frame->duration;
  308. #endif
  309. double frameEndTime = (frame->pts + packet_duration) * av_q2d(format->streams[stream]->time_base);
  310. frameTime += GH.framerate().getElapsedMilliseconds() / 1000.0;
  311. if (frameTime >= frameEndTime )
  312. {
  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. }
  330. void CVideoPlayer::close()
  331. {
  332. fname = VideoPath();
  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. frameTime = 0.0;
  380. while(nextFrame())
  381. {
  382. if(stopOnKey)
  383. {
  384. GH.input().fetchEvents();
  385. if(GH.input().ignoreEventsUntilInput())
  386. return false;
  387. }
  388. SDL_Rect rect = CSDL_Ext::toSDL(pos);
  389. SDL_RenderCopy(mainRenderer, texture, nullptr, &rect);
  390. SDL_RenderPresent(mainRenderer);
  391. #if (LIBAVUTIL_VERSION_MAJOR < 58)
  392. auto packet_duration = frame->pkt_duration;
  393. #else
  394. auto packet_duration = frame->duration;
  395. #endif
  396. double frameDurationSec = packet_duration * av_q2d(format->streams[stream]->time_base);
  397. uint32_t timeToSleepMillisec = 1000 * (frameDurationSec);
  398. boost::this_thread::sleep_for(boost::chrono::milliseconds(timeToSleepMillisec));
  399. }
  400. return true;
  401. }
  402. bool CVideoPlayer::openAndPlayVideo(const VideoPath & name, int x, int y, bool stopOnKey, bool scale)
  403. {
  404. open(name, false, true, scale);
  405. bool ret = playVideo(x, y, stopOnKey);
  406. close();
  407. return ret;
  408. }
  409. CVideoPlayer::~CVideoPlayer()
  410. {
  411. close();
  412. }
  413. #endif