video_stream_webm.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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 "core/config/project_settings.h"
  32. #include "core/os/file_access.h"
  33. #include "core/os/os.h"
  34. #include "servers/audio_server.h"
  35. #include "thirdparty/misc/yuv2rgb.h"
  36. // libsimplewebm
  37. #include <OpusVorbisDecoder.hpp>
  38. #include <VPXDecoder.hpp>
  39. // libvpx
  40. #include <vpx/vpx_image.h>
  41. // libwebm
  42. #include <mkvparser/mkvparser.h>
  43. class MkvReader : public mkvparser::IMkvReader {
  44. public:
  45. MkvReader(const String &p_file) {
  46. file = FileAccess::open(p_file, FileAccess::READ);
  47. ERR_FAIL_COND_MSG(!file, "Failed loading resource: '" + p_file + "'.");
  48. }
  49. ~MkvReader() {
  50. if (file) {
  51. memdelete(file);
  52. }
  53. }
  54. virtual int Read(long long pos, long len, unsigned char *buf) {
  55. if (file) {
  56. if (file->get_position() != (size_t)pos) {
  57. file->seek(pos);
  58. }
  59. if (file->get_buffer(buf, len) == len) {
  60. return 0;
  61. }
  62. }
  63. return -1;
  64. }
  65. virtual int Length(long long *total, long long *available) {
  66. if (file) {
  67. const size_t len = file->get_len();
  68. if (total) {
  69. *total = len;
  70. }
  71. if (available) {
  72. *available = len;
  73. }
  74. return 0;
  75. }
  76. return -1;
  77. }
  78. private:
  79. FileAccess *file;
  80. };
  81. /**/
  82. VideoStreamPlaybackWebm::VideoStreamPlaybackWebm() :
  83. texture(memnew(ImageTexture)) {}
  84. VideoStreamPlaybackWebm::~VideoStreamPlaybackWebm() {
  85. delete_pointers();
  86. }
  87. bool VideoStreamPlaybackWebm::open_file(const String &p_file) {
  88. file_name = p_file;
  89. webm = memnew(WebMDemuxer(new MkvReader(file_name), 0, audio_track));
  90. if (webm->isOpen()) {
  91. video = memnew(VPXDecoder(*webm, OS::get_singleton()->get_processor_count()));
  92. if (video->isOpen()) {
  93. audio = memnew(OpusVorbisDecoder(*webm));
  94. if (audio->isOpen()) {
  95. audio_frame = memnew(WebMFrame);
  96. pcm = (float *)memalloc(sizeof(float) * audio->getBufferSamples() * webm->getChannels());
  97. } else {
  98. memdelete(audio);
  99. audio = nullptr;
  100. }
  101. frame_data.resize((webm->getWidth() * webm->getHeight()) << 2);
  102. Ref<Image> img;
  103. img.instance();
  104. img->create(webm->getWidth(), webm->getHeight(), false, Image::FORMAT_RGBA8);
  105. texture->create_from_image(img);
  106. return true;
  107. }
  108. memdelete(video);
  109. video = nullptr;
  110. }
  111. memdelete(webm);
  112. webm = nullptr;
  113. return false;
  114. }
  115. void VideoStreamPlaybackWebm::stop() {
  116. if (playing) {
  117. delete_pointers();
  118. pcm = nullptr;
  119. audio_frame = nullptr;
  120. video_frames = nullptr;
  121. video = nullptr;
  122. audio = nullptr;
  123. open_file(file_name); //Should not fail here...
  124. video_frames_capacity = video_frames_pos = 0;
  125. num_decoded_samples = 0;
  126. samples_offset = -1;
  127. video_frame_delay = video_pos = 0.0;
  128. }
  129. time = 0.0;
  130. playing = false;
  131. }
  132. void VideoStreamPlaybackWebm::play() {
  133. stop();
  134. delay_compensation = ProjectSettings::get_singleton()->get("audio/video/video_delay_compensation_ms");
  135. delay_compensation /= 1000.0;
  136. playing = true;
  137. }
  138. bool VideoStreamPlaybackWebm::is_playing() const {
  139. return playing;
  140. }
  141. void VideoStreamPlaybackWebm::set_paused(bool p_paused) {
  142. paused = p_paused;
  143. }
  144. bool VideoStreamPlaybackWebm::is_paused() const {
  145. return paused;
  146. }
  147. void VideoStreamPlaybackWebm::set_loop(bool p_enable) {
  148. //Empty
  149. }
  150. bool VideoStreamPlaybackWebm::has_loop() const {
  151. return false;
  152. }
  153. float VideoStreamPlaybackWebm::get_length() const {
  154. if (webm) {
  155. return webm->getLength();
  156. }
  157. return 0.0f;
  158. }
  159. float VideoStreamPlaybackWebm::get_playback_position() const {
  160. return video_pos;
  161. }
  162. void VideoStreamPlaybackWebm::seek(float p_time) {
  163. //Not implemented
  164. }
  165. void VideoStreamPlaybackWebm::set_audio_track(int p_idx) {
  166. audio_track = p_idx;
  167. }
  168. Ref<Texture2D> VideoStreamPlaybackWebm::get_texture() const {
  169. return texture;
  170. }
  171. void VideoStreamPlaybackWebm::update(float p_delta) {
  172. if ((!playing || paused) || !video) {
  173. return;
  174. }
  175. time += p_delta;
  176. if (time < video_pos) {
  177. return;
  178. }
  179. bool audio_buffer_full = false;
  180. if (samples_offset > -1) {
  181. //Mix remaining samples
  182. const int to_read = num_decoded_samples - samples_offset;
  183. const int mixed = mix_callback(mix_udata, pcm + samples_offset * webm->getChannels(), to_read);
  184. if (mixed != to_read) {
  185. samples_offset += mixed;
  186. audio_buffer_full = true;
  187. } else {
  188. samples_offset = -1;
  189. }
  190. }
  191. const bool hasAudio = (audio && mix_callback);
  192. while ((hasAudio && !audio_buffer_full && !has_enough_video_frames()) ||
  193. (!hasAudio && video_frames_pos == 0)) {
  194. if (hasAudio && !audio_buffer_full && audio_frame->isValid() &&
  195. audio->getPCMF(*audio_frame, pcm, num_decoded_samples) && num_decoded_samples > 0) {
  196. const int mixed = mix_callback(mix_udata, pcm, num_decoded_samples);
  197. if (mixed != num_decoded_samples) {
  198. samples_offset = mixed;
  199. audio_buffer_full = true;
  200. }
  201. }
  202. WebMFrame *video_frame;
  203. if (video_frames_pos >= video_frames_capacity) {
  204. WebMFrame **video_frames_new = (WebMFrame **)memrealloc(video_frames, ++video_frames_capacity * sizeof(void *));
  205. ERR_FAIL_COND(!video_frames_new); //Out of memory
  206. (video_frames = video_frames_new)[video_frames_capacity - 1] = memnew(WebMFrame);
  207. }
  208. video_frame = video_frames[video_frames_pos];
  209. if (!webm->readFrame(video_frame, audio_frame)) { //This will invalidate frames
  210. break; //Can't demux, EOS?
  211. }
  212. if (video_frame->isValid()) {
  213. ++video_frames_pos;
  214. }
  215. };
  216. bool video_frame_done = false;
  217. while (video_frames_pos > 0 && !video_frame_done) {
  218. WebMFrame *video_frame = video_frames[0];
  219. // It seems VPXDecoder::decode has to be executed even though we might skip this frame
  220. if (video->decode(*video_frame)) {
  221. VPXDecoder::IMAGE_ERROR err;
  222. VPXDecoder::Image image;
  223. if (should_process(*video_frame)) {
  224. if ((err = video->getImage(image)) != VPXDecoder::NO_FRAME) {
  225. if (err == VPXDecoder::NO_ERROR && image.w == webm->getWidth() && image.h == webm->getHeight()) {
  226. uint8_t *w = frame_data.ptrw();
  227. bool converted = false;
  228. if (image.chromaShiftW == 0 && image.chromaShiftH == 0 && image.cs == VPX_CS_SRGB) {
  229. uint8_t *wp = w;
  230. unsigned char *rRow = image.planes[2];
  231. unsigned char *gRow = image.planes[0];
  232. unsigned char *bRow = image.planes[1];
  233. for (int i = 0; i < image.h; i++) {
  234. for (int j = 0; j < image.w; j++) {
  235. *wp++ = rRow[j];
  236. *wp++ = gRow[j];
  237. *wp++ = bRow[j];
  238. *wp++ = 255;
  239. }
  240. rRow += image.linesize[2];
  241. gRow += image.linesize[0];
  242. bRow += image.linesize[1];
  243. }
  244. converted = true;
  245. } else if (image.chromaShiftW == 1 && image.chromaShiftH == 1) {
  246. yuv420_2_rgb8888(w, image.planes[0], image.planes[1], image.planes[2], image.w, image.h, image.linesize[0], image.linesize[1], image.w << 2);
  247. //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);
  248. converted = true;
  249. } else if (image.chromaShiftW == 1 && image.chromaShiftH == 0) {
  250. yuv422_2_rgb8888(w, image.planes[0], image.planes[1], image.planes[2], image.w, image.h, image.linesize[0], image.linesize[1], image.w << 2);
  251. //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);
  252. converted = true;
  253. } else if (image.chromaShiftW == 0 && image.chromaShiftH == 0) {
  254. yuv444_2_rgb8888(w, image.planes[0], image.planes[1], image.planes[2], image.w, image.h, image.linesize[0], image.linesize[1], image.w << 2);
  255. //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);
  256. converted = true;
  257. } else if (image.chromaShiftW == 2 && image.chromaShiftH == 0) {
  258. //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);
  259. //converted = true;
  260. }
  261. if (converted) {
  262. Ref<Image> img = memnew(Image(image.w, image.h, 0, Image::FORMAT_RGBA8, frame_data));
  263. texture->update(img); //Zero copy send to visual server
  264. video_frame_done = true;
  265. }
  266. }
  267. }
  268. }
  269. }
  270. video_pos = video_frame->time;
  271. memmove(video_frames, video_frames + 1, (--video_frames_pos) * sizeof(void *));
  272. video_frames[video_frames_pos] = video_frame;
  273. }
  274. if (video_frames_pos == 0 && webm->isEOS()) {
  275. stop();
  276. }
  277. }
  278. void VideoStreamPlaybackWebm::set_mix_callback(VideoStreamPlayback::AudioMixCallback p_callback, void *p_userdata) {
  279. mix_callback = p_callback;
  280. mix_udata = p_userdata;
  281. }
  282. int VideoStreamPlaybackWebm::get_channels() const {
  283. if (audio) {
  284. return webm->getChannels();
  285. }
  286. return 0;
  287. }
  288. int VideoStreamPlaybackWebm::get_mix_rate() const {
  289. if (audio) {
  290. return webm->getSampleRate();
  291. }
  292. return 0;
  293. }
  294. inline bool VideoStreamPlaybackWebm::has_enough_video_frames() const {
  295. if (video_frames_pos > 0) {
  296. // FIXME: AudioServer output latency was fixed in af9bb0e, previously it used to
  297. // systematically return 0. Now that it gives a proper latency, it broke this
  298. // code where the delay compensation likely never really worked.
  299. //const double audio_delay = AudioServer::get_singleton()->get_output_latency();
  300. const double video_time = video_frames[video_frames_pos - 1]->time;
  301. return video_time >= time + /* audio_delay + */ delay_compensation;
  302. }
  303. return false;
  304. }
  305. bool VideoStreamPlaybackWebm::should_process(WebMFrame &video_frame) {
  306. // FIXME: AudioServer output latency was fixed in af9bb0e, previously it used to
  307. // systematically return 0. Now that it gives a proper latency, it broke this
  308. // code where the delay compensation likely never really worked.
  309. //const double audio_delay = AudioServer::get_singleton()->get_output_latency();
  310. return video_frame.time >= time + /* audio_delay + */ delay_compensation;
  311. }
  312. void VideoStreamPlaybackWebm::delete_pointers() {
  313. if (pcm) {
  314. memfree(pcm);
  315. }
  316. if (audio_frame) {
  317. memdelete(audio_frame);
  318. }
  319. if (video_frames) {
  320. for (int i = 0; i < video_frames_capacity; ++i) {
  321. memdelete(video_frames[i]);
  322. }
  323. memfree(video_frames);
  324. }
  325. if (video) {
  326. memdelete(video);
  327. }
  328. if (audio) {
  329. memdelete(audio);
  330. }
  331. if (webm) {
  332. memdelete(webm);
  333. }
  334. }
  335. /**/
  336. VideoStreamWebm::VideoStreamWebm() {}
  337. Ref<VideoStreamPlayback> VideoStreamWebm::instance_playback() {
  338. Ref<VideoStreamPlaybackWebm> pb = memnew(VideoStreamPlaybackWebm);
  339. pb->set_audio_track(audio_track);
  340. if (pb->open_file(file)) {
  341. return pb;
  342. }
  343. return nullptr;
  344. }
  345. void VideoStreamWebm::set_file(const String &p_file) {
  346. file = p_file;
  347. }
  348. String VideoStreamWebm::get_file() {
  349. return file;
  350. }
  351. void VideoStreamWebm::_bind_methods() {
  352. ClassDB::bind_method(D_METHOD("set_file", "file"), &VideoStreamWebm::set_file);
  353. ClassDB::bind_method(D_METHOD("get_file"), &VideoStreamWebm::get_file);
  354. ADD_PROPERTY(PropertyInfo(Variant::STRING, "file", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "set_file", "get_file");
  355. }
  356. void VideoStreamWebm::set_audio_track(int p_track) {
  357. audio_track = p_track;
  358. }
  359. ////////////
  360. RES ResourceFormatLoaderWebm::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) {
  361. FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
  362. if (!f) {
  363. if (r_error) {
  364. *r_error = ERR_CANT_OPEN;
  365. }
  366. return RES();
  367. }
  368. VideoStreamWebm *stream = memnew(VideoStreamWebm);
  369. stream->set_file(p_path);
  370. Ref<VideoStreamWebm> webm_stream = Ref<VideoStreamWebm>(stream);
  371. if (r_error) {
  372. *r_error = OK;
  373. }
  374. f->close();
  375. memdelete(f);
  376. return webm_stream;
  377. }
  378. void ResourceFormatLoaderWebm::get_recognized_extensions(List<String> *p_extensions) const {
  379. p_extensions->push_back("webm");
  380. }
  381. bool ResourceFormatLoaderWebm::handles_type(const String &p_type) const {
  382. return ClassDB::is_parent_class(p_type, "VideoStream");
  383. }
  384. String ResourceFormatLoaderWebm::get_resource_type(const String &p_path) const {
  385. String el = p_path.get_extension().to_lower();
  386. if (el == "webm") {
  387. return "VideoStreamWebm";
  388. }
  389. return "";
  390. }