videoTexture.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. import { Observable } from "../../Misc/observable";
  2. import { Tools } from "../../Misc/tools";
  3. import { Logger } from "../../Misc/logger";
  4. import { Nullable } from "../../types";
  5. import { Scene } from "../../scene";
  6. import { Engine } from "../../Engines/engine";
  7. import { Texture } from "../../Materials/Textures/texture";
  8. import "../../Engines/Extensions/engine.videoTexture";
  9. import "../../Engines/Extensions/engine.dynamicTexture";
  10. /**
  11. * Settings for finer control over video usage
  12. */
  13. export interface VideoTextureSettings {
  14. /**
  15. * Applies `autoplay` to video, if specified
  16. */
  17. autoPlay?: boolean;
  18. /**
  19. * Applies `loop` to video, if specified
  20. */
  21. loop?: boolean;
  22. /**
  23. * Automatically updates internal texture from video at every frame in the render loop
  24. */
  25. autoUpdateTexture: boolean;
  26. /**
  27. * Image src displayed during the video loading or until the user interacts with the video.
  28. */
  29. poster?: string;
  30. }
  31. /**
  32. * If you want to display a video in your scene, this is the special texture for that.
  33. * This special texture works similar to other textures, with the exception of a few parameters.
  34. * @see https://doc.babylonjs.com/how_to/video_texture
  35. */
  36. export class VideoTexture extends Texture {
  37. /**
  38. * Tells whether textures will be updated automatically or user is required to call `updateTexture` manually
  39. */
  40. public readonly autoUpdateTexture: boolean;
  41. /**
  42. * The video instance used by the texture internally
  43. */
  44. public readonly video: HTMLVideoElement;
  45. private _onUserActionRequestedObservable: Nullable<Observable<Texture>> = null;
  46. /**
  47. * Event triggerd when a dom action is required by the user to play the video.
  48. * This happens due to recent changes in browser policies preventing video to auto start.
  49. */
  50. public get onUserActionRequestedObservable(): Observable<Texture> {
  51. if (!this._onUserActionRequestedObservable) {
  52. this._onUserActionRequestedObservable = new Observable<Texture>();
  53. }
  54. return this._onUserActionRequestedObservable;
  55. }
  56. private _generateMipMaps: boolean;
  57. private _engine: Engine;
  58. private _stillImageCaptured = false;
  59. private _displayingPosterTexture = false;
  60. private _settings: VideoTextureSettings;
  61. private _createInternalTextureOnEvent: string;
  62. private _frameId = -1;
  63. private _currentSrc: Nullable<string | string[] | HTMLVideoElement> = null;
  64. /**
  65. * Creates a video texture.
  66. * If you want to display a video in your scene, this is the special texture for that.
  67. * This special texture works similar to other textures, with the exception of a few parameters.
  68. * @see https://doc.babylonjs.com/how_to/video_texture
  69. * @param name optional name, will detect from video source, if not defined
  70. * @param src can be used to provide an url, array of urls or an already setup HTML video element.
  71. * @param scene is obviously the current scene.
  72. * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  73. * @param invertY is false by default but can be used to invert video on Y axis
  74. * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  75. * @param settings allows finer control over video usage
  76. */
  77. constructor(
  78. name: Nullable<string>,
  79. src: string | string[] | HTMLVideoElement,
  80. scene: Nullable<Scene>,
  81. generateMipMaps = false,
  82. invertY = false,
  83. samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE,
  84. settings: VideoTextureSettings = {
  85. autoPlay: true,
  86. loop: true,
  87. autoUpdateTexture: true,
  88. }
  89. ) {
  90. super(null, scene, !generateMipMaps, invertY);
  91. this._engine = this.getScene()!.getEngine();
  92. this._generateMipMaps = generateMipMaps;
  93. this._initialSamplingMode = samplingMode;
  94. this.autoUpdateTexture = settings.autoUpdateTexture;
  95. this._currentSrc = src;
  96. this.name = name || this._getName(src);
  97. this.video = this._getVideo(src);
  98. this._settings = settings;
  99. if (settings.poster) {
  100. this.video.poster = settings.poster;
  101. }
  102. if (settings.autoPlay !== undefined) {
  103. this.video.autoplay = settings.autoPlay;
  104. }
  105. if (settings.loop !== undefined) {
  106. this.video.loop = settings.loop;
  107. }
  108. this.video.setAttribute("playsinline", "");
  109. this.video.addEventListener("paused", this._updateInternalTexture);
  110. this.video.addEventListener("seeked", this._updateInternalTexture);
  111. this.video.addEventListener("emptied", this.reset);
  112. this._createInternalTextureOnEvent = (settings.poster && !settings.autoPlay) ? "play" : "canplay";
  113. this.video.addEventListener(this._createInternalTextureOnEvent, this._createInternalTexture);
  114. const videoHasEnoughData = (this.video.readyState >= this.video.HAVE_CURRENT_DATA);
  115. if (settings.poster &&
  116. (!settings.autoPlay || !videoHasEnoughData)) {
  117. this._texture = this._engine.createTexture(settings.poster!, false, !this.invertY, scene);
  118. this._displayingPosterTexture = true;
  119. }
  120. else if (videoHasEnoughData) {
  121. this._createInternalTexture();
  122. }
  123. }
  124. private _getName(src: string | string[] | HTMLVideoElement): string {
  125. if (src instanceof HTMLVideoElement) {
  126. return src.currentSrc;
  127. }
  128. if (typeof src === "object") {
  129. return src.toString();
  130. }
  131. return src;
  132. }
  133. private _getVideo(src: string | string[] | HTMLVideoElement): HTMLVideoElement {
  134. if (src instanceof HTMLVideoElement) {
  135. Tools.SetCorsBehavior(src.currentSrc, src);
  136. return src;
  137. }
  138. const video: HTMLVideoElement = document.createElement("video");
  139. if (typeof src === "string") {
  140. Tools.SetCorsBehavior(src, video);
  141. video.src = src;
  142. } else {
  143. Tools.SetCorsBehavior(src[0], video);
  144. src.forEach((url) => {
  145. const source = document.createElement("source");
  146. source.src = url;
  147. video.appendChild(source);
  148. });
  149. }
  150. return video;
  151. }
  152. private _createInternalTexture = (): void => {
  153. if (this._texture != null) {
  154. if (this._displayingPosterTexture) {
  155. this._texture.dispose();
  156. this._displayingPosterTexture = false;
  157. }
  158. else {
  159. return;
  160. }
  161. }
  162. if (!this._engine.needPOTTextures ||
  163. (Tools.IsExponentOfTwo(this.video.videoWidth) && Tools.IsExponentOfTwo(this.video.videoHeight))) {
  164. this.wrapU = Texture.WRAP_ADDRESSMODE;
  165. this.wrapV = Texture.WRAP_ADDRESSMODE;
  166. } else {
  167. this.wrapU = Texture.CLAMP_ADDRESSMODE;
  168. this.wrapV = Texture.CLAMP_ADDRESSMODE;
  169. this._generateMipMaps = false;
  170. }
  171. this._texture = this._engine.createDynamicTexture(
  172. this.video.videoWidth,
  173. this.video.videoHeight,
  174. this._generateMipMaps,
  175. this.samplingMode
  176. );
  177. if (!this.video.autoplay && !this._settings.poster) {
  178. let oldHandler = this.video.onplaying;
  179. let error = false;
  180. let oldMuted = this.video.muted;
  181. this.video.muted = true;
  182. this.video.onplaying = () => {
  183. this.video.muted = oldMuted;
  184. this.video.onplaying = oldHandler;
  185. this._texture!.isReady = true;
  186. this._updateInternalTexture();
  187. if (!error) {
  188. this.video.pause();
  189. }
  190. if (this.onLoadObservable.hasObservers()) {
  191. this.onLoadObservable.notifyObservers(this);
  192. }
  193. };
  194. var playing = this.video.play();
  195. if (playing) {
  196. playing.then(() => {
  197. // Everything is good.
  198. })
  199. .catch(() => {
  200. error = true;
  201. // On Chrome for instance, new policies might prevent playing without user interaction.
  202. if (this._onUserActionRequestedObservable && this._onUserActionRequestedObservable.hasObservers()) {
  203. this._onUserActionRequestedObservable.notifyObservers(this);
  204. }
  205. });
  206. }
  207. else {
  208. this.video.onplaying = oldHandler;
  209. this._texture.isReady = true;
  210. this._updateInternalTexture();
  211. if (this.onLoadObservable.hasObservers()) {
  212. this.onLoadObservable.notifyObservers(this);
  213. }
  214. }
  215. }
  216. else {
  217. this._texture.isReady = true;
  218. this._updateInternalTexture();
  219. if (this.onLoadObservable.hasObservers()) {
  220. this.onLoadObservable.notifyObservers(this);
  221. }
  222. }
  223. }
  224. private reset = (): void => {
  225. if (this._texture == null) {
  226. return;
  227. }
  228. if (!this._displayingPosterTexture) {
  229. this._texture.dispose();
  230. this._texture = null;
  231. }
  232. }
  233. /**
  234. * @hidden Internal method to initiate `update`.
  235. */
  236. public _rebuild(): void {
  237. this.update();
  238. }
  239. /**
  240. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  241. */
  242. public update(): void {
  243. if (!this.autoUpdateTexture) {
  244. // Expecting user to call `updateTexture` manually
  245. return;
  246. }
  247. this.updateTexture(true);
  248. }
  249. /**
  250. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  251. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  252. */
  253. public updateTexture(isVisible: boolean): void {
  254. if (!isVisible) {
  255. return;
  256. }
  257. if (this.video.paused && this._stillImageCaptured) {
  258. return;
  259. }
  260. this._stillImageCaptured = true;
  261. this._updateInternalTexture();
  262. }
  263. protected _updateInternalTexture = (): void => {
  264. if (this._texture == null || !this._texture.isReady) {
  265. return;
  266. }
  267. if (this.video.readyState < this.video.HAVE_CURRENT_DATA) {
  268. return;
  269. }
  270. if (this._displayingPosterTexture) {
  271. return;
  272. }
  273. let frameId = this.getScene()!.getFrameId();
  274. if (this._frameId === frameId) {
  275. return;
  276. }
  277. this._frameId = frameId;
  278. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  279. }
  280. /**
  281. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  282. * @param url New url.
  283. */
  284. public updateURL(url: string): void {
  285. this.video.src = url;
  286. this._currentSrc = url;
  287. }
  288. /**
  289. * Clones the texture.
  290. * @returns the cloned texture
  291. */
  292. public clone(): VideoTexture {
  293. return new VideoTexture(this.name,
  294. this._currentSrc!,
  295. this.getScene(),
  296. this._generateMipMaps,
  297. this.invertY,
  298. this.samplingMode,
  299. this._settings);
  300. }
  301. /**
  302. * Dispose the texture and release its associated resources.
  303. */
  304. public dispose(): void {
  305. super.dispose();
  306. this._currentSrc = null;
  307. if (this._onUserActionRequestedObservable) {
  308. this._onUserActionRequestedObservable.clear();
  309. this._onUserActionRequestedObservable = null;
  310. }
  311. this.video.removeEventListener(this._createInternalTextureOnEvent, this._createInternalTexture);
  312. this.video.removeEventListener("paused", this._updateInternalTexture);
  313. this.video.removeEventListener("seeked", this._updateInternalTexture);
  314. this.video.removeEventListener("emptied", this.reset);
  315. this.video.pause();
  316. }
  317. /**
  318. * Creates a video texture straight from a stream.
  319. * @param scene Define the scene the texture should be created in
  320. * @param stream Define the stream the texture should be created from
  321. * @returns The created video texture as a promise
  322. */
  323. public static CreateFromStreamAsync(scene: Scene, stream: MediaStream): Promise<VideoTexture> {
  324. var video = document.createElement("video");
  325. video.setAttribute('autoplay', '');
  326. video.setAttribute('muted', 'true');
  327. video.setAttribute('playsinline', '');
  328. video.muted = true;
  329. if (video.mozSrcObject !== undefined) {
  330. // hack for Firefox < 19
  331. video.mozSrcObject = stream;
  332. } else {
  333. if (typeof video.srcObject == "object") {
  334. video.srcObject = stream;
  335. } else {
  336. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  337. video.src = (window.URL && window.URL.createObjectURL(stream));
  338. }
  339. }
  340. return new Promise<VideoTexture>((resolve) => {
  341. let onPlaying = () => {
  342. resolve(new VideoTexture("video", video, scene, true, true));
  343. video.removeEventListener("playing", onPlaying);
  344. };
  345. video.addEventListener("playing", onPlaying);
  346. video.play();
  347. });
  348. }
  349. /**
  350. * Creates a video texture straight from your WebCam video feed.
  351. * @param scene Define the scene the texture should be created in
  352. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  353. * @param audioConstaints Define the audio constraints to use to create the web cam feed from WebRTC
  354. * @returns The created video texture as a promise
  355. */
  356. public static CreateFromWebCamAsync(
  357. scene: Scene,
  358. constraints: {
  359. minWidth: number;
  360. maxWidth: number;
  361. minHeight: number;
  362. maxHeight: number;
  363. deviceId: string;
  364. } & MediaTrackConstraints,
  365. audioConstaints: boolean | MediaTrackConstraints = false
  366. ): Promise<VideoTexture> {
  367. var constraintsDeviceId;
  368. if (constraints && constraints.deviceId) {
  369. constraintsDeviceId = {
  370. exact: constraints.deviceId,
  371. };
  372. }
  373. if (navigator.mediaDevices) {
  374. return navigator.mediaDevices.getUserMedia({
  375. video: constraints,
  376. audio: audioConstaints
  377. })
  378. .then((stream) => {
  379. return this.CreateFromStreamAsync(scene, stream);
  380. });
  381. }
  382. else {
  383. navigator.getUserMedia =
  384. navigator.getUserMedia ||
  385. navigator.webkitGetUserMedia ||
  386. navigator.mozGetUserMedia ||
  387. navigator.msGetUserMedia;
  388. if (navigator.getUserMedia) {
  389. navigator.getUserMedia(
  390. {
  391. video: {
  392. deviceId: constraintsDeviceId,
  393. width: {
  394. min: (constraints && constraints.minWidth) || 256,
  395. max: (constraints && constraints.maxWidth) || 640,
  396. },
  397. height: {
  398. min: (constraints && constraints.minHeight) || 256,
  399. max: (constraints && constraints.maxHeight) || 480,
  400. },
  401. },
  402. audio: audioConstaints
  403. },
  404. (stream: any) => {
  405. return this.CreateFromStreamAsync(scene, stream);
  406. },
  407. function(e: MediaStreamError) {
  408. Logger.Error(e.name);
  409. }
  410. );
  411. }
  412. }
  413. return Promise.reject("No support for userMedia on this device");
  414. }
  415. /**
  416. * Creates a video texture straight from your WebCam video feed.
  417. * @param scene Define the scene the texture should be created in
  418. * @param onReady Define a callback to triggered once the texture will be ready
  419. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  420. * @param audioConstaints Define the audio constraints to use to create the web cam feed from WebRTC
  421. */
  422. public static CreateFromWebCam(
  423. scene: Scene,
  424. onReady: (videoTexture: VideoTexture) => void,
  425. constraints: {
  426. minWidth: number;
  427. maxWidth: number;
  428. minHeight: number;
  429. maxHeight: number;
  430. deviceId: string;
  431. } & MediaTrackConstraints,
  432. audioConstaints: boolean | MediaTrackConstraints = false
  433. ): void {
  434. this.CreateFromWebCamAsync(scene, constraints, audioConstaints)
  435. .then(function(videoTexture) {
  436. if (onReady) {
  437. onReady(videoTexture);
  438. }
  439. })
  440. .catch(function(err) {
  441. Logger.Error(err.name);
  442. });
  443. }
  444. }