CVideoHandler.cpp 11 KB

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