video_stream_webm.cpp 14 KB

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