video_stream_webm.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. /*************************************************************************/
  2. /* video_stream_webm.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "video_stream_webm.h"
  31. #include "OpusVorbisDecoder.hpp"
  32. #include "VPXDecoder.hpp"
  33. #include "mkvparser/mkvparser.h"
  34. #include "core/os/file_access.h"
  35. #include "core/os/os.h"
  36. #include "core/project_settings.h"
  37. #include "thirdparty/misc/yuv2rgb.h"
  38. #include "servers/audio_server.h"
  39. #include <string.h>
  40. class MkvReader : public mkvparser::IMkvReader {
  41. public:
  42. MkvReader(const String &p_file) {
  43. file = FileAccess::open(p_file, FileAccess::READ);
  44. ERR_EXPLAIN("Failed loading resource: '" + p_file + "';");
  45. ERR_FAIL_COND(!file);
  46. }
  47. ~MkvReader() {
  48. if (file)
  49. memdelete(file);
  50. }
  51. virtual int Read(long long pos, long len, unsigned char *buf) {
  52. if (file) {
  53. if (file->get_position() != (size_t)pos)
  54. file->seek(pos);
  55. if (file->get_buffer(buf, len) == len)
  56. return 0;
  57. }
  58. return -1;
  59. }
  60. virtual int Length(long long *total, long long *available) {
  61. if (file) {
  62. const size_t len = file->get_len();
  63. if (total)
  64. *total = len;
  65. if (available)
  66. *available = len;
  67. return 0;
  68. }
  69. return -1;
  70. }
  71. private:
  72. FileAccess *file;
  73. };
  74. /**/
  75. VideoStreamPlaybackWebm::VideoStreamPlaybackWebm() :
  76. audio_track(0),
  77. webm(NULL),
  78. video(NULL),
  79. audio(NULL),
  80. video_frames(NULL),
  81. audio_frame(NULL),
  82. video_frames_pos(0),
  83. video_frames_capacity(0),
  84. num_decoded_samples(0),
  85. samples_offset(-1),
  86. mix_callback(NULL),
  87. mix_udata(NULL),
  88. playing(false),
  89. paused(false),
  90. delay_compensation(0.0),
  91. time(0.0),
  92. video_frame_delay(0.0),
  93. video_pos(0.0),
  94. texture(memnew(ImageTexture)),
  95. pcm(NULL) {}
  96. VideoStreamPlaybackWebm::~VideoStreamPlaybackWebm() {
  97. delete_pointers();
  98. }
  99. bool VideoStreamPlaybackWebm::open_file(const String &p_file) {
  100. file_name = p_file;
  101. webm = memnew(WebMDemuxer(new MkvReader(file_name), 0, audio_track));
  102. if (webm->isOpen()) {
  103. video = memnew(VPXDecoder(*webm, OS::get_singleton()->get_processor_count()));
  104. if (video->isOpen()) {
  105. audio = memnew(OpusVorbisDecoder(*webm));
  106. if (audio->isOpen()) {
  107. audio_frame = memnew(WebMFrame);
  108. pcm = (float *)memalloc(sizeof(float) * audio->getBufferSamples() * webm->getChannels());
  109. } else {
  110. memdelete(audio);
  111. audio = NULL;
  112. }
  113. frame_data.resize((webm->getWidth() * webm->getHeight()) << 2);
  114. texture->create(webm->getWidth(), webm->getHeight(), Image::FORMAT_RGBA8, Texture::FLAG_FILTER | Texture::FLAG_VIDEO_SURFACE);
  115. return true;
  116. }
  117. memdelete(video);
  118. video = NULL;
  119. }
  120. memdelete(webm);
  121. webm = NULL;
  122. return false;
  123. }
  124. void VideoStreamPlaybackWebm::stop() {
  125. if (playing) {
  126. delete_pointers();
  127. pcm = NULL;
  128. audio_frame = NULL;
  129. video_frames = NULL;
  130. video = NULL;
  131. audio = NULL;
  132. open_file(file_name); //Should not fail here...
  133. video_frames_capacity = video_frames_pos = 0;
  134. num_decoded_samples = 0;
  135. samples_offset = -1;
  136. video_frame_delay = video_pos = 0.0;
  137. }
  138. time = 0.0;
  139. playing = false;
  140. }
  141. void VideoStreamPlaybackWebm::play() {
  142. stop();
  143. delay_compensation = ProjectSettings::get_singleton()->get("audio/video_delay_compensation_ms");
  144. delay_compensation /= 1000.0;
  145. playing = true;
  146. }
  147. bool VideoStreamPlaybackWebm::is_playing() const {
  148. return playing;
  149. }
  150. void VideoStreamPlaybackWebm::set_paused(bool p_paused) {
  151. paused = p_paused;
  152. }
  153. bool VideoStreamPlaybackWebm::is_paused() const {
  154. return paused;
  155. }
  156. void VideoStreamPlaybackWebm::set_loop(bool p_enable) {
  157. //Empty
  158. }
  159. bool VideoStreamPlaybackWebm::has_loop() const {
  160. return false;
  161. }
  162. float VideoStreamPlaybackWebm::get_length() const {
  163. if (webm)
  164. return webm->getLength();
  165. return 0.0f;
  166. }
  167. float VideoStreamPlaybackWebm::get_playback_position() const {
  168. return video_pos;
  169. }
  170. void VideoStreamPlaybackWebm::seek(float p_time) {
  171. //Not implemented
  172. }
  173. void VideoStreamPlaybackWebm::set_audio_track(int p_idx) {
  174. audio_track = p_idx;
  175. }
  176. Ref<Texture> VideoStreamPlaybackWebm::get_texture() {
  177. return texture;
  178. }
  179. void VideoStreamPlaybackWebm::update(float p_delta) {
  180. if ((!playing || paused) || !video)
  181. return;
  182. time += p_delta;
  183. if (time < video_pos) {
  184. return;
  185. }
  186. bool audio_buffer_full = false;
  187. if (samples_offset > -1) {
  188. //Mix remaining samples
  189. const int to_read = num_decoded_samples - samples_offset;
  190. const int mixed = mix_callback(mix_udata, pcm + samples_offset * webm->getChannels(), to_read);
  191. if (mixed != to_read) {
  192. samples_offset += mixed;
  193. audio_buffer_full = true;
  194. } else {
  195. samples_offset = -1;
  196. }
  197. }
  198. const bool hasAudio = (audio && mix_callback);
  199. while ((hasAudio && !audio_buffer_full && !has_enough_video_frames()) ||
  200. (!hasAudio && video_frames_pos == 0)) {
  201. if (hasAudio && !audio_buffer_full && audio_frame->isValid() &&
  202. audio->getPCMF(*audio_frame, pcm, num_decoded_samples) && num_decoded_samples > 0) {
  203. const int mixed = mix_callback(mix_udata, pcm, num_decoded_samples);
  204. if (mixed != num_decoded_samples) {
  205. samples_offset = mixed;
  206. audio_buffer_full = true;
  207. }
  208. }
  209. WebMFrame *video_frame;
  210. if (video_frames_pos >= video_frames_capacity) {
  211. WebMFrame **video_frames_new = (WebMFrame **)memrealloc(video_frames, ++video_frames_capacity * sizeof(void *));
  212. ERR_FAIL_COND(!video_frames_new); //Out of memory
  213. (video_frames = video_frames_new)[video_frames_capacity - 1] = memnew(WebMFrame);
  214. }
  215. video_frame = video_frames[video_frames_pos];
  216. if (!webm->readFrame(video_frame, audio_frame)) //This will invalidate frames
  217. break; //Can't demux, EOS?
  218. if (video_frame->isValid())
  219. ++video_frames_pos;
  220. };
  221. bool video_frame_done = false;
  222. while (video_frames_pos > 0 && !video_frame_done) {
  223. WebMFrame *video_frame = video_frames[0];
  224. // It seems VPXDecoder::decode has to be executed even though we might skip this frame
  225. if (video->decode(*video_frame)) {
  226. VPXDecoder::IMAGE_ERROR err;
  227. VPXDecoder::Image image;
  228. if (should_process(*video_frame)) {
  229. if ((err = video->getImage(image)) != VPXDecoder::NO_FRAME) {
  230. if (err == VPXDecoder::NO_ERROR && image.w == webm->getWidth() && image.h == webm->getHeight()) {
  231. PoolVector<uint8_t>::Write w = frame_data.write();
  232. bool converted = false;
  233. if (image.chromaShiftW == 1 && image.chromaShiftH == 1) {
  234. yuv420_2_rgb8888(w.ptr(), image.planes[0], image.planes[2], image.planes[1], image.w, image.h, image.linesize[0], image.linesize[1], image.w << 2, 0);
  235. // libyuv::I420ToARGB(image.planes[0], image.linesize[0], image.planes[2], image.linesize[2], image.planes[1], image.linesize[1], w.ptr(), image.w << 2, image.w, image.h);
  236. converted = true;
  237. } else if (image.chromaShiftW == 1 && image.chromaShiftH == 0) {
  238. yuv422_2_rgb8888(w.ptr(), image.planes[0], image.planes[2], image.planes[1], image.w, image.h, image.linesize[0], image.linesize[1], image.w << 2, 0);
  239. // libyuv::I422ToARGB(image.planes[0], image.linesize[0], image.planes[2], image.linesize[2], image.planes[1], image.linesize[1], w.ptr(), image.w << 2, image.w, image.h);
  240. converted = true;
  241. } else if (image.chromaShiftW == 0 && image.chromaShiftH == 0) {
  242. yuv444_2_rgb8888(w.ptr(), image.planes[0], image.planes[2], image.planes[1], image.w, image.h, image.linesize[0], image.linesize[1], image.w << 2, 0);
  243. // libyuv::I444ToARGB(image.planes[0], image.linesize[0], image.planes[2], image.linesize[2], image.planes[1], image.linesize[1], w.ptr(), image.w << 2, image.w, image.h);
  244. converted = true;
  245. } else if (image.chromaShiftW == 2 && image.chromaShiftH == 0) {
  246. // libyuv::I411ToARGB(image.planes[0], image.linesize[0], image.planes[2], image.linesize[2], image.planes[1], image.linesize[1], w.ptr(), image.w << 2, image.w, image.h);
  247. // converted = true;
  248. }
  249. if (converted) {
  250. Ref<Image> img = memnew(Image(image.w, image.h, 0, Image::FORMAT_RGBA8, frame_data));
  251. texture->set_data(img); //Zero copy send to visual server
  252. video_frame_done = true;
  253. }
  254. }
  255. }
  256. }
  257. }
  258. video_pos = video_frame->time;
  259. memmove(video_frames, video_frames + 1, (--video_frames_pos) * sizeof(void *));
  260. video_frames[video_frames_pos] = video_frame;
  261. }
  262. if (video_frames_pos == 0 && webm->isEOS())
  263. stop();
  264. }
  265. void VideoStreamPlaybackWebm::set_mix_callback(VideoStreamPlayback::AudioMixCallback p_callback, void *p_userdata) {
  266. mix_callback = p_callback;
  267. mix_udata = p_userdata;
  268. }
  269. int VideoStreamPlaybackWebm::get_channels() const {
  270. if (audio)
  271. return webm->getChannels();
  272. return 0;
  273. }
  274. int VideoStreamPlaybackWebm::get_mix_rate() const {
  275. if (audio)
  276. return webm->getSampleRate();
  277. return 0;
  278. }
  279. inline bool VideoStreamPlaybackWebm::has_enough_video_frames() const {
  280. if (video_frames_pos > 0) {
  281. const double audio_delay = AudioServer::get_singleton()->get_output_delay();
  282. const double video_time = video_frames[video_frames_pos - 1]->time;
  283. return video_time >= time + audio_delay + delay_compensation;
  284. }
  285. return false;
  286. }
  287. bool VideoStreamPlaybackWebm::should_process(WebMFrame &video_frame) {
  288. const double audio_delay = AudioServer::get_singleton()->get_output_delay();
  289. return video_frame.time >= time + audio_delay + delay_compensation;
  290. }
  291. void VideoStreamPlaybackWebm::delete_pointers() {
  292. if (pcm)
  293. memfree(pcm);
  294. if (audio_frame)
  295. memdelete(audio_frame);
  296. for (int i = 0; i < video_frames_capacity; ++i)
  297. memdelete(video_frames[i]);
  298. if (video_frames)
  299. memfree(video_frames);
  300. if (video)
  301. memdelete(video);
  302. if (audio)
  303. memdelete(audio);
  304. if (webm)
  305. memdelete(webm);
  306. }
  307. /**/
  308. VideoStreamWebm::VideoStreamWebm() :
  309. audio_track(0) {}
  310. Ref<VideoStreamPlayback> VideoStreamWebm::instance_playback() {
  311. Ref<VideoStreamPlaybackWebm> pb = memnew(VideoStreamPlaybackWebm);
  312. pb->set_audio_track(audio_track);
  313. if (pb->open_file(file))
  314. return pb;
  315. return NULL;
  316. }
  317. void VideoStreamWebm::set_file(const String &p_file) {
  318. file = p_file;
  319. }
  320. String VideoStreamWebm::get_file() {
  321. return file;
  322. }
  323. void VideoStreamWebm::_bind_methods() {
  324. ClassDB::bind_method(D_METHOD("set_file", "file"), &VideoStreamWebm::set_file);
  325. ClassDB::bind_method(D_METHOD("get_file"), &VideoStreamWebm::get_file);
  326. ADD_PROPERTY(PropertyInfo(Variant::STRING, "file", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "set_file", "get_file");
  327. }
  328. void VideoStreamWebm::set_audio_track(int p_track) {
  329. audio_track = p_track;
  330. }
  331. ////////////
  332. RES ResourceFormatLoaderWebm::load(const String &p_path, const String &p_original_path, Error *r_error) {
  333. FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
  334. if (!f) {
  335. if (r_error) {
  336. *r_error = ERR_CANT_OPEN;
  337. }
  338. return RES();
  339. }
  340. VideoStreamWebm *stream = memnew(VideoStreamWebm);
  341. stream->set_file(p_path);
  342. Ref<VideoStreamWebm> webm_stream = Ref<VideoStreamWebm>(stream);
  343. if (r_error) {
  344. *r_error = OK;
  345. }
  346. return webm_stream;
  347. }
  348. void ResourceFormatLoaderWebm::get_recognized_extensions(List<String> *p_extensions) const {
  349. p_extensions->push_back("webm");
  350. }
  351. bool ResourceFormatLoaderWebm::handles_type(const String &p_type) const {
  352. return ClassDB::is_parent_class(p_type, "VideoStream");
  353. }
  354. String ResourceFormatLoaderWebm::get_resource_type(const String &p_path) const {
  355. String el = p_path.get_extension().to_lower();
  356. if (el == "webm")
  357. return "VideoStreamWebm";
  358. return "";
  359. }