Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

video-source.ts 9.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. /*
  2. * encantar.js
  3. * GPU-accelerated Augmented Reality for the web
  4. * Copyright (C) 2022-2024 Alexandre Martins <alemartf(at)gmail.com>
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Lesser General Public License as published
  8. * by the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. *
  19. * video-source.ts
  20. * HTMLVideoElement-based source of data
  21. */
  22. import Speedy from 'speedy-vision';
  23. import { SpeedyMedia } from 'speedy-vision/types/core/speedy-media';
  24. import { SpeedyPromise } from 'speedy-vision/types/core/speedy-promise';
  25. import { Utils, Nullable } from '../utils/utils';
  26. import { IllegalOperationError, NotSupportedError, TimeoutError } from '../utils/errors';
  27. import { Source } from './source';
  28. /** A message to be displayed if a video can't autoplay and user interaction is required */
  29. const ALERT_MESSAGE = 'Tap on the screen to start';
  30. /** Whether or not we have displayed the ALERT_MESSAGE */
  31. let displayedAlertMessage = false;
  32. /**
  33. * HTMLVideoElement-based source of data
  34. */
  35. export class VideoSource implements Source
  36. {
  37. /** video element */
  38. private _video: HTMLVideoElement;
  39. /** media source */
  40. protected _media: Nullable<SpeedyMedia>;
  41. /**
  42. * Constructor
  43. */
  44. constructor(video: HTMLVideoElement)
  45. {
  46. Utils.assert(video instanceof HTMLVideoElement, 'Expected a video element');
  47. this._video = video;
  48. this._media = null;
  49. }
  50. /**
  51. * A type-identifier of the source of data
  52. * @internal
  53. */
  54. get _type(): string
  55. {
  56. return 'video';
  57. }
  58. /**
  59. * Get media
  60. * @internal
  61. */
  62. get _internalMedia(): SpeedyMedia
  63. {
  64. if(this._media == null)
  65. throw new IllegalOperationError(`The media of the source of data isn't loaded`);
  66. return this._media;
  67. }
  68. /**
  69. * Stats related to this source of data
  70. * @internal
  71. */
  72. get _stats(): string
  73. {
  74. const media = this._media;
  75. if(media != null)
  76. return `${media.width}x${media.height} video`;
  77. else
  78. return 'uninitialized video';
  79. }
  80. /**
  81. * Initialize this source of data
  82. * @returns a promise that resolves as soon as this source of data is initialized
  83. * @internal
  84. */
  85. _init(): SpeedyPromise<void>
  86. {
  87. Utils.log(`Initializing ${this._type} source...`);
  88. // prepare the video before loading the SpeedyMedia!
  89. return this._prepareVideo(this._video).then(video => {
  90. Utils.log('The video is prepared');
  91. return Speedy.load(video).then(media => {
  92. Utils.log(`Source of data is a ${media.width}x${media.height} ${this._type}`);
  93. this._media = media;
  94. });
  95. });
  96. }
  97. /**
  98. * Release this source of data
  99. * @returns a promise that resolves as soon as this source of data is released
  100. * @internal
  101. */
  102. _release(): SpeedyPromise<void>
  103. {
  104. if(this._media)
  105. this._media.release();
  106. this._media = null;
  107. return Speedy.Promise.resolve();
  108. }
  109. /**
  110. * Handle browser-specific quirks for <video> elements
  111. * @param video a video element
  112. * @returns a promise that resolves to the input video
  113. */
  114. private _prepareVideo(video: HTMLVideoElement): SpeedyPromise<HTMLVideoElement>
  115. {
  116. // WebKit <video> policies for iOS:
  117. // https://webkit.org/blog/6784/new-video-policies-for-ios/
  118. // required on iOS; nice to have in all browsers
  119. video.setAttribute('playsinline', '');
  120. // handle autoplay
  121. return this._handleAutoPlay(video).then(video => {
  122. // handle WebKit quirks
  123. if(Utils.isWebKit()) {
  124. // on Epiphany 45, a hidden <video> shows up as a black screen when copied to a canvas
  125. // on iOS 15.2-17.3, this hack doesn't seem necessary, but works okay
  126. if(video.hidden) {
  127. video.hidden = false;
  128. video.style.setProperty('opacity', '0');
  129. video.style.setProperty('position', 'fixed'); // make sure that it's visible on-screen
  130. video.style.setProperty('left', '0');
  131. video.style.setProperty('top', '0');
  132. //video.style.setProperty('display', 'none'); // doesn't work. Same as video.hidden
  133. //video.style.setProperty('visibility', 'hidden'); // doesn't work either
  134. }
  135. }
  136. // done
  137. return video;
  138. });
  139. }
  140. /**
  141. * Handle browser-specific quirks for videos marked with autoplay
  142. * @param video a <video> marked with autoplay
  143. * @returns a promise that resolves to the input video
  144. */
  145. private _handleAutoPlay(video: HTMLVideoElement): SpeedyPromise<HTMLVideoElement>
  146. {
  147. // Autoplay guide: https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide
  148. // Chrome policy: https://developer.chrome.com/blog/autoplay/
  149. // WebKit policy: https://webkit.org/blog/7734/auto-play-policy-changes-for-macos/
  150. // nothing to do?
  151. if(!video.autoplay)
  152. return Speedy.Promise.resolve(video);
  153. // videos marked with autoplay should be muted
  154. if(!video.muted) {
  155. Utils.warning('Videos marked with autoplay should be muted', video);
  156. video.muted = true;
  157. }
  158. // the browser may not honor the autoplay attribute if the video is not
  159. // visible on-screen. So, let's try to play the video in any case.
  160. return this._waitUntilPlayable(video).then(video => {
  161. // try to play the video
  162. const promise = video.play();
  163. // handle older browsers
  164. if(promise === undefined)
  165. return video;
  166. // resolve if successful
  167. return new Speedy.Promise<HTMLVideoElement>((resolve, reject) => {
  168. promise.then(() => resolve(video), error => {
  169. // can't play the video
  170. Utils.error(`Can't autoplay video!`, error, video);
  171. // autoplay is blocked for some reason
  172. if(error.name == 'NotAllowedError') {
  173. Utils.warning('Tip: allow manual playback');
  174. if(Utils.isIOS())
  175. Utils.warning('Is low power mode on?');
  176. // User interaction is required to play the video. We can
  177. // solve this here (easy and convenient to do) or at the
  178. // application layer (for a better user experience). If the
  179. // latter is preferred, just disable autoplay and play the
  180. // video programatically.
  181. if(video.hidden || !video.controls || video.parentNode === null) {
  182. // this is added for convenience
  183. document.body.addEventListener('pointerdown', () => video.play());
  184. // ask only once for user interaction
  185. if(!displayedAlertMessage) {
  186. alert(ALERT_MESSAGE);
  187. displayedAlertMessage = true;
  188. }
  189. // XXX what if the Session mode is inline? In this
  190. // case, this convenience code may be undesirable.
  191. // A workaround is to disable autoplay.
  192. }
  193. /*else {
  194. // play the video after the first interaction with the page
  195. const polling = setInterval(() => {
  196. video.play().then(() => clearInterval(polling));
  197. }, 500);
  198. }*/
  199. }
  200. // unsupported media source
  201. else if(error.name == 'NotSupportedError') {
  202. reject(new NotSupportedError('Unsupported video format', error));
  203. return;
  204. }
  205. // done
  206. resolve(video);
  207. });
  208. });
  209. });
  210. }
  211. /**
  212. * Wait for the input video to be playable
  213. * @param video
  214. * @returns a promise that resolves to the input video when it can be played
  215. */
  216. private _waitUntilPlayable(video: HTMLVideoElement): SpeedyPromise<HTMLVideoElement>
  217. {
  218. const TIMEOUT = 15000, INTERVAL = 500;
  219. if(video.readyState >= 3)
  220. return Speedy.Promise.resolve(video);
  221. return new Speedy.Promise<HTMLVideoElement>((resolve, reject) => {
  222. let ms = 0, t = setInterval(() => {
  223. //if(video.readyState >= 4) { // canplaythrough (may timeout on slow connections)
  224. if(video.readyState >= 3) {
  225. clearInterval(t);
  226. resolve(video);
  227. }
  228. else if((ms += INTERVAL) >= TIMEOUT) {
  229. clearInterval(t);
  230. reject(new TimeoutError('The video took too long to load'));
  231. }
  232. }, INTERVAL);
  233. });
  234. }
  235. }