CVideoHandler.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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. #ifndef DISABLE_VIDEO
  13. #include "ISoundPlayer.h"
  14. #include "../CGameInfo.h"
  15. #include "../CMT.h"
  16. #include "../eventsSDL/InputHandler.h"
  17. #include "../gui/CGuiHandler.h"
  18. #include "../render/Canvas.h"
  19. #include "../render/IScreenHandler.h"
  20. #include "../renderSDL/SDL_Extensions.h"
  21. #include "../../lib/filesystem/CInputStream.h"
  22. #include "../../lib/filesystem/Filesystem.h"
  23. #include "../../lib/texts/CGeneralTextHandler.h"
  24. #include "../../lib/texts/Languages.h"
  25. #include <SDL_render.h>
  26. extern "C" {
  27. #include <libavformat/avformat.h>
  28. #include <libavcodec/avcodec.h>
  29. #include <libavutil/imgutils.h>
  30. #include <libswscale/swscale.h>
  31. }
  32. // Define a set of functions to read data
  33. static int lodRead(void * opaque, uint8_t * buf, int size)
  34. {
  35. auto * data = static_cast<CInputStream *>(opaque);
  36. auto bytesRead = data->read(buf, size);
  37. if(bytesRead == 0)
  38. return AVERROR_EOF;
  39. return bytesRead;
  40. }
  41. static si64 lodSeek(void * opaque, si64 pos, int whence)
  42. {
  43. auto * data = static_cast<CInputStream *>(opaque);
  44. if(whence & AVSEEK_SIZE)
  45. return data->getSize();
  46. return data->seek(pos);
  47. }
  48. [[noreturn]] static void throwFFmpegError(int errorCode)
  49. {
  50. std::array<char, AV_ERROR_MAX_STRING_SIZE> errorMessage{};
  51. av_strerror(errorCode, errorMessage.data(), errorMessage.size());
  52. throw std::runtime_error(errorMessage.data());
  53. }
  54. static std::unique_ptr<CInputStream> findVideoData(const VideoPath & videoToOpen)
  55. {
  56. if(CResourceHandler::get()->existsResource(videoToOpen))
  57. return CResourceHandler::get()->load(videoToOpen);
  58. auto highQualityVideoToOpenWithDir = videoToOpen.addPrefix("VIDEO/");
  59. auto lowQualityVideo = videoToOpen.toType<EResType::VIDEO_LOW_QUALITY>();
  60. auto lowQualityVideoWithDir = highQualityVideoToOpenWithDir.toType<EResType::VIDEO_LOW_QUALITY>();
  61. if(CResourceHandler::get()->existsResource(highQualityVideoToOpenWithDir))
  62. return CResourceHandler::get()->load(highQualityVideoToOpenWithDir);
  63. if(CResourceHandler::get()->existsResource(lowQualityVideo))
  64. return CResourceHandler::get()->load(lowQualityVideo);
  65. if(CResourceHandler::get()->existsResource(lowQualityVideoWithDir))
  66. return CResourceHandler::get()->load(lowQualityVideoWithDir);
  67. return nullptr;
  68. }
  69. bool FFMpegStream::openInput(const VideoPath & videoToOpen)
  70. {
  71. input = findVideoData(videoToOpen);
  72. return input != nullptr;
  73. }
  74. void FFMpegStream::openContext()
  75. {
  76. static const int BUFFER_SIZE = 4096;
  77. input->seek(0);
  78. auto * buffer = static_cast<unsigned char *>(av_malloc(BUFFER_SIZE)); // will be freed by ffmpeg
  79. context = avio_alloc_context(buffer, BUFFER_SIZE, 0, input.get(), lodRead, nullptr, lodSeek);
  80. formatContext = avformat_alloc_context();
  81. formatContext->pb = context;
  82. // filename is not needed - file was already open and stored in this->data;
  83. int avfopen = avformat_open_input(&formatContext, "dummyFilename", nullptr, nullptr);
  84. if(avfopen != 0)
  85. throwFFmpegError(avfopen);
  86. // Retrieve stream information
  87. int findStreamInfo = avformat_find_stream_info(formatContext, nullptr);
  88. if(avfopen < 0)
  89. throwFFmpegError(findStreamInfo);
  90. }
  91. void FFMpegStream::openCodec(int desiredStreamIndex)
  92. {
  93. streamIndex = desiredStreamIndex;
  94. // Find the decoder for the stream
  95. codec = avcodec_find_decoder(formatContext->streams[streamIndex]->codecpar->codec_id);
  96. if(codec == nullptr)
  97. throw std::runtime_error("Unsupported codec");
  98. codecContext = avcodec_alloc_context3(codec);
  99. if(codecContext == nullptr)
  100. throw std::runtime_error("Failed to create codec context");
  101. // Get a pointer to the codec context for the video stream
  102. int ret = avcodec_parameters_to_context(codecContext, formatContext->streams[streamIndex]->codecpar);
  103. if(ret < 0)
  104. {
  105. //We cannot get codec from parameters
  106. avcodec_free_context(&codecContext);
  107. throwFFmpegError(ret);
  108. }
  109. // Open codec
  110. ret = avcodec_open2(codecContext, codec, nullptr);
  111. if(ret < 0)
  112. {
  113. // Could not open codec
  114. codec = nullptr;
  115. throwFFmpegError(ret);
  116. }
  117. // Allocate video frame
  118. frame = av_frame_alloc();
  119. }
  120. const AVCodecParameters * FFMpegStream::getCodecParameters() const
  121. {
  122. return formatContext->streams[streamIndex]->codecpar;
  123. }
  124. const AVCodecContext * FFMpegStream::getCodecContext() const
  125. {
  126. return codecContext;
  127. }
  128. const AVFrame * FFMpegStream::getCurrentFrame() const
  129. {
  130. return frame;
  131. }
  132. void CVideoInstance::openVideo()
  133. {
  134. openContext();
  135. openCodec(findVideoStream());
  136. }
  137. void CVideoInstance::prepareOutput(float scaleFactor, bool useTextureOutput)
  138. {
  139. //setup scaling
  140. dimensions = Point(getCodecContext()->width * scaleFactor, getCodecContext()->height * scaleFactor) * GH.screenHandler().getScalingFactor();
  141. // Allocate a place to put our YUV image on that screen
  142. if (useTextureOutput)
  143. {
  144. std::array potentialFormats = {
  145. AV_PIX_FMT_YUV420P, // -> SDL_PIXELFORMAT_IYUV - most of H3 videos use YUV format, so it is preferred to save some space & conversion time
  146. AV_PIX_FMT_RGB32, // -> SDL_PIXELFORMAT_ARGB8888 - some .smk videos actually use palette, so RGB > YUV. This is also our screen texture format
  147. AV_PIX_FMT_NONE
  148. };
  149. auto preferredFormat = avcodec_find_best_pix_fmt_of_list(potentialFormats.data(), getCodecContext()->pix_fmt, false, nullptr);
  150. if (preferredFormat == AV_PIX_FMT_YUV420P)
  151. textureYUV = SDL_CreateTexture( mainRenderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING, dimensions.x, dimensions.y);
  152. else
  153. textureRGB = SDL_CreateTexture( mainRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, dimensions.x, dimensions.y);
  154. sws = sws_getContext(getCodecContext()->width, getCodecContext()->height, getCodecContext()->pix_fmt,
  155. dimensions.x, dimensions.y, preferredFormat,
  156. SWS_BICUBIC, nullptr, nullptr, nullptr);
  157. }
  158. else
  159. {
  160. surface = CSDL_Ext::newSurface(dimensions);
  161. sws = sws_getContext(getCodecContext()->width, getCodecContext()->height, getCodecContext()->pix_fmt,
  162. dimensions.x, dimensions.y, AV_PIX_FMT_RGB32,
  163. SWS_BICUBIC, nullptr, nullptr, nullptr);
  164. }
  165. if (sws == nullptr)
  166. throw std::runtime_error("Failed to create sws");
  167. }
  168. void FFMpegStream::decodeNextFrame()
  169. {
  170. int rc = avcodec_receive_frame(codecContext, frame);
  171. // frame extracted - data that was sent to codecContext before was sufficient
  172. if (rc == 0)
  173. return;
  174. // returning AVERROR(EAGAIN) is legal - this indicates that codec requires more data from input stream to decode next frame
  175. if(rc != AVERROR(EAGAIN))
  176. throwFFmpegError(rc);
  177. for(;;)
  178. {
  179. AVPacket packet;
  180. // codecContext does not have enough input data - read next packet from input stream
  181. int ret = av_read_frame(formatContext, &packet);
  182. if(ret < 0)
  183. {
  184. if(ret == AVERROR_EOF)
  185. {
  186. av_packet_unref(&packet);
  187. av_frame_free(&frame);
  188. frame = nullptr;
  189. return;
  190. }
  191. throwFFmpegError(ret);
  192. }
  193. // Is this a packet from the stream that needs decoding?
  194. if(packet.stream_index == streamIndex)
  195. {
  196. // Decode read packet
  197. // Note: this method may return AVERROR(EAGAIN). However this should never happen with ffmpeg API
  198. // since there is guaranteed call to avcodec_receive_frame and ffmpeg API promises that *both* of these methods will never return AVERROR(EAGAIN).
  199. int rc = avcodec_send_packet(codecContext, &packet);
  200. if(rc < 0)
  201. throwFFmpegError(rc);
  202. rc = avcodec_receive_frame(codecContext, frame);
  203. if(rc == AVERROR(EAGAIN))
  204. {
  205. // still need more data - read next packet
  206. av_packet_unref(&packet);
  207. continue;
  208. }
  209. else if(rc < 0)
  210. {
  211. throwFFmpegError(rc);
  212. }
  213. else
  214. {
  215. // read succesful. Exit the loop
  216. av_packet_unref(&packet);
  217. return;
  218. }
  219. }
  220. av_packet_unref(&packet);
  221. }
  222. }
  223. bool CVideoInstance::loadNextFrame()
  224. {
  225. decodeNextFrame();
  226. const AVFrame * frame = getCurrentFrame();
  227. if(!frame)
  228. return false;
  229. uint8_t * data[4] = {};
  230. int linesize[4] = {};
  231. if(textureYUV)
  232. {
  233. av_image_alloc(data, linesize, dimensions.x, dimensions.y, AV_PIX_FMT_YUV420P, 1);
  234. sws_scale(sws, frame->data, frame->linesize, 0, getCodecContext()->height, data, linesize);
  235. SDL_UpdateYUVTexture(textureYUV, nullptr, data[0], linesize[0], data[1], linesize[1], data[2], linesize[2]);
  236. av_freep(&data[0]);
  237. }
  238. if(textureRGB)
  239. {
  240. av_image_alloc(data, linesize, dimensions.x, dimensions.y, AV_PIX_FMT_RGB32, 1);
  241. sws_scale(sws, frame->data, frame->linesize, 0, getCodecContext()->height, data, linesize);
  242. SDL_UpdateTexture(textureRGB, nullptr, data[0], linesize[0]);
  243. av_freep(&data[0]);
  244. }
  245. if(surface)
  246. {
  247. // Avoid buffer overflow caused by sws_scale():
  248. // http://trac.ffmpeg.org/ticket/9254
  249. size_t pic_bytes = surface->pitch * surface->h;
  250. size_t ffmped_pad = 1024; /* a few bytes of overflow will go here */
  251. void * for_sws = av_malloc(pic_bytes + ffmped_pad);
  252. data[0] = (ui8 *)for_sws;
  253. linesize[0] = surface->pitch;
  254. sws_scale(sws, frame->data, frame->linesize, 0, getCodecContext()->height, data, linesize);
  255. memcpy(surface->pixels, for_sws, pic_bytes);
  256. av_free(for_sws);
  257. }
  258. return true;
  259. }
  260. bool CVideoInstance::videoEnded()
  261. {
  262. return getCurrentFrame() == nullptr;
  263. }
  264. CVideoInstance::~CVideoInstance()
  265. {
  266. sws_freeContext(sws);
  267. SDL_DestroyTexture(textureYUV);
  268. SDL_DestroyTexture(textureRGB);
  269. SDL_FreeSurface(surface);
  270. }
  271. FFMpegStream::~FFMpegStream()
  272. {
  273. av_frame_free(&frame);
  274. #if (LIBAVCODEC_VERSION_MAJOR < 61 )
  275. // deprecated, apparently no longer necessary - avcodec_free_context should suffice
  276. avcodec_close(codecContext);
  277. #endif
  278. avcodec_free_context(&codecContext);
  279. avformat_close_input(&formatContext);
  280. av_free(context);
  281. }
  282. Point CVideoInstance::size()
  283. {
  284. return dimensions / GH.screenHandler().getScalingFactor();
  285. }
  286. void CVideoInstance::show(const Point & position, Canvas & canvas)
  287. {
  288. if(sws == nullptr)
  289. throw std::runtime_error("No video to show!");
  290. CSDL_Ext::blitSurface(surface, canvas.getInternalSurface(), position * GH.screenHandler().getScalingFactor());
  291. }
  292. double FFMpegStream::getCurrentFrameEndTime() const
  293. {
  294. #if(LIBAVUTIL_VERSION_MAJOR < 58)
  295. auto packet_duration = frame->pkt_duration;
  296. #else
  297. auto packet_duration = frame->duration;
  298. #endif
  299. return (frame->pts + packet_duration) * av_q2d(formatContext->streams[streamIndex]->time_base);
  300. }
  301. double FFMpegStream::getCurrentFrameDuration() const
  302. {
  303. #if(LIBAVUTIL_VERSION_MAJOR < 58)
  304. auto packet_duration = frame->pkt_duration;
  305. #else
  306. auto packet_duration = frame->duration;
  307. #endif
  308. return packet_duration * av_q2d(formatContext->streams[streamIndex]->time_base);
  309. }
  310. void CVideoInstance::tick(uint32_t msPassed)
  311. {
  312. if(sws == nullptr)
  313. throw std::runtime_error("No video to show!");
  314. if(videoEnded())
  315. throw std::runtime_error("Video already ended!");
  316. frameTime += msPassed / 1000.0;
  317. if(frameTime >= getCurrentFrameEndTime())
  318. loadNextFrame();
  319. }
  320. struct FFMpegFormatDescription
  321. {
  322. uint8_t sampleSizeBytes;
  323. uint8_t wavFormatID;
  324. bool isPlanar;
  325. };
  326. static FFMpegFormatDescription getAudioFormatProperties(int audioFormat)
  327. {
  328. switch (audioFormat)
  329. {
  330. case AV_SAMPLE_FMT_U8: return { 1, 1, false};
  331. case AV_SAMPLE_FMT_U8P: return { 1, 1, true};
  332. case AV_SAMPLE_FMT_S16: return { 2, 1, false};
  333. case AV_SAMPLE_FMT_S16P: return { 2, 1, true};
  334. case AV_SAMPLE_FMT_S32: return { 4, 1, false};
  335. case AV_SAMPLE_FMT_S32P: return { 4, 1, true};
  336. case AV_SAMPLE_FMT_S64: return { 8, 1, false};
  337. case AV_SAMPLE_FMT_S64P: return { 8, 1, true};
  338. case AV_SAMPLE_FMT_FLT: return { 4, 3, false};
  339. case AV_SAMPLE_FMT_FLTP: return { 4, 3, true};
  340. case AV_SAMPLE_FMT_DBL: return { 8, 3, false};
  341. case AV_SAMPLE_FMT_DBLP: return { 8, 3, true};
  342. }
  343. throw std::runtime_error("Invalid audio format");
  344. }
  345. int FFMpegStream::findAudioStream() const
  346. {
  347. std::vector<int> audioStreamIndices;
  348. for(int i = 0; i < formatContext->nb_streams; i++)
  349. if(formatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  350. audioStreamIndices.push_back(i);
  351. if (audioStreamIndices.empty())
  352. return -1;
  353. if (audioStreamIndices.size() == 1)
  354. return audioStreamIndices.front();
  355. // multiple audio streams - try to pick best one based on language settings
  356. std::map<int, std::string> streamToLanguage;
  357. // Approach 1 - check if stream has language set in metadata
  358. for (auto const & index : audioStreamIndices)
  359. {
  360. const AVDictionaryEntry *e = av_dict_get(formatContext->streams[index]->metadata, "language", nullptr, 0);
  361. if (e)
  362. streamToLanguage[index] = e->value;
  363. }
  364. // Approach 2 - no metadata found. This may be video from Chronicles which have predefined (presumably hardcoded) list of languages
  365. if (streamToLanguage.empty())
  366. {
  367. if (audioStreamIndices.size() == 2)
  368. {
  369. streamToLanguage[audioStreamIndices[0]] = Languages::getLanguageOptions(Languages::ELanguages::ENGLISH).tagISO2;
  370. streamToLanguage[audioStreamIndices[1]] = Languages::getLanguageOptions(Languages::ELanguages::GERMAN).tagISO2;
  371. }
  372. if (audioStreamIndices.size() == 5)
  373. {
  374. streamToLanguage[audioStreamIndices[0]] = Languages::getLanguageOptions(Languages::ELanguages::ENGLISH).tagISO2;
  375. streamToLanguage[audioStreamIndices[1]] = Languages::getLanguageOptions(Languages::ELanguages::FRENCH).tagISO2;
  376. streamToLanguage[audioStreamIndices[2]] = Languages::getLanguageOptions(Languages::ELanguages::GERMAN).tagISO2;
  377. streamToLanguage[audioStreamIndices[3]] = Languages::getLanguageOptions(Languages::ELanguages::ITALIAN).tagISO2;
  378. streamToLanguage[audioStreamIndices[4]] = Languages::getLanguageOptions(Languages::ELanguages::SPANISH).tagISO2;
  379. }
  380. }
  381. std::string preferredLanguageName = CGI->generaltexth->getPreferredLanguage();
  382. std::string preferredTag = Languages::getLanguageOptions(preferredLanguageName).tagISO2;
  383. for (auto const & entry : streamToLanguage)
  384. if (entry.second == preferredTag)
  385. return entry.first;
  386. return audioStreamIndices.front();
  387. }
  388. int FFMpegStream::findVideoStream() const
  389. {
  390. for(int i = 0; i < formatContext->nb_streams; i++)
  391. if(formatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  392. return i;
  393. return -1;
  394. }
  395. std::pair<std::unique_ptr<ui8 []>, si64> CAudioInstance::extractAudio(const VideoPath & videoToOpen)
  396. {
  397. if (!openInput(videoToOpen))
  398. return { nullptr, 0};
  399. openContext();
  400. int audioStreamIndex = findAudioStream();
  401. if (audioStreamIndex == -1)
  402. return { nullptr, 0};
  403. openCodec(audioStreamIndex);
  404. const auto * codecpar = getCodecParameters();
  405. std::vector<ui8> samples;
  406. auto formatProperties = getAudioFormatProperties(codecpar->format);
  407. #if(LIBAVUTIL_VERSION_MAJOR < 58)
  408. int numChannels = codecpar->channels;
  409. #else
  410. int numChannels = codecpar->ch_layout.nb_channels;
  411. #endif
  412. samples.reserve(44100 * 5); // arbitrary 5-second buffer
  413. for (;;)
  414. {
  415. decodeNextFrame();
  416. const AVFrame * frame = getCurrentFrame();
  417. if (!frame)
  418. break;
  419. int samplesToRead = frame->nb_samples * numChannels;
  420. int bytesToRead = samplesToRead * formatProperties.sampleSizeBytes;
  421. if (formatProperties.isPlanar && numChannels > 1)
  422. {
  423. // Workaround for lack of resampler
  424. // Currently, ffmpeg on conan systems is built without sws resampler
  425. // Because of that, and because wav format does not supports 'planar' formats from ffmpeg
  426. // we need to de-planarize it and convert to "normal" (non-planar / interleaved) stream
  427. samples.reserve(samples.size() + bytesToRead);
  428. for (int sm = 0; sm < frame->nb_samples; ++sm)
  429. for (int ch = 0; ch < numChannels; ++ch)
  430. samples.insert(samples.end(), frame->data[ch] + sm * formatProperties.sampleSizeBytes, frame->data[ch] + (sm+1) * formatProperties.sampleSizeBytes );
  431. }
  432. else
  433. {
  434. samples.insert(samples.end(), frame->data[0], frame->data[0] + bytesToRead);
  435. }
  436. }
  437. struct WavHeader {
  438. ui8 RIFF[4] = {'R', 'I', 'F', 'F'};
  439. ui32 ChunkSize;
  440. ui8 WAVE[4] = {'W', 'A', 'V', 'E'};
  441. ui8 fmt[4] = {'f', 'm', 't', ' '};
  442. ui32 Subchunk1Size = 16;
  443. ui16 AudioFormat = 1;
  444. ui16 NumOfChan = 2;
  445. ui32 SamplesPerSec = 22050;
  446. ui32 bytesPerSec = 22050 * 2;
  447. ui16 blockAlign = 1;
  448. ui16 bitsPerSample = 32;
  449. ui8 Subchunk2ID[4] = {'d', 'a', 't', 'a'};
  450. ui32 Subchunk2Size;
  451. };
  452. WavHeader wav;
  453. wav.ChunkSize = samples.size() + sizeof(WavHeader) - 8;
  454. wav.AudioFormat = formatProperties.wavFormatID; // 1 = PCM, 3 = IEEE float
  455. wav.NumOfChan = numChannels;
  456. wav.SamplesPerSec = codecpar->sample_rate;
  457. wav.bytesPerSec = codecpar->sample_rate * formatProperties.sampleSizeBytes;
  458. wav.bitsPerSample = formatProperties.sampleSizeBytes * 8;
  459. wav.Subchunk2Size = samples.size() + sizeof(WavHeader) - 44;
  460. auto * wavPtr = reinterpret_cast<ui8*>(&wav);
  461. auto dat = std::make_pair(std::make_unique<ui8[]>(samples.size() + sizeof(WavHeader)), samples.size() + sizeof(WavHeader));
  462. std::copy(wavPtr, wavPtr + sizeof(WavHeader), dat.first.get());
  463. std::copy(samples.begin(), samples.end(), dat.first.get() + sizeof(WavHeader));
  464. return dat;
  465. }
  466. bool CVideoPlayer::openAndPlayVideoImpl(const VideoPath & name, const Point & position, bool useOverlay, bool stopOnKey)
  467. {
  468. CVideoInstance instance;
  469. CAudioInstance audio;
  470. auto extractedAudio = audio.extractAudio(name);
  471. int audioHandle = CCS->soundh->playSound(extractedAudio);
  472. if (!instance.openInput(name))
  473. return true;
  474. instance.openVideo();
  475. instance.prepareOutput(1, true);
  476. auto lastTimePoint = boost::chrono::steady_clock::now();
  477. while(instance.loadNextFrame())
  478. {
  479. if(stopOnKey)
  480. {
  481. GH.input().fetchEvents();
  482. if(GH.input().ignoreEventsUntilInput())
  483. {
  484. CCS->soundh->stopSound(audioHandle);
  485. return false;
  486. }
  487. }
  488. SDL_Rect rect;
  489. rect.x = position.x;
  490. rect.y = position.y;
  491. rect.w = instance.dimensions.x;
  492. rect.h = instance.dimensions.y;
  493. SDL_RenderFillRect(mainRenderer, &rect);
  494. if(instance.textureYUV)
  495. SDL_RenderCopy(mainRenderer, instance.textureYUV, nullptr, &rect);
  496. else
  497. SDL_RenderCopy(mainRenderer, instance.textureRGB, nullptr, &rect);
  498. SDL_RenderPresent(mainRenderer);
  499. // Framerate delay
  500. double targetFrameTimeSeconds = instance.getCurrentFrameDuration();
  501. auto targetFrameTime = boost::chrono::milliseconds(static_cast<int>(1000 * targetFrameTimeSeconds));
  502. auto timePointAfterPresent = boost::chrono::steady_clock::now();
  503. auto timeSpentBusy = boost::chrono::duration_cast<boost::chrono::milliseconds>(timePointAfterPresent - lastTimePoint);
  504. if(targetFrameTime > timeSpentBusy)
  505. boost::this_thread::sleep_for(targetFrameTime - timeSpentBusy);
  506. lastTimePoint = boost::chrono::steady_clock::now();
  507. }
  508. return true;
  509. }
  510. void CVideoPlayer::playSpellbookAnimation(const VideoPath & name, const Point & position)
  511. {
  512. openAndPlayVideoImpl(name, position * GH.screenHandler().getScalingFactor(), false, false);
  513. }
  514. std::unique_ptr<IVideoInstance> CVideoPlayer::open(const VideoPath & name, float scaleFactor)
  515. {
  516. auto result = std::make_unique<CVideoInstance>();
  517. if (!result->openInput(name))
  518. return nullptr;
  519. result->openVideo();
  520. result->prepareOutput(scaleFactor, false);
  521. result->loadNextFrame(); // prepare 1st frame
  522. return result;
  523. }
  524. std::pair<std::unique_ptr<ui8[]>, si64> CVideoPlayer::getAudio(const VideoPath & videoToOpen)
  525. {
  526. CAudioInstance audio;
  527. return audio.extractAudio(videoToOpen);
  528. }
  529. #endif