Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

video-source.ts 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /*
  2. * MARTINS.js Free Edition
  3. * GPU-accelerated Augmented Reality for the web
  4. * Copyright (C) 2022 Alexandre Martins <alemartf(at)gmail.com>
  5. * https://github.com/alemart/martins-js
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Affero General Public License version 3
  9. * as published by the Free Software Foundation.
  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 Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero 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 _data(): 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', 'absolute');
  130. //video.style.setProperty('display', 'none'); // doesn't work. Same as video.hidden
  131. //video.style.setProperty('visibility', 'hidden'); // doesn't work either
  132. }
  133. }
  134. // done
  135. return video;
  136. });
  137. }
  138. /**
  139. * Handle browser-specific quirks for videos marked with autoplay
  140. * @param video a <video> marked with autoplay
  141. * @returns a promise that resolves to the input video
  142. */
  143. private _handleAutoPlay(video: HTMLVideoElement): SpeedyPromise<HTMLVideoElement>
  144. {
  145. // Autoplay guide: https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide
  146. // Chrome policy: https://developer.chrome.com/blog/autoplay/
  147. // WebKit policy: https://webkit.org/blog/7734/auto-play-policy-changes-for-macos/
  148. // nothing to do?
  149. if(!video.autoplay)
  150. return Speedy.Promise.resolve(video);
  151. // videos marked with autoplay should be muted
  152. if(!video.muted) {
  153. Utils.warning('Videos marked with autoplay should be muted', video);
  154. video.muted = true;
  155. }
  156. // the browser may not honor the autoplay attribute if the video is not
  157. // visible on-screen. So, let's try to play the video in any case.
  158. return this._waitUntilPlayable(video).then(video => {
  159. // try to play the video
  160. const promise = video.play();
  161. // handle older browsers
  162. if(promise === undefined)
  163. return video;
  164. // resolve if successful
  165. return new Speedy.Promise<HTMLVideoElement>((resolve, reject) => {
  166. promise.then(() => resolve(video), error => {
  167. // can't play the video
  168. Utils.error(`Can't autoplay video!`, error, video);
  169. // autoplay is blocked for some reason
  170. if(error.name == 'NotAllowedError') {
  171. Utils.warning('Tip: allow manual playback');
  172. if(Utils.isIOS())
  173. Utils.warning('Is low power mode on?');
  174. // User interaction is required to play the video. We can
  175. // solve this here (easy and convenient to do) or at the
  176. // application layer (for a better user experience). If the
  177. // latter is preferred, just disable autoplay and play the
  178. // video programatically.
  179. if(video.hidden || !video.controls || video.parentNode === null) {
  180. // this is added for convenience
  181. document.body.addEventListener('pointerdown', () => video.play());
  182. // ask only once for user interaction
  183. if(!displayedAlertMessage) {
  184. alert(ALERT_MESSAGE);
  185. displayedAlertMessage = true;
  186. }
  187. // XXX what if the Session mode is inline? In this
  188. // case, this convenience code may be undesirable.
  189. // A workaround is to disable autoplay.
  190. }
  191. /*else {
  192. // play the video after the first interaction with the page
  193. const polling = setInterval(() => {
  194. video.play().then(() => clearInterval(polling));
  195. }, 500);
  196. }*/
  197. }
  198. // unsupported media source
  199. else if(error.name == 'NotSupportedError') {
  200. reject(new NotSupportedError('Unsupported video format', error));
  201. return;
  202. }
  203. // done
  204. resolve(video);
  205. });
  206. });
  207. });
  208. }
  209. /**
  210. * Wait for the input video to be playable
  211. * @param video
  212. * @returns a promise that resolves to the input video when it can be played through to the end
  213. */
  214. private _waitUntilPlayable(video: HTMLVideoElement): SpeedyPromise<HTMLVideoElement>
  215. {
  216. const TIMEOUT = 15000, INTERVAL = 500;
  217. if(video.readyState >= 4)
  218. return Speedy.Promise.resolve(video);
  219. return new Speedy.Promise<HTMLVideoElement>((resolve, reject) => {
  220. let ms = 0, t = setInterval(() => {
  221. if(video.readyState >= 4) { // canplaythrough
  222. clearInterval(t);
  223. resolve(video);
  224. }
  225. else if((ms += INTERVAL) >= TIMEOUT) {
  226. clearInterval(t);
  227. reject(new TimeoutError('The video took too long to load'));
  228. }
  229. }, INTERVAL);
  230. });
  231. }
  232. }