CVideoHandler.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. #include "StdInc.h"
  2. #include <SDL.h>
  3. #include "CVideoHandler.h"
  4. #include "gui/CGuiHandler.h"
  5. #include "gui/SDL_Extensions.h"
  6. #include "CPlayerInterface.h"
  7. #include "../lib/filesystem/Filesystem.h"
  8. extern CGuiHandler GH; //global gui handler
  9. #ifndef DISABLE_VIDEO
  10. //reads events and returns true on key down
  11. static bool keyDown()
  12. {
  13. SDL_Event ev;
  14. while(SDL_PollEvent(&ev))
  15. {
  16. if(ev.type == SDL_KEYDOWN || ev.type == SDL_MOUSEBUTTONDOWN)
  17. return true;
  18. }
  19. return false;
  20. }
  21. #ifdef _MSC_VER
  22. #pragma comment(lib, "avcodec.lib")
  23. #pragma comment(lib, "avutil.lib")
  24. #pragma comment(lib, "avformat.lib")
  25. #pragma comment(lib, "swscale.lib")
  26. #endif // _MSC_VER
  27. // Define a set of functions to read data
  28. static int lodRead(void* opaque, uint8_t* buf, int size)
  29. {
  30. auto video = reinterpret_cast<CVideoPlayer *>(opaque);
  31. return video->data->read(buf, size);
  32. }
  33. static si64 lodSeek(void * opaque, si64 pos, int whence)
  34. {
  35. auto video = reinterpret_cast<CVideoPlayer *>(opaque);
  36. if (whence & AVSEEK_SIZE)
  37. return video->data->getSize();
  38. return video->data->seek(pos);
  39. }
  40. CVideoPlayer::CVideoPlayer()
  41. {
  42. stream = -1;
  43. format = nullptr;
  44. codecContext = nullptr;
  45. codec = nullptr;
  46. frame = nullptr;
  47. sws = nullptr;
  48. context = nullptr;
  49. texture = nullptr;
  50. dest = nullptr;
  51. destRect = genRect(0,0,0,0);
  52. pos = genRect(0,0,0,0);
  53. refreshWait = 0;
  54. refreshCount = 0;
  55. doLoop = false;
  56. // Register codecs. TODO: May be overkill. Should call a
  57. // combination of av_register_input_format() /
  58. // av_register_output_format() / av_register_protocol() instead.
  59. av_register_all();
  60. }
  61. bool CVideoPlayer::open(std::string fname, bool scale/* = false*/)
  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 /*= false*/)
  68. {
  69. close();
  70. this->fname = fname;
  71. refreshWait = 3;
  72. refreshCount = -1;
  73. doLoop = loop;
  74. ResourceID resource(std::string("Video/") + fname, EResType::VIDEO);
  75. if (!CResourceHandler::get()->existsResource(resource))
  76. {
  77. logGlobal->errorStream() << "Error: video " << resource.getName() << " was not found";
  78. return false;
  79. }
  80. data = CResourceHandler::get()->load(resource);
  81. static const int BUFFER_SIZE = 4096;
  82. unsigned char * buffer = (unsigned char *)av_malloc(BUFFER_SIZE);// will be freed by ffmpeg
  83. context = avio_alloc_context( buffer, BUFFER_SIZE, 0, (void *)this, lodRead, nullptr, lodSeek);
  84. format = avformat_alloc_context();
  85. format->pb = context;
  86. // filename is not needed - file was already open and stored in this->data;
  87. int avfopen = avformat_open_input(&format, "dummyFilename", nullptr, nullptr);
  88. if (avfopen != 0)
  89. {
  90. return false;
  91. }
  92. // Retrieve stream information
  93. if (avformat_find_stream_info(format, nullptr) < 0)
  94. return false;
  95. // Find the first video stream
  96. stream = -1;
  97. for(ui32 i=0; i<format->nb_streams; i++)
  98. {
  99. if (format->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
  100. {
  101. stream = i;
  102. break;
  103. }
  104. }
  105. if (stream < 0)
  106. // No video stream in that file
  107. return false;
  108. // Get a pointer to the codec context for the video stream
  109. codecContext = format->streams[stream]->codec;
  110. // Find the decoder for the video stream
  111. codec = avcodec_find_decoder(codecContext->codec_id);
  112. if (codec == nullptr)
  113. {
  114. // Unsupported codec
  115. return false;
  116. }
  117. // Open codec
  118. if ( avcodec_open2(codecContext, codec, nullptr) < 0 )
  119. {
  120. // Could not open codec
  121. codec = nullptr;
  122. return false;
  123. }
  124. // Allocate video frame
  125. frame = av_frame_alloc();
  126. //setup scaling
  127. if(scale)
  128. {
  129. pos.w = screen->w;
  130. pos.h = screen->h;
  131. }
  132. else
  133. {
  134. pos.w = codecContext->width;
  135. pos.h = codecContext->height;
  136. }
  137. // Allocate a place to put our YUV image on that screen
  138. if (useOverlay)
  139. {
  140. texture = SDL_CreateTexture( mainRenderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STATIC, pos.w, pos.h);
  141. }
  142. else
  143. {
  144. dest = CSDL_Ext::newSurface(pos.w, pos.h);
  145. destRect.x = destRect.y = 0;
  146. destRect.w = pos.w;
  147. destRect.h = pos.h;
  148. }
  149. if (texture == nullptr && dest == nullptr)
  150. return false;
  151. if (texture)
  152. { // Convert the image into YUV format that SDL uses
  153. sws = sws_getContext(codecContext->width, codecContext->height, codecContext->pix_fmt,
  154. pos.w, pos.h,
  155. AV_PIX_FMT_YUV420P,
  156. SWS_BICUBIC, nullptr, nullptr, nullptr);
  157. }
  158. else
  159. {
  160. AVPixelFormat screenFormat = AV_PIX_FMT_NONE;
  161. if (screen->format->Bshift > screen->format->Rshift)
  162. {
  163. // this a BGR surface
  164. switch (screen->format->BytesPerPixel)
  165. {
  166. case 2: screenFormat = AV_PIX_FMT_BGR565; break;
  167. case 3: screenFormat = AV_PIX_FMT_BGR24; break;
  168. case 4: screenFormat = AV_PIX_FMT_BGR32; break;
  169. default: return false;
  170. }
  171. }
  172. else
  173. {
  174. // this a RGB surface
  175. switch (screen->format->BytesPerPixel)
  176. {
  177. case 2: screenFormat = AV_PIX_FMT_RGB565; break;
  178. case 3: screenFormat = AV_PIX_FMT_RGB24; break;
  179. case 4: screenFormat = AV_PIX_FMT_RGB32; break;
  180. default: return false;
  181. }
  182. }
  183. sws = sws_getContext(codecContext->width, codecContext->height, codecContext->pix_fmt,
  184. pos.w, pos.h, screenFormat,
  185. SWS_BICUBIC, nullptr, nullptr, nullptr);
  186. }
  187. if (sws == nullptr)
  188. return false;
  189. return true;
  190. }
  191. // Read the next frame. Return false on error/end of file.
  192. bool CVideoPlayer::nextFrame()
  193. {
  194. AVPacket packet;
  195. int frameFinished = 0;
  196. bool gotError = false;
  197. if (sws == nullptr)
  198. return false;
  199. while(!frameFinished)
  200. {
  201. int ret = av_read_frame(format, &packet);
  202. if (ret < 0)
  203. {
  204. // Error. It's probably an end of file.
  205. if (doLoop && !gotError)
  206. {
  207. // Rewind
  208. if (av_seek_frame(format, stream, 0, AVSEEK_FLAG_BYTE) < 0)
  209. break;
  210. gotError = true;
  211. }
  212. else
  213. {
  214. break;
  215. }
  216. }
  217. else
  218. {
  219. // Is this a packet from the video stream?
  220. if (packet.stream_index == stream)
  221. {
  222. // Decode video frame
  223. avcodec_decode_video2(codecContext, frame, &frameFinished, &packet);
  224. // Did we get a video frame?
  225. if (frameFinished)
  226. {
  227. AVPicture pict;
  228. if (texture) {
  229. avpicture_alloc(&pict, AV_PIX_FMT_YUV420P, pos.w, pos.h);
  230. sws_scale(sws, frame->data, frame->linesize,
  231. 0, codecContext->height, pict.data, pict.linesize);
  232. SDL_UpdateYUVTexture(texture, NULL, pict.data[0], pict.linesize[0],
  233. pict.data[1], pict.linesize[1],
  234. pict.data[2], pict.linesize[2]);
  235. avpicture_free(&pict);
  236. }
  237. else
  238. {
  239. pict.data[0] = (ui8 *)dest->pixels;
  240. pict.linesize[0] = dest->pitch;
  241. sws_scale(sws, frame->data, frame->linesize,
  242. 0, codecContext->height, pict.data, pict.linesize);
  243. }
  244. }
  245. }
  246. av_free_packet(&packet);
  247. }
  248. }
  249. return frameFinished != 0;
  250. }
  251. void CVideoPlayer::show( int x, int y, SDL_Surface *dst, bool update )
  252. {
  253. if (sws == nullptr)
  254. return;
  255. pos.x = x;
  256. pos.y = y;
  257. CSDL_Ext::blitSurface(dest, &destRect, dst, &pos);
  258. if (update)
  259. SDL_UpdateRect(dst, pos.x, pos.y, pos.w, pos.h);
  260. }
  261. void CVideoPlayer::redraw( int x, int y, SDL_Surface *dst, bool update )
  262. {
  263. show(x, y, dst, update);
  264. }
  265. void CVideoPlayer::update( int x, int y, SDL_Surface *dst, bool forceRedraw, bool update )
  266. {
  267. if (sws == nullptr)
  268. return;
  269. if (refreshCount <= 0)
  270. {
  271. refreshCount = refreshWait;
  272. if (nextFrame())
  273. show(x,y,dst,update);
  274. else
  275. {
  276. open(fname);
  277. nextFrame();
  278. // The y position is wrong at the first frame.
  279. // Note: either the windows player or the linux player is
  280. // broken. Compensate here until the bug is found.
  281. show(x, y--, dst, update);
  282. }
  283. }
  284. else
  285. {
  286. redraw(x, y, dst, update);
  287. }
  288. refreshCount --;
  289. }
  290. void CVideoPlayer::close()
  291. {
  292. fname = "";
  293. if (sws)
  294. {
  295. sws_freeContext(sws);
  296. sws = nullptr;
  297. }
  298. if (texture)
  299. {
  300. SDL_DestroyTexture(texture);
  301. texture = nullptr;
  302. }
  303. if (dest)
  304. {
  305. SDL_FreeSurface(dest);
  306. dest = nullptr;
  307. }
  308. if (frame)
  309. {
  310. av_frame_free(&frame);//will be set to null
  311. }
  312. if (codec)
  313. {
  314. avcodec_close(codecContext);
  315. codec = nullptr;
  316. codecContext = nullptr;
  317. }
  318. if (format)
  319. {
  320. avformat_close_input(&format);
  321. }
  322. if (context)
  323. {
  324. av_free(context);
  325. context = nullptr;
  326. }
  327. }
  328. // Plays a video. Only works for overlays.
  329. bool CVideoPlayer::playVideo(int x, int y, SDL_Surface *dst, bool stopOnKey)
  330. {
  331. // Note: either the windows player or the linux player is
  332. // broken. Compensate here until the bug is found.
  333. y--;
  334. pos.x = x;
  335. pos.y = y;
  336. while(nextFrame())
  337. {
  338. if(stopOnKey && keyDown())
  339. return false;
  340. SDL_RenderCopy(mainRenderer, texture, NULL, &pos);
  341. SDL_RenderPresent(mainRenderer);
  342. // Wait 3 frames
  343. GH.mainFPSmng->framerateDelay();
  344. GH.mainFPSmng->framerateDelay();
  345. GH.mainFPSmng->framerateDelay();
  346. }
  347. return true;
  348. }
  349. bool CVideoPlayer::openAndPlayVideo(std::string name, int x, int y, SDL_Surface *dst, bool stopOnKey, bool scale/* = false*/)
  350. {
  351. open(name, false, true, scale);
  352. bool ret = playVideo(x, y, dst, stopOnKey);
  353. close();
  354. return ret;
  355. }
  356. CVideoPlayer::~CVideoPlayer()
  357. {
  358. close();
  359. }
  360. #endif