CVideoHandler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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. // Find the first audio stream
  108. streamAudio = -1;
  109. for(ui32 i=0; i<format->nb_streams; i++)
  110. {
  111. if (format->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  112. {
  113. streamAudio = i;
  114. break;
  115. }
  116. }
  117. if (stream < 0)
  118. // No video stream in that file
  119. return false;
  120. // Find the decoder for the video stream
  121. codec = avcodec_find_decoder(format->streams[stream]->codecpar->codec_id);
  122. if(streamAudio > -1)
  123. {
  124. // Find the decoder for the audio stream
  125. codecAudio = avcodec_find_decoder(format->streams[streamAudio]->codecpar->codec_id);
  126. }
  127. if (codec == nullptr)
  128. {
  129. // Unsupported codec
  130. return false;
  131. }
  132. codecContext = avcodec_alloc_context3(codec);
  133. if(!codecContext)
  134. return false;
  135. if (codecAudio != nullptr)
  136. codecContextAudio = avcodec_alloc_context3(codecAudio);
  137. // Get a pointer to the codec context for the video stream
  138. int ret = avcodec_parameters_to_context(codecContext, format->streams[stream]->codecpar);
  139. if (ret < 0)
  140. {
  141. //We cannot get codec from parameters
  142. avcodec_free_context(&codecContext);
  143. return false;
  144. }
  145. // Get a pointer to the codec context for the audio stream
  146. if (streamAudio > -1)
  147. {
  148. ret = avcodec_parameters_to_context(codecContextAudio, format->streams[streamAudio]->codecpar);
  149. if (ret < 0)
  150. {
  151. //We cannot get codec from parameters
  152. avcodec_free_context(&codecContextAudio);
  153. }
  154. }
  155. // Open codec
  156. if ( avcodec_open2(codecContext, codec, nullptr) < 0 )
  157. {
  158. // Could not open codec
  159. codec = nullptr;
  160. return false;
  161. }
  162. // Allocate video frame
  163. frame = av_frame_alloc();
  164. // Open codec
  165. if (codecAudio != nullptr)
  166. {
  167. if ( avcodec_open2(codecContextAudio, codecAudio, nullptr) < 0 )
  168. {
  169. // Could not open codec
  170. codecAudio = nullptr;
  171. }
  172. // Allocate audio frame
  173. frameAudio = av_frame_alloc();
  174. }
  175. //setup scaling
  176. if(scale)
  177. {
  178. pos.w = screen->w;
  179. pos.h = screen->h;
  180. }
  181. else
  182. {
  183. pos.w = codecContext->width;
  184. pos.h = codecContext->height;
  185. }
  186. // Allocate a place to put our YUV image on that screen
  187. if (useOverlay)
  188. {
  189. texture = SDL_CreateTexture( mainRenderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STATIC, pos.w, pos.h);
  190. }
  191. else
  192. {
  193. dest = CSDL_Ext::newSurface(pos.w, pos.h);
  194. destRect.x = destRect.y = 0;
  195. destRect.w = pos.w;
  196. destRect.h = pos.h;
  197. }
  198. if (texture == nullptr && dest == nullptr)
  199. return false;
  200. if (texture)
  201. { // Convert the image into YUV format that SDL uses
  202. sws = sws_getContext(codecContext->width, codecContext->height, codecContext->pix_fmt,
  203. pos.w, pos.h,
  204. AV_PIX_FMT_YUV420P,
  205. SWS_BICUBIC, nullptr, nullptr, nullptr);
  206. }
  207. else
  208. {
  209. AVPixelFormat screenFormat = AV_PIX_FMT_NONE;
  210. if (screen->format->Bshift > screen->format->Rshift)
  211. {
  212. // this a BGR surface
  213. switch (screen->format->BytesPerPixel)
  214. {
  215. case 2: screenFormat = AV_PIX_FMT_BGR565; break;
  216. case 3: screenFormat = AV_PIX_FMT_BGR24; break;
  217. case 4: screenFormat = AV_PIX_FMT_BGR32; break;
  218. default: return false;
  219. }
  220. }
  221. else
  222. {
  223. // this a RGB surface
  224. switch (screen->format->BytesPerPixel)
  225. {
  226. case 2: screenFormat = AV_PIX_FMT_RGB565; break;
  227. case 3: screenFormat = AV_PIX_FMT_RGB24; break;
  228. case 4: screenFormat = AV_PIX_FMT_RGB32; break;
  229. default: return false;
  230. }
  231. }
  232. sws = sws_getContext(codecContext->width, codecContext->height, codecContext->pix_fmt,
  233. pos.w, pos.h, screenFormat,
  234. SWS_BICUBIC, nullptr, nullptr, nullptr);
  235. }
  236. if (sws == nullptr)
  237. return false;
  238. playVideoAudio();
  239. return true;
  240. }
  241. // Read the next frame. Return false on error/end of file.
  242. bool CVideoPlayer::nextFrame()
  243. {
  244. AVPacket packet;
  245. int frameFinished = 0;
  246. bool gotError = false;
  247. if (sws == nullptr)
  248. return false;
  249. while(!frameFinished)
  250. {
  251. int ret = av_read_frame(format, &packet);
  252. if (ret < 0)
  253. {
  254. // Error. It's probably an end of file.
  255. if (doLoop && !gotError)
  256. {
  257. // Rewind
  258. frameTime = 0;
  259. if (av_seek_frame(format, stream, 0, AVSEEK_FLAG_BYTE) < 0)
  260. break;
  261. gotError = true;
  262. }
  263. else
  264. {
  265. break;
  266. }
  267. }
  268. else
  269. {
  270. // Is this a packet from the video stream?
  271. if (packet.stream_index == stream)
  272. {
  273. // Decode video frame
  274. int rc = avcodec_send_packet(codecContext, &packet);
  275. if (rc >=0)
  276. packet.size = 0;
  277. rc = avcodec_receive_frame(codecContext, frame);
  278. if (rc >= 0)
  279. frameFinished = 1;
  280. // Did we get a video frame?
  281. if (frameFinished)
  282. {
  283. uint8_t *data[4];
  284. int linesize[4];
  285. if (texture) {
  286. av_image_alloc(data, linesize, pos.w, pos.h, AV_PIX_FMT_YUV420P, 1);
  287. sws_scale(sws, frame->data, frame->linesize,
  288. 0, codecContext->height, data, linesize);
  289. SDL_UpdateYUVTexture(texture, NULL, data[0], linesize[0],
  290. data[1], linesize[1],
  291. data[2], linesize[2]);
  292. av_freep(&data[0]);
  293. }
  294. else
  295. {
  296. /* Avoid buffer overflow caused by sws_scale():
  297. * http://trac.ffmpeg.org/ticket/9254
  298. * Currently (ffmpeg-4.4 with SSE3 enabled) sws_scale()
  299. * has a few requirements for target data buffers on rescaling:
  300. * 1. buffer has to be aligned to be usable for SIMD instructions
  301. * 2. buffer has to be padded to allow small overflow by SIMD instructions
  302. * Unfortunately SDL_Surface does not provide these guarantees.
  303. * This means that atempt to rescale directly into SDL surface causes
  304. * memory corruption. Usually it happens on campaign selection screen
  305. * where short video moves start spinning on mouse hover.
  306. *
  307. * To fix [1.] we use av_malloc() for memory allocation.
  308. * To fix [2.] we add an `ffmpeg_pad` that provides plenty of space.
  309. * We have to use intermdiate buffer and then use memcpy() to land it
  310. * to SDL_Surface.
  311. */
  312. size_t pic_bytes = dest->pitch * dest->h;
  313. size_t ffmped_pad = 1024; /* a few bytes of overflow will go here */
  314. void * for_sws = av_malloc (pic_bytes + ffmped_pad);
  315. data[0] = (ui8 *)for_sws;
  316. linesize[0] = dest->pitch;
  317. sws_scale(sws, frame->data, frame->linesize,
  318. 0, codecContext->height, data, linesize);
  319. memcpy(dest->pixels, for_sws, pic_bytes);
  320. av_free(for_sws);
  321. }
  322. }
  323. }
  324. av_packet_unref(&packet);
  325. }
  326. }
  327. return frameFinished != 0;
  328. }
  329. void CVideoPlayer::show( int x, int y, SDL_Surface *dst, bool update )
  330. {
  331. if (sws == nullptr)
  332. return;
  333. pos.x = x;
  334. pos.y = y;
  335. CSDL_Ext::blitSurface(dest, destRect, dst, pos.topLeft());
  336. if (update)
  337. CSDL_Ext::updateRect(dst, pos);
  338. }
  339. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  340. {
  341. show(x, y, dst, update);
  342. }
  343. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update, std::function<void()> onVideoRestart)
  344. {
  345. if (sws == nullptr)
  346. return;
  347. #if (LIBAVUTIL_VERSION_MAJOR < 58)
  348. auto packet_duration = frame->pkt_duration;
  349. #else
  350. auto packet_duration = frame->duration;
  351. #endif
  352. double frameEndTime = (frame->pts + packet_duration) * av_q2d(format->streams[stream]->time_base);
  353. frameTime += GH.framerate().getElapsedMilliseconds() / 1000.0;
  354. if (frameTime >= frameEndTime )
  355. {
  356. if (nextFrame())
  357. show(x,y,dst,update);
  358. else
  359. {
  360. if(onVideoRestart)
  361. onVideoRestart();
  362. VideoPath filenameToReopen = fname; // create copy to backup this->fname
  363. open(filenameToReopen);
  364. nextFrame();
  365. // The y position is wrong at the first frame.
  366. // Note: either the windows player or the linux player is
  367. // broken. Compensate here until the bug is found.
  368. show(x, y--, dst, update);
  369. }
  370. }
  371. else
  372. {
  373. redraw(x, y, dst, update);
  374. }
  375. }
  376. void CVideoPlayer::close()
  377. {
  378. fname = VideoPath();
  379. if (sws)
  380. {
  381. sws_freeContext(sws);
  382. sws = nullptr;
  383. }
  384. if (texture)
  385. {
  386. SDL_DestroyTexture(texture);
  387. texture = nullptr;
  388. }
  389. if (dest)
  390. {
  391. SDL_FreeSurface(dest);
  392. dest = nullptr;
  393. }
  394. if (frame)
  395. {
  396. av_frame_free(&frame);//will be set to null
  397. }
  398. if (codec)
  399. {
  400. avcodec_close(codecContext);
  401. codec = nullptr;
  402. }
  403. if (codecContext)
  404. {
  405. avcodec_free_context(&codecContext);
  406. }
  407. if (format)
  408. {
  409. avformat_close_input(&format);
  410. }
  411. if (context)
  412. {
  413. av_free(context);
  414. context = nullptr;
  415. }
  416. }
  417. void CVideoPlayer::playVideoAudio()
  418. {
  419. AVPacket packet;
  420. std::pair<std::unique_ptr<ui8 []>, si64> data;
  421. std::vector<double> samples;
  422. while (av_read_frame(format, &packet) >= 0)
  423. {
  424. avcodec_send_packet(codecContextAudio, &packet);
  425. avcodec_receive_frame(codecContextAudio, frameAudio);
  426. data.second = frameAudio->linesize[0];
  427. data.first = (new ui8[data.second]);
  428. for (int s = 0; s < frameAudio->linesize[0]; s+=sizeof(ui8))
  429. {
  430. ui8 value;
  431. memcpy(&value, &frameAudio->data[0][s], sizeof(ui8));
  432. samples.push_back(value);
  433. data.first.
  434. }
  435. }
  436. }
  437. // Plays a video. Only works for overlays.
  438. bool CVideoPlayer::playVideo(int x, int y, bool stopOnKey)
  439. {
  440. // Note: either the windows player or the linux player is
  441. // broken. Compensate here until the bug is found.
  442. y--;
  443. pos.x = x;
  444. pos.y = y;
  445. frameTime = 0.0;
  446. while(nextFrame())
  447. {
  448. if(stopOnKey)
  449. {
  450. GH.input().fetchEvents();
  451. if(GH.input().ignoreEventsUntilInput())
  452. return false;
  453. }
  454. SDL_Rect rect = CSDL_Ext::toSDL(pos);
  455. SDL_RenderCopy(mainRenderer, texture, nullptr, &rect);
  456. SDL_RenderPresent(mainRenderer);
  457. #if (LIBAVUTIL_VERSION_MAJOR < 58)
  458. auto packet_duration = frame->pkt_duration;
  459. #else
  460. auto packet_duration = frame->duration;
  461. #endif
  462. double frameDurationSec = packet_duration * av_q2d(format->streams[stream]->time_base);
  463. uint32_t timeToSleepMillisec = 1000 * (frameDurationSec);
  464. boost::this_thread::sleep_for(boost::chrono::milliseconds(timeToSleepMillisec));
  465. }
  466. return true;
  467. }
  468. bool CVideoPlayer::openAndPlayVideo(const VideoPath & name, int x, int y, bool stopOnKey, bool scale)
  469. {
  470. open(name, false, true, scale);
  471. bool ret = playVideo(x, y, stopOnKey);
  472. close();
  473. return ret;
  474. }
  475. CVideoPlayer::~CVideoPlayer()
  476. {
  477. close();
  478. }
  479. #endif