CVideoHandler.cpp 12 KB

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