CVideoHandler.cpp 11 KB

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