Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. return Speedy.load(this._video).then(media => {
  88. Utils.log(`Source of data is a ${media.width}x${media.height} ${this._type}`);
  89. this._media = media;
  90. return this._handleBrowserQuirks(this._video).then(() => void(0));
  91. });
  92. }
  93. /**
  94. * Release this source of data
  95. * @returns a promise that resolves as soon as this source of data is released
  96. * @internal
  97. */
  98. _release(): SpeedyPromise<void>
  99. {
  100. if(this._media)
  101. this._media.release();
  102. this._media = null;
  103. return Speedy.Promise.resolve();
  104. }
  105. /**
  106. * Handle browser-specific quirks for <video> elements
  107. * @param video a video element
  108. * @returns a promise that resolves to the input video
  109. * @internal
  110. */
  111. _handleBrowserQuirks(video: HTMLVideoElement): SpeedyPromise<HTMLVideoElement>
  112. {
  113. // WebKit <video> policies for iOS:
  114. // https://webkit.org/blog/6784/new-video-policies-for-ios/
  115. // required on iOS; nice to have in all browsers
  116. video.setAttribute('playsinline', '');
  117. // handle autoplay
  118. return this._handleAutoPlay(video).then(video => {
  119. // handle WebKit quirks
  120. // note: navigator.vendor is deprecated. Alternatively, test GL_RENDERER == "Apple GPU"
  121. if(Utils.isIOS() || /Apple/.test(navigator.vendor)) {
  122. // on Epiphany, a hidden <video> shows up as a black screen when copied to a canvas
  123. if(video.hidden) {
  124. video.hidden = false;
  125. video.style.setProperty('opacity', '0');
  126. video.style.setProperty('position', 'absolute');
  127. }
  128. }
  129. // done
  130. return video;
  131. });
  132. }
  133. /**
  134. * Handle browser-specific quirks for videos marked with autoplay
  135. * @param video a <video> marked with autoplay
  136. * @returns a promise that resolves to the input video
  137. * @internal
  138. */
  139. _handleAutoPlay(video: HTMLVideoElement): SpeedyPromise<HTMLVideoElement>
  140. {
  141. // Autoplay guide: https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide
  142. // Chrome policy: https://developer.chrome.com/blog/autoplay/
  143. // WebKit policy: https://webkit.org/blog/7734/auto-play-policy-changes-for-macos/
  144. // nothing to do?
  145. if(!video.autoplay)
  146. return Speedy.Promise.resolve(video);
  147. // videos marked with autoplay should be muted
  148. video.muted = true;
  149. // the browser may not honor the autoplay attribute if the video is not
  150. // visible on-screen. So, let's try to play the video in any case.
  151. return this._waitUntilPlayable(video).then(video => {
  152. // try to play the video
  153. const promise = video.play();
  154. // handle older browsers
  155. if(promise === undefined)
  156. return video;
  157. // resolve if successful
  158. return new Speedy.Promise<HTMLVideoElement>((resolve, reject) => {
  159. promise.then(() => resolve(video), error => {
  160. // can't play the video
  161. Utils.error(`Can't autoplay video!`, error, video);
  162. // autoplay is blocked for some reason
  163. if(error.name == 'NotAllowedError') {
  164. Utils.warning('Tip: allow manual playback');
  165. if(Utils.isIOS())
  166. Utils.warning('Is low power mode on?');
  167. // User interaction is required to play the video. We can
  168. // solve this here (easy and convenient to do) or at the
  169. // application layer (for a better user experience). If the
  170. // latter is preferred, just disable autoplay and play the
  171. // video programatically.
  172. if(video.hidden || !video.controls || video.parentNode === null) {
  173. // this is added for convenience
  174. document.body.addEventListener('pointerdown', () => video.play());
  175. // ask only once for user interaction
  176. if(!displayedAlertMessage) {
  177. alert(ALERT_MESSAGE);
  178. displayedAlertMessage = true;
  179. }
  180. // XXX what if the Session mode is inline? In this
  181. // case, this convenience code may be undesirable.
  182. // A workaround is to disable autoplay.
  183. }
  184. /*else {
  185. // play the video after the first interaction with the page
  186. const polling = setInterval(() => {
  187. video.play().then(() => clearInterval(polling));
  188. }, 500);
  189. }*/
  190. }
  191. // unsupported media source
  192. else if(error.name == 'NotSupportedError') {
  193. reject(new NotSupportedError('Unsupported video format', error));
  194. return;
  195. }
  196. // done
  197. resolve(video);
  198. });
  199. });
  200. });
  201. }
  202. /**
  203. * Wait for the input video to be playable
  204. * @param video
  205. * @returns a promise that resolves to the input video when it can be played through to the end
  206. * @internal
  207. */
  208. _waitUntilPlayable(video: HTMLVideoElement): SpeedyPromise<HTMLVideoElement>
  209. {
  210. const TIMEOUT = 15000, INTERVAL = 500;
  211. if(video.readyState >= 4)
  212. return Speedy.Promise.resolve(video);
  213. return new Speedy.Promise<HTMLVideoElement>((resolve, reject) => {
  214. let ms = 0, t = setInterval(() => {
  215. if(video.readyState >= 4) { // canplaythrough
  216. clearInterval(t);
  217. resolve(video);
  218. }
  219. else if((ms += INTERVAL) > TIMEOUT) {
  220. reject(new TimeoutError('The video took too long to load'));
  221. }
  222. }, INTERVAL);
  223. });
  224. }
  225. }