CVideoHandler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  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. // Define a set of functions to read data
  48. static int lodReadAudio(void* opaque, uint8_t* buf, int size)
  49. {
  50. auto video = reinterpret_cast<CVideoPlayer *>(opaque);
  51. return static_cast<int>(video->dataAudio->read(buf, size));
  52. }
  53. static si64 lodSeekAudio(void * opaque, si64 pos, int whence)
  54. {
  55. auto video = reinterpret_cast<CVideoPlayer *>(opaque);
  56. if (whence & AVSEEK_SIZE)
  57. return video->dataAudio->getSize();
  58. return video->dataAudio->seek(pos);
  59. }
  60. CVideoPlayer::CVideoPlayer()
  61. : stream(-1)
  62. , format (nullptr)
  63. , codecContext(nullptr)
  64. , codec(nullptr)
  65. , frame(nullptr)
  66. , sws(nullptr)
  67. , context(nullptr)
  68. , texture(nullptr)
  69. , dest(nullptr)
  70. , destRect(0,0,0,0)
  71. , pos(0,0,0,0)
  72. , frameTime(0)
  73. , doLoop(false)
  74. {}
  75. bool CVideoPlayer::open(const VideoPath & fname, bool scale)
  76. {
  77. return open(fname, true, false);
  78. }
  79. // loop = to loop through the video
  80. // useOverlay = directly write to the screen.
  81. bool CVideoPlayer::open(const VideoPath & videoToOpen, bool loop, bool useOverlay, bool scale)
  82. {
  83. close();
  84. doLoop = loop;
  85. frameTime = 0;
  86. if (CResourceHandler::get()->existsResource(videoToOpen))
  87. fname = videoToOpen;
  88. else
  89. fname = videoToOpen.addPrefix("VIDEO/");
  90. if (!CResourceHandler::get()->existsResource(fname))
  91. {
  92. logGlobal->error("Error: video %s was not found", fname.getName());
  93. return false;
  94. }
  95. data = CResourceHandler::get()->load(fname);
  96. static const int BUFFER_SIZE = 4096;
  97. unsigned char * buffer = (unsigned char *)av_malloc(BUFFER_SIZE);// will be freed by ffmpeg
  98. context = avio_alloc_context( buffer, BUFFER_SIZE, 0, (void *)this, lodRead, nullptr, lodSeek);
  99. format = avformat_alloc_context();
  100. format->pb = context;
  101. // filename is not needed - file was already open and stored in this->data;
  102. int avfopen = avformat_open_input(&format, "dummyFilename", nullptr, nullptr);
  103. if (avfopen != 0)
  104. {
  105. return false;
  106. }
  107. // Retrieve stream information
  108. if (avformat_find_stream_info(format, nullptr) < 0)
  109. return false;
  110. // Find the first video stream
  111. stream = -1;
  112. for(ui32 i=0; i<format->nb_streams; i++)
  113. {
  114. if (format->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  115. {
  116. stream = i;
  117. break;
  118. }
  119. }
  120. if (stream < 0)
  121. // No video stream in that file
  122. return false;
  123. // Find the decoder for the video stream
  124. codec = avcodec_find_decoder(format->streams[stream]->codecpar->codec_id);
  125. if (codec == nullptr)
  126. {
  127. // Unsupported codec
  128. return false;
  129. }
  130. codecContext = avcodec_alloc_context3(codec);
  131. if(!codecContext)
  132. return false;
  133. // Get a pointer to the codec context for the video stream
  134. int ret = avcodec_parameters_to_context(codecContext, format->streams[stream]->codecpar);
  135. if (ret < 0)
  136. {
  137. //We cannot get codec from parameters
  138. avcodec_free_context(&codecContext);
  139. return false;
  140. }
  141. // Open codec
  142. if ( avcodec_open2(codecContext, codec, nullptr) < 0 )
  143. {
  144. // Could not open codec
  145. codec = nullptr;
  146. return false;
  147. }
  148. // Allocate video frame
  149. frame = av_frame_alloc();
  150. //setup scaling
  151. if(scale)
  152. {
  153. pos.w = screen->w;
  154. pos.h = screen->h;
  155. }
  156. else
  157. {
  158. pos.w = codecContext->width;
  159. pos.h = codecContext->height;
  160. }
  161. // Allocate a place to put our YUV image on that screen
  162. if (useOverlay)
  163. {
  164. texture = SDL_CreateTexture( mainRenderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STATIC, pos.w, pos.h);
  165. }
  166. else
  167. {
  168. dest = CSDL_Ext::newSurface(pos.w, pos.h);
  169. destRect.x = destRect.y = 0;
  170. destRect.w = pos.w;
  171. destRect.h = pos.h;
  172. }
  173. if (texture == nullptr && dest == nullptr)
  174. return false;
  175. if (texture)
  176. { // Convert the image into YUV format that SDL uses
  177. sws = sws_getContext(codecContext->width, codecContext->height, codecContext->pix_fmt,
  178. pos.w, pos.h,
  179. AV_PIX_FMT_YUV420P,
  180. SWS_BICUBIC, nullptr, nullptr, nullptr);
  181. }
  182. else
  183. {
  184. AVPixelFormat screenFormat = AV_PIX_FMT_NONE;
  185. if (screen->format->Bshift > screen->format->Rshift)
  186. {
  187. // this a BGR surface
  188. switch (screen->format->BytesPerPixel)
  189. {
  190. case 2: screenFormat = AV_PIX_FMT_BGR565; break;
  191. case 3: screenFormat = AV_PIX_FMT_BGR24; break;
  192. case 4: screenFormat = AV_PIX_FMT_BGR32; break;
  193. default: return false;
  194. }
  195. }
  196. else
  197. {
  198. // this a RGB surface
  199. switch (screen->format->BytesPerPixel)
  200. {
  201. case 2: screenFormat = AV_PIX_FMT_RGB565; break;
  202. case 3: screenFormat = AV_PIX_FMT_RGB24; break;
  203. case 4: screenFormat = AV_PIX_FMT_RGB32; break;
  204. default: return false;
  205. }
  206. }
  207. sws = sws_getContext(codecContext->width, codecContext->height, codecContext->pix_fmt,
  208. pos.w, pos.h, screenFormat,
  209. SWS_BICUBIC, nullptr, nullptr, nullptr);
  210. }
  211. if (sws == nullptr)
  212. return false;
  213. return true;
  214. }
  215. // Read the next frame. Return false on error/end of file.
  216. bool CVideoPlayer::nextFrame()
  217. {
  218. AVPacket packet;
  219. int frameFinished = 0;
  220. bool gotError = false;
  221. if (sws == nullptr)
  222. return false;
  223. while(!frameFinished)
  224. {
  225. int ret = av_read_frame(format, &packet);
  226. if (ret < 0)
  227. {
  228. // Error. It's probably an end of file.
  229. if (doLoop && !gotError)
  230. {
  231. // Rewind
  232. frameTime = 0;
  233. if (av_seek_frame(format, stream, 0, AVSEEK_FLAG_BYTE) < 0)
  234. break;
  235. gotError = true;
  236. }
  237. else
  238. {
  239. break;
  240. }
  241. }
  242. else
  243. {
  244. // Is this a packet from the video stream?
  245. if (packet.stream_index == stream)
  246. {
  247. // Decode video frame
  248. int rc = avcodec_send_packet(codecContext, &packet);
  249. if (rc >=0)
  250. packet.size = 0;
  251. rc = avcodec_receive_frame(codecContext, frame);
  252. if (rc >= 0)
  253. frameFinished = 1;
  254. // Did we get a video frame?
  255. if (frameFinished)
  256. {
  257. uint8_t *data[4];
  258. int linesize[4];
  259. if (texture) {
  260. av_image_alloc(data, linesize, pos.w, pos.h, AV_PIX_FMT_YUV420P, 1);
  261. sws_scale(sws, frame->data, frame->linesize,
  262. 0, codecContext->height, data, linesize);
  263. SDL_UpdateYUVTexture(texture, NULL, data[0], linesize[0],
  264. data[1], linesize[1],
  265. data[2], linesize[2]);
  266. av_freep(&data[0]);
  267. }
  268. else
  269. {
  270. /* Avoid buffer overflow caused by sws_scale():
  271. * http://trac.ffmpeg.org/ticket/9254
  272. * Currently (ffmpeg-4.4 with SSE3 enabled) sws_scale()
  273. * has a few requirements for target data buffers on rescaling:
  274. * 1. buffer has to be aligned to be usable for SIMD instructions
  275. * 2. buffer has to be padded to allow small overflow by SIMD instructions
  276. * Unfortunately SDL_Surface does not provide these guarantees.
  277. * This means that atempt to rescale directly into SDL surface causes
  278. * memory corruption. Usually it happens on campaign selection screen
  279. * where short video moves start spinning on mouse hover.
  280. *
  281. * To fix [1.] we use av_malloc() for memory allocation.
  282. * To fix [2.] we add an `ffmpeg_pad` that provides plenty of space.
  283. * We have to use intermdiate buffer and then use memcpy() to land it
  284. * to SDL_Surface.
  285. */
  286. size_t pic_bytes = dest->pitch * dest->h;
  287. size_t ffmped_pad = 1024; /* a few bytes of overflow will go here */
  288. void * for_sws = av_malloc (pic_bytes + ffmped_pad);
  289. data[0] = (ui8 *)for_sws;
  290. linesize[0] = dest->pitch;
  291. sws_scale(sws, frame->data, frame->linesize,
  292. 0, codecContext->height, data, linesize);
  293. memcpy(dest->pixels, for_sws, pic_bytes);
  294. av_free(for_sws);
  295. }
  296. }
  297. }
  298. av_packet_unref(&packet);
  299. }
  300. }
  301. return frameFinished != 0;
  302. }
  303. void CVideoPlayer::show( int x, int y, SDL_Surface *dst, bool update )
  304. {
  305. if (sws == nullptr)
  306. return;
  307. pos.x = x;
  308. pos.y = y;
  309. CSDL_Ext::blitSurface(dest, destRect, dst, pos.topLeft());
  310. if (update)
  311. CSDL_Ext::updateRect(dst, pos);
  312. }
  313. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  314. {
  315. show(x, y, dst, update);
  316. }
  317. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update, std::function<void()> onVideoRestart)
  318. {
  319. if (sws == nullptr)
  320. return;
  321. #if (LIBAVUTIL_VERSION_MAJOR < 58)
  322. auto packet_duration = frame->pkt_duration;
  323. #else
  324. auto packet_duration = frame->duration;
  325. #endif
  326. double frameEndTime = (frame->pts + packet_duration) * av_q2d(format->streams[stream]->time_base);
  327. frameTime += GH.framerate().getElapsedMilliseconds() / 1000.0;
  328. if (frameTime >= frameEndTime )
  329. {
  330. if (nextFrame())
  331. show(x,y,dst,update);
  332. else
  333. {
  334. if(onVideoRestart)
  335. onVideoRestart();
  336. VideoPath filenameToReopen = fname; // create copy to backup this->fname
  337. open(filenameToReopen);
  338. nextFrame();
  339. // The y position is wrong at the first frame.
  340. // Note: either the windows player or the linux player is
  341. // broken. Compensate here until the bug is found.
  342. show(x, y--, dst, update);
  343. }
  344. }
  345. else
  346. {
  347. redraw(x, y, dst, update);
  348. }
  349. }
  350. void CVideoPlayer::close()
  351. {
  352. fname = VideoPath();
  353. if (sws)
  354. {
  355. sws_freeContext(sws);
  356. sws = nullptr;
  357. }
  358. if (texture)
  359. {
  360. SDL_DestroyTexture(texture);
  361. texture = nullptr;
  362. }
  363. if (dest)
  364. {
  365. SDL_FreeSurface(dest);
  366. dest = nullptr;
  367. }
  368. if (frame)
  369. {
  370. av_frame_free(&frame);//will be set to null
  371. }
  372. if (codec)
  373. {
  374. avcodec_close(codecContext);
  375. codec = nullptr;
  376. }
  377. if (codecContext)
  378. {
  379. avcodec_free_context(&codecContext);
  380. }
  381. if (format)
  382. {
  383. avformat_close_input(&format);
  384. }
  385. if (context)
  386. {
  387. av_free(context);
  388. context = nullptr;
  389. }
  390. }
  391. std::pair<std::unique_ptr<ui8 []>, si64> CVideoPlayer::getAudio(const VideoPath & videoToOpen)
  392. {
  393. std::pair<std::unique_ptr<ui8 []>, si64> dat(std::make_pair(nullptr, 0));
  394. VideoPath fnameAudio;
  395. if (CResourceHandler::get()->existsResource(videoToOpen))
  396. fnameAudio = videoToOpen;
  397. else
  398. fnameAudio = videoToOpen.addPrefix("VIDEO/");
  399. if (!CResourceHandler::get()->existsResource(fnameAudio))
  400. {
  401. logGlobal->error("Error: video %s was not found", fnameAudio.getName());
  402. return dat;
  403. }
  404. dataAudio = CResourceHandler::get()->load(fnameAudio);
  405. static const int BUFFER_SIZE = 4096;
  406. unsigned char * bufferAudio = (unsigned char *)av_malloc(BUFFER_SIZE);// will be freed by ffmpeg
  407. AVIOContext * contextAudio = avio_alloc_context( bufferAudio, BUFFER_SIZE, 0, (void *)this, lodReadAudio, nullptr, lodSeekAudio);
  408. AVFormatContext * formatAudio = avformat_alloc_context();
  409. formatAudio->pb = contextAudio;
  410. // filename is not needed - file was already open and stored in this->data;
  411. int avfopen = avformat_open_input(&formatAudio, "dummyFilename", nullptr, nullptr);
  412. if (avfopen != 0)
  413. {
  414. return dat;
  415. }
  416. // Retrieve stream information
  417. if (avformat_find_stream_info(formatAudio, nullptr) < 0)
  418. return dat;
  419. // Find the first audio stream
  420. int streamAudio = -1;
  421. for(ui32 i = 0; i < formatAudio->nb_streams; i++)
  422. {
  423. if (formatAudio->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  424. {
  425. streamAudio = i;
  426. break;
  427. }
  428. }
  429. if(streamAudio < 0)
  430. return dat;
  431. const AVCodec *codecAudio = avcodec_find_decoder(formatAudio->streams[streamAudio]->codecpar->codec_id);
  432. AVCodecContext *codecContextAudio;
  433. if (codecAudio != nullptr)
  434. codecContextAudio = avcodec_alloc_context3(codecAudio);
  435. // Get a pointer to the codec context for the audio stream
  436. if (streamAudio > -1)
  437. {
  438. int ret = avcodec_parameters_to_context(codecContextAudio, formatAudio->streams[streamAudio]->codecpar);
  439. if (ret < 0)
  440. {
  441. //We cannot get codec from parameters
  442. avcodec_free_context(&codecContextAudio);
  443. }
  444. }
  445. // Open codec
  446. AVFrame *frameAudio;
  447. if (codecAudio != nullptr)
  448. {
  449. if ( avcodec_open2(codecContextAudio, codecAudio, nullptr) < 0 )
  450. {
  451. // Could not open codec
  452. codecAudio = nullptr;
  453. }
  454. // Allocate audio frame
  455. frameAudio = av_frame_alloc();
  456. }
  457. AVPacket packet;
  458. std::vector<ui8> samples;
  459. while (av_read_frame(formatAudio, &packet) >= 0)
  460. {
  461. if(packet.stream_index == streamAudio)
  462. {
  463. int rc = avcodec_send_packet(codecContextAudio, &packet);
  464. if (rc >= 0)
  465. packet.size = 0;
  466. rc = avcodec_receive_frame(codecContextAudio, frameAudio);
  467. int bytesToRead = (frameAudio->nb_samples * 2 * (formatAudio->streams[streamAudio]->codecpar->bits_per_coded_sample / 8));
  468. if (rc >= 0)
  469. for (int s = 0; s < bytesToRead; s += sizeof(ui8))
  470. {
  471. ui8 value;
  472. memcpy(&value, &frameAudio->data[0][s], sizeof(ui8));
  473. samples.push_back(value);
  474. }
  475. }
  476. av_packet_unref(&packet);
  477. }
  478. typedef struct WAV_HEADER {
  479. ui8 RIFF[4] = {'R', 'I', 'F', 'F'};
  480. ui32 ChunkSize;
  481. ui8 WAVE[4] = {'W', 'A', 'V', 'E'};
  482. ui8 fmt[4] = {'f', 'm', 't', ' '};
  483. ui32 Subchunk1Size = 16;
  484. ui16 AudioFormat = 1;
  485. ui16 NumOfChan = 2;
  486. ui32 SamplesPerSec = 22050;
  487. ui32 bytesPerSec = 22050 * 2;
  488. ui16 blockAlign = 2;
  489. ui16 bitsPerSample = 16;
  490. ui8 Subchunk2ID[4] = {'d', 'a', 't', 'a'};
  491. ui32 Subchunk2Size;
  492. } wav_hdr;
  493. wav_hdr wav;
  494. wav.ChunkSize = samples.size() + sizeof(wav_hdr) - 8;
  495. wav.Subchunk2Size = samples.size() + sizeof(wav_hdr) - 44;
  496. wav.SamplesPerSec = formatAudio->streams[streamAudio]->codecpar->sample_rate;
  497. wav.bitsPerSample = formatAudio->streams[streamAudio]->codecpar->bits_per_coded_sample;
  498. auto wavPtr = reinterpret_cast<ui8*>(&wav);
  499. dat = std::make_pair(std::make_unique<ui8[]>(samples.size() + sizeof(wav_hdr)), samples.size() + sizeof(wav_hdr));
  500. std::copy(wavPtr, wavPtr + sizeof(wav_hdr), dat.first.get());
  501. std::copy(samples.begin(), samples.end(), dat.first.get() + sizeof(wav_hdr));
  502. if (frameAudio)
  503. av_frame_free(&frameAudio);
  504. if (codecAudio)
  505. {
  506. avcodec_close(codecContextAudio);
  507. codecAudio = nullptr;
  508. }
  509. if (codecContextAudio)
  510. avcodec_free_context(&codecContextAudio);
  511. if (formatAudio)
  512. avformat_close_input(&formatAudio);
  513. if (contextAudio)
  514. {
  515. av_free(contextAudio);
  516. contextAudio = nullptr;
  517. }
  518. return dat;
  519. }
  520. // Plays a video. Only works for overlays.
  521. bool CVideoPlayer::playVideo(int x, int y, bool stopOnKey)
  522. {
  523. // Note: either the windows player or the linux player is
  524. // broken. Compensate here until the bug is found.
  525. y--;
  526. pos.x = x;
  527. pos.y = y;
  528. frameTime = 0.0;
  529. while(nextFrame())
  530. {
  531. if(stopOnKey)
  532. {
  533. GH.input().fetchEvents();
  534. if(GH.input().ignoreEventsUntilInput())
  535. return false;
  536. }
  537. SDL_Rect rect = CSDL_Ext::toSDL(pos);
  538. SDL_RenderCopy(mainRenderer, texture, nullptr, &rect);
  539. SDL_RenderPresent(mainRenderer);
  540. #if (LIBAVUTIL_VERSION_MAJOR < 58)
  541. auto packet_duration = frame->pkt_duration;
  542. #else
  543. auto packet_duration = frame->duration;
  544. #endif
  545. double frameDurationSec = packet_duration * av_q2d(format->streams[stream]->time_base);
  546. uint32_t timeToSleepMillisec = 1000 * (frameDurationSec);
  547. boost::this_thread::sleep_for(boost::chrono::milliseconds(timeToSleepMillisec));
  548. }
  549. return true;
  550. }
  551. bool CVideoPlayer::openAndPlayVideo(const VideoPath & name, int x, int y, bool stopOnKey, bool scale)
  552. {
  553. open(name, false, true, scale);
  554. bool ret = playVideo(x, y, stopOnKey);
  555. close();
  556. return ret;
  557. }
  558. CVideoPlayer::~CVideoPlayer()
  559. {
  560. close();
  561. }
  562. #endif