video_stream_theoraplayer.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. /*************************************************************************/
  2. /* video_stream.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* http://www.godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */
  9. /* */
  10. /* Permission is hereby granted, free of charge, to any person obtaining */
  11. /* a copy of this software and associated documentation files (the */
  12. /* "Software"), to deal in the Software without restriction, including */
  13. /* without limitation the rights to use, copy, modify, merge, publish, */
  14. /* distribute, sublicense, and/or sell copies of the Software, and to */
  15. /* permit persons to whom the Software is furnished to do so, subject to */
  16. /* the following conditions: */
  17. /* */
  18. /* The above copyright notice and this permission notice shall be */
  19. /* included in all copies or substantial portions of the Software. */
  20. /* */
  21. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  22. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  23. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  24. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  25. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  26. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  27. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  28. /*************************************************************************/
  29. #include "video_stream_theoraplayer.h"
  30. #include "core/os/file_access.h"
  31. #include "include/theoraplayer/TheoraPlayer.h"
  32. #include "include/theoraplayer/TheoraTimer.h"
  33. #include "include/theoraplayer/TheoraAudioInterface.h"
  34. #include "include/theoraplayer/TheoraDataSource.h"
  35. #include "include/theoraplayer/TheoraException.h"
  36. #include "core/ring_buffer.h"
  37. #include "core/os/thread_safe.h"
  38. #include "core/globals.h"
  39. static TheoraVideoManager* mgr = NULL;
  40. class TPDataFA : public TheoraDataSource {
  41. FileAccess* fa;
  42. String data_name;
  43. public:
  44. int read(void* output,int nBytes) {
  45. if (!fa)
  46. return -1;
  47. return fa->get_buffer((uint8_t*)output, nBytes);
  48. };
  49. //! returns a string representation of the DataSource, eg 'File: source.ogg'
  50. virtual std::string repr() {
  51. return data_name.utf8().get_data();
  52. };
  53. //! position the source pointer to byte_index from the start of the source
  54. virtual void seek(unsigned long byte_index) {
  55. if (!fa)
  56. return;
  57. fa->seek(byte_index);
  58. };
  59. //! return the size of the stream in bytes
  60. virtual unsigned long size() {
  61. if (!fa)
  62. return 0;
  63. return fa->get_len();
  64. };
  65. //! return the current position of the source pointer
  66. virtual unsigned long tell() {
  67. if (!fa)
  68. return 0;
  69. return fa->get_pos();
  70. };
  71. TPDataFA(const String& p_path) {
  72. fa = FileAccess::open(p_path, FileAccess::READ);
  73. data_name = "File: " + p_path;
  74. };
  75. TPDataFA(FileAccess* p_fa, const String& p_path) {
  76. fa = p_fa;
  77. data_name = "File: " + p_path;
  78. };
  79. ~TPDataFA() {
  80. if (fa)
  81. memdelete(fa);
  82. };
  83. };
  84. class AudioStreamInput : public AudioStreamResampled {
  85. _THREAD_SAFE_CLASS_;
  86. int channels;
  87. int freq;
  88. RID stream_rid;
  89. mutable RingBuffer<float> rb;
  90. int rb_power;
  91. int total_wrote;
  92. bool playing;
  93. bool paused;
  94. public:
  95. virtual void play() {
  96. _THREAD_SAFE_METHOD_
  97. _setup(channels, freq, 256);
  98. stream_rid=AudioServer::get_singleton()->audio_stream_create(get_audio_stream());
  99. AudioServer::get_singleton()->stream_set_active(stream_rid,true);
  100. AudioServer::get_singleton()->stream_set_volume_scale(stream_rid,1);
  101. playing = true;
  102. paused = false;
  103. };
  104. virtual void stop() {
  105. _THREAD_SAFE_METHOD_
  106. AudioServer::get_singleton()->stream_set_active(stream_rid,false);
  107. //_clear_stream();
  108. playing=false;
  109. _clear();
  110. };
  111. virtual bool is_playing() const { return true; };
  112. virtual void set_paused(bool p_paused) { paused = p_paused; };
  113. virtual bool is_paused(bool p_paused) const { return paused; };
  114. virtual void set_loop(bool p_enable) {};
  115. virtual bool has_loop() const { return false; };
  116. virtual float get_length() const { return 0; };
  117. virtual String get_stream_name() const { return "Theora Audio Stream"; };
  118. virtual int get_loop_count() const { return 1; };
  119. virtual float get_pos() const { return 0; };
  120. virtual void seek_pos(float p_time) {};
  121. virtual UpdateMode get_update_mode() const { return UPDATE_THREAD; };
  122. virtual bool _can_mix() const { return true; };
  123. void input(float* p_data, int p_samples) {
  124. _THREAD_SAFE_METHOD_;
  125. //printf("input %i samples from %p\n", p_samples, p_data);
  126. if (rb.space_left() < p_samples) {
  127. rb_power += 1;
  128. rb.resize(rb_power);
  129. }
  130. rb.write(p_data, p_samples);
  131. update(); //update too here for less latency
  132. };
  133. void update() {
  134. _THREAD_SAFE_METHOD_;
  135. int todo = get_todo();
  136. int16_t* buffer = get_write_buffer();
  137. int frames = rb.data_left()/channels;
  138. const int to_write = MIN(todo, frames);
  139. for (int i=0; i<to_write*channels; i++) {
  140. int v = rb.read() * 32767;
  141. int16_t sample = CLAMP(v,-32768,32767);
  142. buffer[i] = sample;
  143. };
  144. write(to_write);
  145. total_wrote += to_write;
  146. };
  147. int get_pending() const {
  148. return rb.data_left();
  149. };
  150. int get_total_wrote() {
  151. return total_wrote - (get_total() - get_todo());
  152. };
  153. AudioStreamInput(int p_channels, int p_freq) {
  154. playing = false;
  155. paused = true;
  156. channels = p_channels;
  157. freq = p_freq;
  158. total_wrote = 0;
  159. rb_power = 22;
  160. rb.resize(rb_power);
  161. };
  162. ~AudioStreamInput() {
  163. stop();
  164. };
  165. };
  166. class TPAudioGodot : public TheoraAudioInterface, TheoraTimer {
  167. Ref<AudioStreamInput> stream;
  168. int sample_count;
  169. int channels;
  170. int freq;
  171. public:
  172. void insertData(float* data, int nSamples) {
  173. stream->input(data, nSamples);
  174. };
  175. TPAudioGodot(TheoraVideoClip* owner, int nChannels, int p_freq)
  176. : TheoraAudioInterface(owner, nChannels, p_freq), TheoraTimer() {
  177. printf("***************** audio interface constructor freq %i\n", p_freq);
  178. channels = nChannels;
  179. freq = p_freq;
  180. stream = Ref<AudioStreamInput>(memnew(AudioStreamInput(nChannels, p_freq)));
  181. stream->play();
  182. sample_count = 0;
  183. owner->setTimer(this);
  184. };
  185. void stop() {
  186. stream->stop();
  187. };
  188. void update(float time_increase)
  189. {
  190. float prev_time = mTime;
  191. //mTime = (float)(stream->get_total_wrote()) / freq;
  192. //mTime = MAX(0,mTime-AudioServer::get_singleton()->get_output_delay());
  193. //mTime = (float)sample_count / channels / freq;
  194. mTime += time_increase;
  195. if (mTime - prev_time > .02) printf("time increase %f secs\n", mTime - prev_time);
  196. //float duration=mClip->getDuration();
  197. //if (mTime > duration) mTime=duration;
  198. //printf("time at timer is %f, %f, samples %i\n", mTime, time_increase, sample_count);
  199. }
  200. };
  201. class TPAudioGodotFactory : public TheoraAudioInterfaceFactory {
  202. public:
  203. TheoraAudioInterface* createInstance(TheoraVideoClip* owner, int nChannels, int freq) {
  204. printf("************** creating audio output\n");
  205. TheoraAudioInterface* ta = new TPAudioGodot(owner, nChannels, freq);
  206. return ta;
  207. };
  208. };
  209. static TPAudioGodotFactory* audio_factory = NULL;
  210. void VideoStreamTheoraplayer::stop() {
  211. playing = false;
  212. if (clip) {
  213. clip->stop();
  214. clip->seek(0);
  215. };
  216. started = true;
  217. };
  218. void VideoStreamTheoraplayer::play() {
  219. if (clip)
  220. playing = true;
  221. };
  222. bool VideoStreamTheoraplayer::is_playing() const {
  223. return playing;
  224. };
  225. void VideoStreamTheoraplayer::set_paused(bool p_paused) {
  226. paused = p_paused;
  227. if (paused) {
  228. clip->pause();
  229. } else {
  230. if (clip && playing && !started)
  231. clip->play();
  232. }
  233. };
  234. bool VideoStreamTheoraplayer::is_paused(bool p_paused) const {
  235. return !playing;
  236. };
  237. void VideoStreamTheoraplayer::set_loop(bool p_enable) {
  238. loop = p_enable;
  239. };
  240. bool VideoStreamTheoraplayer::has_loop() const {
  241. return loop;
  242. };
  243. float VideoStreamTheoraplayer::get_length() const {
  244. if (!clip)
  245. return 0;
  246. return clip->getDuration();
  247. };
  248. float VideoStreamTheoraplayer::get_pos() const {
  249. if (!clip)
  250. return 0;
  251. return clip->getTimer()->getTime();
  252. };
  253. void VideoStreamTheoraplayer::seek_pos(float p_time) {
  254. if (!clip)
  255. return;
  256. clip->seek(p_time);
  257. };
  258. int VideoStreamTheoraplayer::get_pending_frame_count() const {
  259. if (!clip)
  260. return 0;
  261. TheoraVideoFrame* f = clip->getNextFrame();
  262. return f ? 1 : 0;
  263. };
  264. void VideoStreamTheoraplayer::pop_frame(Ref<ImageTexture> p_tex) {
  265. if (!clip)
  266. return;
  267. TheoraVideoFrame* f = clip->getNextFrame();
  268. if (!f) {
  269. return;
  270. };
  271. #ifdef GLES2_ENABLED
  272. // RasterizerGLES2* r = RasterizerGLES2::get_singleton();
  273. // r->_texture_set_data(p_tex, f->mBpp == 3 ? Image::Format_RGB : Image::Format_RGBA, f->mBpp, w, h, f->getBuffer());
  274. #endif
  275. float w=clip->getWidth(),h=clip->getHeight();
  276. int imgsize = w * h * f->mBpp;
  277. int size = f->getStride() * f->getHeight() * f->mBpp;
  278. data.resize(imgsize);
  279. {
  280. DVector<uint8_t>::Write wr = data.write();
  281. uint8_t* ptr = wr.ptr();
  282. copymem(ptr, f->getBuffer(), imgsize);
  283. }
  284. /*
  285. for (int i=0; i<h; i++) {
  286. int dstofs = i * w * f->mBpp;
  287. int srcofs = i * f->getStride() * f->mBpp;
  288. copymem(ptr + dstofs, f->getBuffer() + dstofs, w * f->mBpp);
  289. };
  290. */
  291. Image frame = Image();
  292. frame.create(w, h, 0, f->mBpp == 3 ? Image::FORMAT_RGB : Image::FORMAT_RGBA, data);
  293. clip->popFrame();
  294. if (p_tex->get_width() == 0) {
  295. p_tex->create(frame.get_width(),frame.get_height(),frame.get_format(),Texture::FLAG_VIDEO_SURFACE|Texture::FLAG_FILTER);
  296. p_tex->set_data(frame);
  297. } else {
  298. p_tex->set_data(frame);
  299. };
  300. };
  301. /*
  302. Image VideoStreamTheoraplayer::pop_frame() {
  303. Image ret = frame;
  304. frame = Image();
  305. return ret;
  306. };
  307. */
  308. Image VideoStreamTheoraplayer::peek_frame() const {
  309. return Image();
  310. };
  311. void VideoStreamTheoraplayer::update(float p_time) {
  312. if (!mgr)
  313. return;
  314. if (!clip)
  315. return;
  316. if (!playing || paused)
  317. return;
  318. //printf("video update!\n");
  319. if (started) {
  320. if (clip->getNumReadyFrames() < 2) {
  321. printf("frames not ready, returning!\n");
  322. return;
  323. };
  324. started = false;
  325. //printf("playing clip!\n");
  326. clip->play();
  327. } else if (clip->isDone()) {
  328. playing = false;
  329. };
  330. mgr->update(p_time);
  331. };
  332. void VideoStreamTheoraplayer::set_audio_track(int p_idx) {
  333. audio_track=p_idx;
  334. if (clip)
  335. clip->set_audio_track(audio_track);
  336. }
  337. void VideoStreamTheoraplayer::set_file(const String& p_file) {
  338. FileAccess* f = FileAccess::open(p_file, FileAccess::READ);
  339. if (!f || !f->is_open())
  340. return;
  341. if (!audio_factory) {
  342. audio_factory = memnew(TPAudioGodotFactory);
  343. };
  344. if (mgr == NULL) {
  345. mgr = memnew(TheoraVideoManager);
  346. mgr->setAudioInterfaceFactory(audio_factory);
  347. };
  348. int track = GLOBAL_DEF("theora/audio_track", 0); // hack
  349. if (p_file.find(".mp4") != -1) {
  350. std::string file = p_file.replace("res://", "").utf8().get_data();
  351. clip = mgr->createVideoClip(file, TH_RGBX, 2, false, track);
  352. //clip->set_audio_track(audio_track);
  353. memdelete(f);
  354. } else {
  355. TheoraDataSource* ds = memnew(TPDataFA(f, p_file));
  356. try {
  357. clip = mgr->createVideoClip(ds);
  358. clip->set_audio_track(audio_track);
  359. } catch (_TheoraGenericException e) {
  360. printf("exception ocurred! %s\n", e.repr().c_str());
  361. clip = NULL;
  362. };
  363. };
  364. clip->pause();
  365. started = true;
  366. };
  367. VideoStreamTheoraplayer::~VideoStreamTheoraplayer() {
  368. stop();
  369. //if (mgr) { // this should be a singleton or static or something
  370. // memdelete(mgr);
  371. //};
  372. //mgr = NULL;
  373. if (clip) {
  374. mgr->destroyVideoClip(clip);
  375. clip = NULL;
  376. };
  377. };
  378. VideoStreamTheoraplayer::VideoStreamTheoraplayer() {
  379. //mgr = NULL;
  380. clip = NULL;
  381. started = false;
  382. playing = false;
  383. paused = false;
  384. loop = false;
  385. audio_track=0;
  386. };
  387. RES ResourceFormatLoaderVideoStreamTheoraplayer::load(const String &p_path,const String& p_original_path) {
  388. VideoStreamTheoraplayer *stream = memnew(VideoStreamTheoraplayer);
  389. stream->set_file(p_path);
  390. return Ref<VideoStreamTheoraplayer>(stream);
  391. }
  392. void ResourceFormatLoaderVideoStreamTheoraplayer::get_recognized_extensions(List<String> *p_extensions) const {
  393. p_extensions->push_back("ogm");
  394. p_extensions->push_back("ogv");
  395. p_extensions->push_back("mp4");
  396. }
  397. bool ResourceFormatLoaderVideoStreamTheoraplayer::handles_type(const String& p_type) const {
  398. return p_type=="VideoStream" || p_type == "VideoStreamTheoraplayer";
  399. }
  400. String ResourceFormatLoaderVideoStreamTheoraplayer::get_resource_type(const String &p_path) const {
  401. String exl=p_path.extension().to_lower();
  402. if (exl=="ogm" || exl=="ogv" || exl=="mp4")
  403. return "VideoStream";
  404. return "";
  405. }