yuv-canvas-1.2.6.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  1. (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. module.exports = {
  3. vertex: "precision lowp float;\n\nattribute vec2 aPosition;\nattribute vec2 aLumaPosition;\nattribute vec2 aChromaPosition;\nvarying vec2 vLumaPosition;\nvarying vec2 vChromaPosition;\nvoid main() {\n gl_Position = vec4(aPosition, 0, 1);\n vLumaPosition = aLumaPosition;\n vChromaPosition = aChromaPosition;\n}\n",
  4. fragment: "// inspired by https://github.com/mbebenita/Broadway/blob/master/Player/canvas.js\n\nprecision lowp float;\n\nuniform sampler2D uTextureY;\nuniform sampler2D uTextureCb;\nuniform sampler2D uTextureCr;\nvarying vec2 vLumaPosition;\nvarying vec2 vChromaPosition;\nvoid main() {\n // Y, Cb, and Cr planes are uploaded as LUMINANCE textures.\n float fY = texture2D(uTextureY, vLumaPosition).x;\n float fCb = texture2D(uTextureCb, vChromaPosition).x;\n float fCr = texture2D(uTextureCr, vChromaPosition).x;\n\n // Premultipy the Y...\n float fYmul = fY * 1.1643828125;\n\n // And convert that to RGB!\n gl_FragColor = vec4(\n fYmul + 1.59602734375 * fCr - 0.87078515625,\n fYmul - 0.39176171875 * fCb - 0.81296875 * fCr + 0.52959375,\n fYmul + 2.017234375 * fCb - 1.081390625,\n 1\n );\n}\n",
  5. vertexStripe: "precision lowp float;\n\nattribute vec2 aPosition;\nattribute vec2 aTexturePosition;\nvarying vec2 vTexturePosition;\n\nvoid main() {\n gl_Position = vec4(aPosition, 0, 1);\n vTexturePosition = aTexturePosition;\n}\n",
  6. fragmentStripe: "// extra 'stripe' texture fiddling to work around IE 11's poor performance on gl.LUMINANCE and gl.ALPHA textures\n\nprecision lowp float;\n\nuniform sampler2D uStripe;\nuniform sampler2D uTexture;\nvarying vec2 vTexturePosition;\nvoid main() {\n // Y, Cb, and Cr planes are mapped into a pseudo-RGBA texture\n // so we can upload them without expanding the bytes on IE 11\n // which doesn't allow LUMINANCE or ALPHA textures\n // The stripe textures mark which channel to keep for each pixel.\n // Each texture extraction will contain the relevant value in one\n // channel only.\n\n float fLuminance = dot(\n texture2D(uStripe, vTexturePosition),\n texture2D(uTexture, vTexturePosition)\n );\n\n gl_FragColor = vec4(fLuminance, fLuminance, fLuminance, 1);\n}\n"
  7. };
  8. },{}],2:[function(require,module,exports){
  9. window.YUVBuffer = require('yuv-buffer')
  10. window.YUVCanvas = require('./../src/yuv-canvas.js')
  11. },{"./../src/yuv-canvas.js":9,"yuv-buffer":3}],3:[function(require,module,exports){
  12. /*
  13. Copyright (c) 2014-2016 Brion Vibber <brion@pobox.com>
  14. Permission is hereby granted, free of charge, to any person obtaining a copy of
  15. this software and associated documentation files (the "Software"), to deal in
  16. the Software without restriction, including without limitation the rights to
  17. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  18. the Software, and to permit persons to whom the Software is furnished to do so,
  19. subject to the following conditions:
  20. The above copyright notice and this permission notice shall be included in all
  21. copies or substantial portions of the Software.
  22. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  23. MPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  24. FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  25. COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  26. IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  27. ONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. */
  29. /**
  30. * Represents metadata about a YUV frame format.
  31. * @typedef {Object} YUVFormat
  32. * @property {number} width - width of encoded frame in luma pixels
  33. * @property {number} height - height of encoded frame in luma pixels
  34. * @property {number} chromaWidth - width of encoded frame in chroma pixels
  35. * @property {number} chromaHeight - height of encoded frame in chroma pixels
  36. * @property {number} cropLeft - upper-left X coordinate of visible crop region, in luma pixels
  37. * @property {number} cropTop - upper-left Y coordinate of visible crop region, in luma pixels
  38. * @property {number} cropWidth - width of visible crop region, in luma pixels
  39. * @property {number} cropHeight - height of visible crop region, in luma pixels
  40. * @property {number} displayWidth - final display width of visible region, in luma pixels
  41. * @property {number} displayHeight - final display height of visible region, in luma pixels
  42. */
  43. /**
  44. * Represents underlying image data for a single luma or chroma plane.
  45. * Cannot be interpreted without the format data from a frame buffer.
  46. * @typedef {Object} YUVPlane
  47. * @property {Uint8Array} bytes - typed array containing image data bytes
  48. * @property {number} stride - byte distance between rows in data
  49. */
  50. /**
  51. * Represents a YUV image frame buffer, with enough format information
  52. * to interpret the data usefully. Buffer objects use generic objects
  53. * under the hood and can be transferred between worker threads using
  54. * the structured clone algorithm.
  55. *
  56. * @typedef {Object} YUVFrame
  57. * @property {YUVFormat} format
  58. * @property {YUVPlane} y
  59. * @property {YUVPlane} u
  60. * @property {YUVPlane} v
  61. */
  62. /**
  63. * Holder namespace for utility functions and constants related to
  64. * YUV frame and plane buffers.
  65. *
  66. * @namespace
  67. */
  68. var YUVBuffer = {
  69. /**
  70. * Validate a plane dimension
  71. * @param {number} dim - vertical or horizontal dimension
  72. * @throws exception on zero, negative, or non-integer value
  73. */
  74. validateDimension: function(dim) {
  75. if (dim <= 0 || dim !== (dim | 0)) {
  76. throw 'YUV plane dimensions must be a positive integer';
  77. }
  78. },
  79. /**
  80. * Validate a plane offset
  81. * @param {number} dim - vertical or horizontal dimension
  82. * @throws exception on negative or non-integer value
  83. */
  84. validateOffset: function(dim) {
  85. if (dim < 0 || dim !== (dim | 0)) {
  86. throw 'YUV plane offsets must be a non-negative integer';
  87. }
  88. },
  89. /**
  90. * Validate and fill out a YUVFormat object structure.
  91. *
  92. * At least width and height fields are required; other fields will be
  93. * derived if left missing or empty:
  94. * - chromaWidth and chromaHeight will be copied from width and height as for a 4:4:4 layout
  95. * - cropLeft and cropTop will be 0
  96. * - cropWidth and cropHeight will be set to whatever of the frame is visible after cropTop and cropLeft are applied
  97. * - displayWidth and displayHeight will be set to cropWidth and cropHeight.
  98. *
  99. * @param {YUVFormat} fields - input fields, must include width and height.
  100. * @returns {YUVFormat} - validated structure, with all derivable fields filled out.
  101. * @throws exception on invalid fields or missing width/height
  102. */
  103. format: function(fields) {
  104. var width = fields.width,
  105. height = fields.height,
  106. chromaWidth = fields.chromaWidth || width,
  107. chromaHeight = fields.chromaHeight || height,
  108. cropLeft = fields.cropLeft || 0,
  109. cropTop = fields.cropTop || 0,
  110. cropWidth = fields.cropWidth || width - cropLeft,
  111. cropHeight = fields.cropHeight || height - cropTop,
  112. displayWidth = fields.displayWidth || cropWidth,
  113. displayHeight = fields.displayHeight || cropHeight;
  114. this.validateDimension(width);
  115. this.validateDimension(height);
  116. this.validateDimension(chromaWidth);
  117. this.validateDimension(chromaHeight);
  118. this.validateOffset(cropLeft);
  119. this.validateOffset(cropTop);
  120. this.validateDimension(cropWidth);
  121. this.validateDimension(cropHeight);
  122. this.validateDimension(displayWidth);
  123. this.validateDimension(displayHeight);
  124. return {
  125. width: width,
  126. height: height,
  127. chromaWidth: chromaWidth,
  128. chromaHeight: chromaHeight,
  129. cropLeft: cropLeft,
  130. cropTop: cropTop,
  131. cropWidth: cropWidth,
  132. cropHeight: cropHeight,
  133. displayWidth: displayWidth,
  134. displayHeight: displayHeight
  135. };
  136. },
  137. /**
  138. * Allocate a new YUVPlane object of the given size.
  139. * @param {number} stride - byte distance between rows
  140. * @param {number} rows - number of rows to allocate
  141. * @returns {YUVPlane} - freshly allocated planar buffer
  142. */
  143. allocPlane: function(stride, rows) {
  144. YUVBuffer.validateDimension(stride);
  145. YUVBuffer.validateDimension(rows);
  146. return {
  147. bytes: new Uint8Array(stride * rows),
  148. stride: stride
  149. }
  150. },
  151. /**
  152. * Pick a suitable stride for a custom-allocated thingy
  153. * @param {number} width - width in bytes
  154. * @returns {number} - new width in bytes at least as large
  155. * @throws exception on invalid input width
  156. */
  157. suitableStride: function(width) {
  158. YUVBuffer.validateDimension(width);
  159. var alignment = 4,
  160. remainder = width % alignment;
  161. if (remainder == 0) {
  162. return width;
  163. } else {
  164. return width + (alignment - remainder);
  165. }
  166. },
  167. /**
  168. * Allocate or extract a YUVPlane object from given dimensions/source.
  169. * @param {number} width - width in pixels
  170. * @param {number} height - height in pixels
  171. * @param {Uint8Array} source - input byte array; optional (will create empty buffer if missing)
  172. * @param {number} stride - row length in bytes; optional (will create a default if missing)
  173. * @param {number} offset - offset into source array to extract; optional (will start at 0 if missing)
  174. * @returns {YUVPlane} - freshly allocated planar buffer
  175. */
  176. allocPlane: function(width, height, source, stride, offset) {
  177. var size, bytes;
  178. this.validateDimension(width);
  179. this.validateDimension(height);
  180. offset = offset || 0;
  181. stride = stride || this.suitableStride(width);
  182. this.validateDimension(stride);
  183. if (stride < width) {
  184. throw "Invalid input stride for YUV plane; must be larger than width";
  185. }
  186. size = stride * height;
  187. if (source) {
  188. if (source.length - offset < size) {
  189. throw "Invalid input buffer for YUV plane; must be large enough for stride times height";
  190. }
  191. bytes = source.slice(offset, offset + size);
  192. } else {
  193. bytes = new Uint8Array(size);
  194. stride = stride || this.suitableStride(width);
  195. }
  196. return {
  197. bytes: bytes,
  198. stride: stride
  199. };
  200. },
  201. /**
  202. * Allocate a new YUVPlane object big enough for a luma plane in the given format
  203. * @param {YUVFormat} format - target frame format
  204. * @param {Uint8Array} source - input byte array; optional (will create empty buffer if missing)
  205. * @param {number} stride - row length in bytes; optional (will create a default if missing)
  206. * @param {number} offset - offset into source array to extract; optional (will start at 0 if missing)
  207. * @returns {YUVPlane} - freshly allocated planar buffer
  208. */
  209. lumaPlane: function(format, source, stride, offset) {
  210. return this.allocPlane(format.width, format.height, source, stride, offset);
  211. },
  212. /**
  213. * Allocate a new YUVPlane object big enough for a chroma plane in the given format,
  214. * optionally copying data from an existing buffer.
  215. *
  216. * @param {YUVFormat} format - target frame format
  217. * @param {Uint8Array} source - input byte array; optional (will create empty buffer if missing)
  218. * @param {number} stride - row length in bytes; optional (will create a default if missing)
  219. * @param {number} offset - offset into source array to extract; optional (will start at 0 if missing)
  220. * @returns {YUVPlane} - freshly allocated planar buffer
  221. */
  222. chromaPlane: function(format, source, stride, offset) {
  223. return this.allocPlane(format.chromaWidth, format.chromaHeight, source, stride, offset);
  224. },
  225. /**
  226. * Allocate a new YUVFrame object big enough for the given format
  227. * @param {YUVFormat} format - target frame format
  228. * @param {YUVPlane} y - optional Y plane; if missing, fresh one will be allocated
  229. * @param {YUVPlane} u - optional U plane; if missing, fresh one will be allocated
  230. * @param {YUVPlane} v - optional V plane; if missing, fresh one will be allocated
  231. * @returns {YUVFrame} - freshly allocated frame buffer
  232. */
  233. frame: function(format, y, u, v) {
  234. y = y || this.lumaPlane(format);
  235. u = u || this.chromaPlane(format);
  236. v = v || this.chromaPlane(format);
  237. return {
  238. format: format,
  239. y: y,
  240. u: u,
  241. v: v
  242. }
  243. },
  244. /**
  245. * Duplicate a plane using new buffer memory.
  246. * @param {YUVPlane} plane - input plane to copy
  247. * @returns {YUVPlane} - freshly allocated and filled planar buffer
  248. */
  249. copyPlane: function(plane) {
  250. return {
  251. bytes: plane.bytes.slice(),
  252. stride: plane.stride
  253. };
  254. },
  255. /**
  256. * Duplicate a frame using new buffer memory.
  257. * @param {YUVFrame} frame - input frame to copyFrame
  258. * @returns {YUVFrame} - freshly allocated and filled frame buffer
  259. */
  260. copyFrame: function(frame) {
  261. return {
  262. format: frame.format,
  263. y: this.copyPlane(frame.y),
  264. u: this.copyPlane(frame.u),
  265. v: this.copyPlane(frame.v)
  266. }
  267. },
  268. /**
  269. * List the backing buffers for the frame's planes for transfer between
  270. * threads via Worker.postMessage.
  271. * @param {YUVFrame} frame - input frame
  272. * @returns {Array} - list of transferable objects
  273. */
  274. transferables: function(frame) {
  275. return [frame.y.bytes.buffer, frame.u.bytes.buffer, frame.v.bytes.buffer];
  276. }
  277. };
  278. module.exports = YUVBuffer;
  279. },{}],4:[function(require,module,exports){
  280. (function() {
  281. "use strict";
  282. /**
  283. * Create a YUVCanvas and attach it to an HTML5 canvas element.
  284. *
  285. * This will take over the drawing context of the canvas and may turn
  286. * it into a WebGL 3d canvas if possible. Do not attempt to use the
  287. * drawing context directly after this.
  288. *
  289. * @param {HTMLCanvasElement} canvas - HTML canvas element to attach to
  290. * @param {YUVCanvasOptions} options - map of options
  291. * @throws exception if WebGL requested but unavailable
  292. * @constructor
  293. * @abstract
  294. */
  295. function FrameSink(canvas, options) {
  296. throw new Error('abstract');
  297. }
  298. /**
  299. * Draw a single YUV frame on the underlying canvas, converting to RGB.
  300. * If necessary the canvas will be resized to the optimal pixel size
  301. * for the given buffer's format.
  302. *
  303. * @param {YUVBuffer} buffer - the YUV buffer to draw
  304. * @see {@link https://www.npmjs.com/package/yuv-buffer|yuv-buffer} for format
  305. */
  306. FrameSink.prototype.drawFrame = function(buffer) {
  307. throw new Error('abstract');
  308. };
  309. /**
  310. * Clear the canvas using appropriate underlying 2d or 3d context.
  311. */
  312. FrameSink.prototype.clear = function() {
  313. throw new Error('abstract');
  314. };
  315. module.exports = FrameSink;
  316. })();
  317. },{}],5:[function(require,module,exports){
  318. /*
  319. Copyright (c) 2014-2016 Brion Vibber <brion@pobox.com>
  320. Permission is hereby granted, free of charge, to any person obtaining a copy of
  321. this software and associated documentation files (the "Software"), to deal in
  322. the Software without restriction, including without limitation the rights to
  323. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  324. the Software, and to permit persons to whom the Software is furnished to do so,
  325. subject to the following conditions:
  326. The above copyright notice and this permission notice shall be included in all
  327. copies or substantial portions of the Software.
  328. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  329. MPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  330. FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  331. COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  332. IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  333. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  334. */
  335. (function() {
  336. "use strict";
  337. var FrameSink = require('./FrameSink.js'),
  338. YCbCr = require('./YCbCr.js');
  339. /**
  340. * @param {HTMLCanvasElement} canvas - HTML canvas eledment to attach to
  341. * @constructor
  342. */
  343. function SoftwareFrameSink(canvas) {
  344. var self = this,
  345. ctx = canvas.getContext('2d'),
  346. imageData = null,
  347. resampleCanvas = null,
  348. resampleContext = null;
  349. function initImageData(width, height) {
  350. imageData = ctx.createImageData(width, height);
  351. // Prefill the alpha to opaque
  352. var data = imageData.data,
  353. pixelCount = width * height * 4;
  354. for (var i = 0; i < pixelCount; i += 4) {
  355. data[i + 3] = 255;
  356. }
  357. }
  358. function initResampleCanvas(cropWidth, cropHeight) {
  359. resampleCanvas = document.createElement('canvas');
  360. resampleCanvas.width = cropWidth;
  361. resampleCanvas.height = cropHeight;
  362. resampleContext = resampleCanvas.getContext('2d');
  363. }
  364. /**
  365. * Actually draw a frame into the canvas.
  366. * @param {YUVFrame} buffer - YUV frame buffer object to draw
  367. */
  368. self.drawFrame = function drawFrame(buffer) {
  369. var format = buffer.format;
  370. if (canvas.width !== format.displayWidth || canvas.height !== format.displayHeight) {
  371. // Keep the canvas at the right size...
  372. canvas.width = format.displayWidth;
  373. canvas.height = format.displayHeight;
  374. }
  375. if (imageData === null ||
  376. imageData.width != format.width ||
  377. imageData.height != format.height) {
  378. initImageData(format.width, format.height);
  379. }
  380. // YUV -> RGB over the entire encoded frame
  381. YCbCr.convertYCbCr(buffer, imageData.data);
  382. var resample = (format.cropWidth != format.displayWidth || format.cropHeight != format.displayHeight);
  383. var drawContext;
  384. if (resample) {
  385. // hack for non-square aspect-ratio
  386. // putImageData doesn't resample, so we have to draw in two steps.
  387. if (!resampleCanvas) {
  388. initResampleCanvas(format.cropWidth, format.cropHeight);
  389. }
  390. drawContext = resampleContext;
  391. } else {
  392. drawContext = ctx;
  393. }
  394. // Draw cropped frame to either the final or temporary canvas
  395. drawContext.putImageData(imageData,
  396. -format.cropLeft, -format.cropTop, // must offset the offset
  397. format.cropLeft, format.cropTop,
  398. format.cropWidth, format.cropHeight);
  399. if (resample) {
  400. ctx.drawImage(resampleCanvas, 0, 0, format.displayWidth, format.displayHeight);
  401. }
  402. };
  403. self.clear = function() {
  404. ctx.clearRect(0, 0, canvas.width, canvas.height);
  405. };
  406. return self;
  407. }
  408. SoftwareFrameSink.prototype = Object.create(FrameSink.prototype);
  409. module.exports = SoftwareFrameSink;
  410. })();
  411. },{"./FrameSink.js":4,"./YCbCr.js":7}],6:[function(require,module,exports){
  412. /*
  413. Copyright (c) 2014-2016 Brion Vibber <brion@pobox.com>
  414. Permission is hereby granted, free of charge, to any person obtaining a copy of
  415. this software and associated documentation files (the "Software"), to deal in
  416. the Software without restriction, including without limitation the rights to
  417. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  418. the Software, and to permit persons to whom the Software is furnished to do so,
  419. subject to the following conditions:
  420. The above copyright notice and this permission notice shall be included in all
  421. copies or substantial portions of the Software.
  422. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  423. MPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  424. FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  425. COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  426. IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  427. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  428. */
  429. (function() {
  430. "use strict";
  431. var FrameSink = require('./FrameSink.js'),
  432. shaders = require('../build/shaders.js');
  433. /**
  434. * Warning: canvas must not have been used for 2d drawing prior!
  435. *
  436. * @param {HTMLCanvasElement} canvas - HTML canvas element to attach to
  437. * @constructor
  438. */
  439. function WebGLFrameSink(canvas) {
  440. var self = this,
  441. gl = WebGLFrameSink.contextForCanvas(canvas),
  442. debug = false; // swap this to enable more error checks, which can slow down rendering
  443. if (gl === null) {
  444. throw new Error('WebGL unavailable');
  445. }
  446. // GL!
  447. function checkError() {
  448. if (debug) {
  449. err = gl.getError();
  450. if (err !== 0) {
  451. throw new Error("GL error " + err);
  452. }
  453. }
  454. }
  455. function compileShader(type, source) {
  456. var shader = gl.createShader(type);
  457. gl.shaderSource(shader, source);
  458. gl.compileShader(shader);
  459. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  460. var err = gl.getShaderInfoLog(shader);
  461. gl.deleteShader(shader);
  462. throw new Error('GL shader compilation for ' + type + ' failed: ' + err);
  463. }
  464. return shader;
  465. }
  466. var program,
  467. unpackProgram,
  468. err;
  469. // In the world of GL there are no rectangles.
  470. // There are only triangles.
  471. // THERE IS NO SPOON.
  472. var rectangle = new Float32Array([
  473. // First triangle (top left, clockwise)
  474. -1.0, -1.0,
  475. +1.0, -1.0,
  476. -1.0, +1.0,
  477. // Second triangle (bottom right, clockwise)
  478. -1.0, +1.0,
  479. +1.0, -1.0,
  480. +1.0, +1.0
  481. ]);
  482. var textures = {};
  483. var framebuffers = {};
  484. var stripes = {};
  485. var buf, positionLocation, unpackPositionLocation;
  486. var unpackTexturePositionBuffer, unpackTexturePositionLocation;
  487. var stripeLocation, unpackTextureLocation;
  488. var lumaPositionBuffer, lumaPositionLocation;
  489. var chromaPositionBuffer, chromaPositionLocation;
  490. function createOrReuseTexture(name) {
  491. if (!textures[name]) {
  492. textures[name] = gl.createTexture();
  493. }
  494. return textures[name];
  495. }
  496. function uploadTexture(name, width, height, data) {
  497. var texture = createOrReuseTexture(name);
  498. gl.activeTexture(gl.TEXTURE0);
  499. if (WebGLFrameSink.stripe) {
  500. var uploadTemp = !textures[name + '_temp'];
  501. var tempTexture = createOrReuseTexture(name + '_temp');
  502. gl.bindTexture(gl.TEXTURE_2D, tempTexture);
  503. if (uploadTemp) {
  504. // new texture
  505. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  506. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  507. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  508. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  509. gl.texImage2D(
  510. gl.TEXTURE_2D,
  511. 0, // mip level
  512. gl.RGBA, // internal format
  513. width / 4,
  514. height,
  515. 0, // border
  516. gl.RGBA, // format
  517. gl.UNSIGNED_BYTE, // type
  518. data // data!
  519. );
  520. } else {
  521. // update texture
  522. gl.texSubImage2D(
  523. gl.TEXTURE_2D,
  524. 0, // mip level
  525. 0, // x offset
  526. 0, // y offset
  527. width / 4,
  528. height,
  529. gl.RGBA, // format
  530. gl.UNSIGNED_BYTE, // type
  531. data // data!
  532. );
  533. }
  534. var stripeTexture = textures[name + '_stripe'];
  535. var uploadStripe = !stripeTexture;
  536. if (uploadStripe) {
  537. stripeTexture = createOrReuseTexture(name + '_stripe');
  538. }
  539. gl.bindTexture(gl.TEXTURE_2D, stripeTexture);
  540. if (uploadStripe) {
  541. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  542. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  543. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  544. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  545. gl.texImage2D(
  546. gl.TEXTURE_2D,
  547. 0, // mip level
  548. gl.RGBA, // internal format
  549. width,
  550. 1,
  551. 0, // border
  552. gl.RGBA, // format
  553. gl.UNSIGNED_BYTE, //type
  554. buildStripe(width, 1) // data!
  555. );
  556. }
  557. } else {
  558. gl.bindTexture(gl.TEXTURE_2D, texture);
  559. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  560. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  561. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  562. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  563. gl.texImage2D(
  564. gl.TEXTURE_2D,
  565. 0, // mip level
  566. gl.LUMINANCE, // internal format
  567. width,
  568. height,
  569. 0, // border
  570. gl.LUMINANCE, // format
  571. gl.UNSIGNED_BYTE, //type
  572. data // data!
  573. );
  574. }
  575. }
  576. function unpackTexture(name, width, height) {
  577. var texture = textures[name];
  578. // Upload to a temporary RGBA texture, then unpack it.
  579. // This is faster than CPU-side swizzling in ANGLE on Windows.
  580. gl.useProgram(unpackProgram);
  581. var fb = framebuffers[name];
  582. if (!fb) {
  583. // Create a framebuffer and an empty target size
  584. gl.activeTexture(gl.TEXTURE0);
  585. gl.bindTexture(gl.TEXTURE_2D, texture);
  586. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  587. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  588. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  589. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  590. gl.texImage2D(
  591. gl.TEXTURE_2D,
  592. 0, // mip level
  593. gl.RGBA, // internal format
  594. width,
  595. height,
  596. 0, // border
  597. gl.RGBA, // format
  598. gl.UNSIGNED_BYTE, //type
  599. null // data!
  600. );
  601. fb = framebuffers[name] = gl.createFramebuffer();
  602. }
  603. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  604. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  605. var tempTexture = textures[name + '_temp'];
  606. gl.activeTexture(gl.TEXTURE1);
  607. gl.bindTexture(gl.TEXTURE_2D, tempTexture);
  608. gl.uniform1i(unpackTextureLocation, 1);
  609. var stripeTexture = textures[name + '_stripe'];
  610. gl.activeTexture(gl.TEXTURE2);
  611. gl.bindTexture(gl.TEXTURE_2D, stripeTexture);
  612. gl.uniform1i(stripeLocation, 2);
  613. // Rectangle geometry
  614. gl.bindBuffer(gl.ARRAY_BUFFER, buf);
  615. gl.enableVertexAttribArray(positionLocation);
  616. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  617. // Set up the texture geometry...
  618. gl.bindBuffer(gl.ARRAY_BUFFER, unpackTexturePositionBuffer);
  619. gl.enableVertexAttribArray(unpackTexturePositionLocation);
  620. gl.vertexAttribPointer(unpackTexturePositionLocation, 2, gl.FLOAT, false, 0, 0);
  621. // Draw into the target texture...
  622. gl.viewport(0, 0, width, height);
  623. gl.drawArrays(gl.TRIANGLES, 0, rectangle.length / 2);
  624. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  625. }
  626. function attachTexture(name, register, index) {
  627. gl.activeTexture(register);
  628. gl.bindTexture(gl.TEXTURE_2D, textures[name]);
  629. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  630. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  631. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  632. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  633. gl.uniform1i(gl.getUniformLocation(program, name), index);
  634. }
  635. function buildStripe(width) {
  636. if (stripes[width]) {
  637. return stripes[width];
  638. }
  639. var len = width,
  640. out = new Uint32Array(len);
  641. for (var i = 0; i < len; i += 4) {
  642. out[i ] = 0x000000ff;
  643. out[i + 1] = 0x0000ff00;
  644. out[i + 2] = 0x00ff0000;
  645. out[i + 3] = 0xff000000;
  646. }
  647. return stripes[width] = new Uint8Array(out.buffer);
  648. }
  649. function initProgram(vertexShaderSource, fragmentShaderSource) {
  650. var vertexShader = compileShader(gl.VERTEX_SHADER, vertexShaderSource);
  651. var fragmentShader = compileShader(gl.FRAGMENT_SHADER, fragmentShaderSource);
  652. var program = gl.createProgram();
  653. gl.attachShader(program, vertexShader);
  654. gl.attachShader(program, fragmentShader);
  655. gl.linkProgram(program);
  656. if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
  657. var err = gl.getProgramInfoLog(program);
  658. gl.deleteProgram(program);
  659. throw new Error('GL program linking failed: ' + err);
  660. }
  661. return program;
  662. }
  663. function init() {
  664. if (WebGLFrameSink.stripe) {
  665. unpackProgram = initProgram(shaders.vertexStripe, shaders.fragmentStripe);
  666. unpackPositionLocation = gl.getAttribLocation(unpackProgram, 'aPosition');
  667. unpackTexturePositionBuffer = gl.createBuffer();
  668. var textureRectangle = new Float32Array([
  669. 0, 0,
  670. 1, 0,
  671. 0, 1,
  672. 0, 1,
  673. 1, 0,
  674. 1, 1
  675. ]);
  676. gl.bindBuffer(gl.ARRAY_BUFFER, unpackTexturePositionBuffer);
  677. gl.bufferData(gl.ARRAY_BUFFER, textureRectangle, gl.STATIC_DRAW);
  678. unpackTexturePositionLocation = gl.getAttribLocation(unpackProgram, 'aTexturePosition');
  679. stripeLocation = gl.getUniformLocation(unpackProgram, 'uStripe');
  680. unpackTextureLocation = gl.getUniformLocation(unpackProgram, 'uTexture');
  681. }
  682. program = initProgram(shaders.vertex, shaders.fragment);
  683. buf = gl.createBuffer();
  684. gl.bindBuffer(gl.ARRAY_BUFFER, buf);
  685. gl.bufferData(gl.ARRAY_BUFFER, rectangle, gl.STATIC_DRAW);
  686. positionLocation = gl.getAttribLocation(program, 'aPosition');
  687. lumaPositionBuffer = gl.createBuffer();
  688. lumaPositionLocation = gl.getAttribLocation(program, 'aLumaPosition');
  689. chromaPositionBuffer = gl.createBuffer();
  690. chromaPositionLocation = gl.getAttribLocation(program, 'aChromaPosition');
  691. }
  692. /**
  693. * Actually draw a frame.
  694. * @param {YUVFrame} buffer - YUV frame buffer object
  695. */
  696. self.drawFrame = function(buffer) {
  697. var format = buffer.format;
  698. var formatUpdate = (!program || canvas.width !== format.displayWidth || canvas.height !== format.displayHeight);
  699. if (formatUpdate) {
  700. // Keep the canvas at the right size...
  701. canvas.width = format.displayWidth;
  702. canvas.height = format.displayHeight;
  703. self.clear();
  704. }
  705. if (!program) {
  706. init();
  707. }
  708. if (formatUpdate) {
  709. var setupTexturePosition = function(buffer, location, texWidth) {
  710. // Warning: assumes that the stride for Cb and Cr is the same size in output pixels
  711. var textureX0 = format.cropLeft / texWidth;
  712. var textureX1 = (format.cropLeft + format.cropWidth) / texWidth;
  713. var textureY0 = (format.cropTop + format.cropHeight) / format.height;
  714. var textureY1 = format.cropTop / format.height;
  715. var textureRectangle = new Float32Array([
  716. textureX0, textureY0,
  717. textureX1, textureY0,
  718. textureX0, textureY1,
  719. textureX0, textureY1,
  720. textureX1, textureY0,
  721. textureX1, textureY1
  722. ]);
  723. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  724. gl.bufferData(gl.ARRAY_BUFFER, textureRectangle, gl.STATIC_DRAW);
  725. };
  726. setupTexturePosition(
  727. lumaPositionBuffer,
  728. lumaPositionLocation,
  729. buffer.y.stride);
  730. setupTexturePosition(
  731. chromaPositionBuffer,
  732. chromaPositionLocation,
  733. buffer.u.stride * format.width / format.chromaWidth);
  734. }
  735. // Create or update the textures...
  736. uploadTexture('uTextureY', buffer.y.stride, format.height, buffer.y.bytes);
  737. uploadTexture('uTextureCb', buffer.u.stride, format.chromaHeight, buffer.u.bytes);
  738. uploadTexture('uTextureCr', buffer.v.stride, format.chromaHeight, buffer.v.bytes);
  739. if (WebGLFrameSink.stripe) {
  740. // Unpack the textures after upload to avoid blocking on GPU
  741. unpackTexture('uTextureY', buffer.y.stride, format.height);
  742. unpackTexture('uTextureCb', buffer.u.stride, format.chromaHeight);
  743. unpackTexture('uTextureCr', buffer.v.stride, format.chromaHeight);
  744. }
  745. // Set up the rectangle and draw it
  746. gl.useProgram(program);
  747. gl.viewport(0, 0, canvas.width, canvas.height);
  748. attachTexture('uTextureY', gl.TEXTURE0, 0);
  749. attachTexture('uTextureCb', gl.TEXTURE1, 1);
  750. attachTexture('uTextureCr', gl.TEXTURE2, 2);
  751. // Set up geometry
  752. gl.bindBuffer(gl.ARRAY_BUFFER, buf);
  753. gl.enableVertexAttribArray(positionLocation);
  754. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  755. // Set up the texture geometry...
  756. gl.bindBuffer(gl.ARRAY_BUFFER, lumaPositionBuffer);
  757. gl.enableVertexAttribArray(lumaPositionLocation);
  758. gl.vertexAttribPointer(lumaPositionLocation, 2, gl.FLOAT, false, 0, 0);
  759. gl.bindBuffer(gl.ARRAY_BUFFER, chromaPositionBuffer);
  760. gl.enableVertexAttribArray(chromaPositionLocation);
  761. gl.vertexAttribPointer(chromaPositionLocation, 2, gl.FLOAT, false, 0, 0);
  762. // Aaaaand draw stuff.
  763. gl.drawArrays(gl.TRIANGLES, 0, rectangle.length / 2);
  764. };
  765. self.clear = function() {
  766. gl.viewport(0, 0, canvas.width, canvas.height);
  767. gl.clearColor(0.0, 0.0, 0.0, 0.0);
  768. gl.clear(gl.COLOR_BUFFER_BIT);
  769. };
  770. self.clear();
  771. return self;
  772. }
  773. // For Windows; luminance and alpha textures are ssllooww to upload,
  774. // so we pack into RGBA and unpack in the shaders.
  775. //
  776. // This seems to affect all browsers on Windows, probably due to fun
  777. // mismatches between GL and D3D.
  778. WebGLFrameSink.stripe = (function() {
  779. if (navigator.userAgent.indexOf('Windows') !== -1) {
  780. return true;
  781. }
  782. return false;
  783. })();
  784. WebGLFrameSink.contextForCanvas = function(canvas) {
  785. var options = {
  786. // Don't trigger discrete GPU in multi-GPU systems
  787. preferLowPowerToHighPerformance: true,
  788. powerPreference: 'low-power',
  789. // Don't try to use software GL rendering!
  790. failIfMajorPerformanceCaveat: true,
  791. // In case we need to capture the resulting output.
  792. preserveDrawingBuffer: true
  793. };
  794. return canvas.getContext('webgl', options) || canvas.getContext('experimental-webgl', options);
  795. };
  796. /**
  797. * Static function to check if WebGL will be available with appropriate features.
  798. *
  799. * @returns {boolean} - true if available
  800. */
  801. WebGLFrameSink.isAvailable = function() {
  802. var canvas = document.createElement('canvas'),
  803. gl;
  804. canvas.width = 1;
  805. canvas.height = 1;
  806. try {
  807. gl = WebGLFrameSink.contextForCanvas(canvas);
  808. } catch (e) {
  809. return false;
  810. }
  811. if (gl) {
  812. var register = gl.TEXTURE0,
  813. width = 4,
  814. height = 4,
  815. texture = gl.createTexture(),
  816. data = new Uint8Array(width * height),
  817. texWidth = WebGLFrameSink.stripe ? (width / 4) : width,
  818. format = WebGLFrameSink.stripe ? gl.RGBA : gl.LUMINANCE,
  819. filter = WebGLFrameSink.stripe ? gl.NEAREST : gl.LINEAR;
  820. gl.activeTexture(register);
  821. gl.bindTexture(gl.TEXTURE_2D, texture);
  822. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  823. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  824. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);
  825. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);
  826. gl.texImage2D(
  827. gl.TEXTURE_2D,
  828. 0, // mip level
  829. format, // internal format
  830. texWidth,
  831. height,
  832. 0, // border
  833. format, // format
  834. gl.UNSIGNED_BYTE, //type
  835. data // data!
  836. );
  837. var err = gl.getError();
  838. if (err) {
  839. // Doesn't support luminance textures?
  840. return false;
  841. } else {
  842. return true;
  843. }
  844. } else {
  845. return false;
  846. }
  847. };
  848. WebGLFrameSink.prototype = Object.create(FrameSink.prototype);
  849. module.exports = WebGLFrameSink;
  850. })();
  851. },{"../build/shaders.js":1,"./FrameSink.js":4}],7:[function(require,module,exports){
  852. /*
  853. Copyright (c) 2014-2019 Brion Vibber <brion@pobox.com>
  854. Permission is hereby granted, free of charge, to any person obtaining a copy of
  855. this software and associated documentation files (the "Software"), to deal in
  856. the Software without restriction, including without limitation the rights to
  857. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  858. the Software, and to permit persons to whom the Software is furnished to do so,
  859. subject to the following conditions:
  860. The above copyright notice and this permission notice shall be included in all
  861. copies or substantial portions of the Software.
  862. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  863. MPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  864. FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  865. COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  866. IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  867. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  868. */
  869. (function() {
  870. "use strict";
  871. var depower = require('./depower.js');
  872. /**
  873. * Basic YCbCr->RGB conversion
  874. *
  875. * @author Brion Vibber <brion@pobox.com>
  876. * @copyright 2014-2019
  877. * @license MIT-style
  878. *
  879. * @param {YUVFrame} buffer - input frame buffer
  880. * @param {Uint8ClampedArray} output - array to draw RGBA into
  881. * Assumes that the output array already has alpha channel set to opaque.
  882. */
  883. function convertYCbCr(buffer, output) {
  884. var width = buffer.format.width | 0,
  885. height = buffer.format.height | 0,
  886. hdec = depower(buffer.format.width / buffer.format.chromaWidth) | 0,
  887. vdec = depower(buffer.format.height / buffer.format.chromaHeight) | 0,
  888. bytesY = buffer.y.bytes,
  889. bytesCb = buffer.u.bytes,
  890. bytesCr = buffer.v.bytes,
  891. strideY = buffer.y.stride | 0,
  892. strideCb = buffer.u.stride | 0,
  893. strideCr = buffer.v.stride | 0,
  894. outStride = width << 2,
  895. YPtr = 0, Y0Ptr = 0, Y1Ptr = 0,
  896. CbPtr = 0, CrPtr = 0,
  897. outPtr = 0, outPtr0 = 0, outPtr1 = 0,
  898. colorCb = 0, colorCr = 0,
  899. multY = 0, multCrR = 0, multCbCrG = 0, multCbB = 0,
  900. x = 0, y = 0, xdec = 0, ydec = 0;
  901. if (hdec == 1 && vdec == 1) {
  902. // Optimize for 4:2:0, which is most common
  903. outPtr0 = 0;
  904. outPtr1 = outStride;
  905. ydec = 0;
  906. for (y = 0; y < height; y += 2) {
  907. Y0Ptr = y * strideY | 0;
  908. Y1Ptr = Y0Ptr + strideY | 0;
  909. CbPtr = ydec * strideCb | 0;
  910. CrPtr = ydec * strideCr | 0;
  911. for (x = 0; x < width; x += 2) {
  912. colorCb = bytesCb[CbPtr++] | 0;
  913. colorCr = bytesCr[CrPtr++] | 0;
  914. // Quickie YUV conversion
  915. // https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.2020_conversion
  916. // multiplied by 256 for integer-friendliness
  917. multCrR = (409 * colorCr | 0) - 57088 | 0;
  918. multCbCrG = (100 * colorCb | 0) + (208 * colorCr | 0) - 34816 | 0;
  919. multCbB = (516 * colorCb | 0) - 70912 | 0;
  920. multY = 298 * bytesY[Y0Ptr++] | 0;
  921. output[outPtr0 ] = (multY + multCrR) >> 8;
  922. output[outPtr0 + 1] = (multY - multCbCrG) >> 8;
  923. output[outPtr0 + 2] = (multY + multCbB) >> 8;
  924. outPtr0 += 4;
  925. multY = 298 * bytesY[Y0Ptr++] | 0;
  926. output[outPtr0 ] = (multY + multCrR) >> 8;
  927. output[outPtr0 + 1] = (multY - multCbCrG) >> 8;
  928. output[outPtr0 + 2] = (multY + multCbB) >> 8;
  929. outPtr0 += 4;
  930. multY = 298 * bytesY[Y1Ptr++] | 0;
  931. output[outPtr1 ] = (multY + multCrR) >> 8;
  932. output[outPtr1 + 1] = (multY - multCbCrG) >> 8;
  933. output[outPtr1 + 2] = (multY + multCbB) >> 8;
  934. outPtr1 += 4;
  935. multY = 298 * bytesY[Y1Ptr++] | 0;
  936. output[outPtr1 ] = (multY + multCrR) >> 8;
  937. output[outPtr1 + 1] = (multY - multCbCrG) >> 8;
  938. output[outPtr1 + 2] = (multY + multCbB) >> 8;
  939. outPtr1 += 4;
  940. }
  941. outPtr0 += outStride;
  942. outPtr1 += outStride;
  943. ydec++;
  944. }
  945. } else {
  946. outPtr = 0;
  947. for (y = 0; y < height; y++) {
  948. xdec = 0;
  949. ydec = y >> vdec;
  950. YPtr = y * strideY | 0;
  951. CbPtr = ydec * strideCb | 0;
  952. CrPtr = ydec * strideCr | 0;
  953. for (x = 0; x < width; x++) {
  954. xdec = x >> hdec;
  955. colorCb = bytesCb[CbPtr + xdec] | 0;
  956. colorCr = bytesCr[CrPtr + xdec] | 0;
  957. // Quickie YUV conversion
  958. // https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.2020_conversion
  959. // multiplied by 256 for integer-friendliness
  960. multCrR = (409 * colorCr | 0) - 57088 | 0;
  961. multCbCrG = (100 * colorCb | 0) + (208 * colorCr | 0) - 34816 | 0;
  962. multCbB = (516 * colorCb | 0) - 70912 | 0;
  963. multY = 298 * bytesY[YPtr++] | 0;
  964. output[outPtr ] = (multY + multCrR) >> 8;
  965. output[outPtr + 1] = (multY - multCbCrG) >> 8;
  966. output[outPtr + 2] = (multY + multCbB) >> 8;
  967. outPtr += 4;
  968. }
  969. }
  970. }
  971. }
  972. module.exports = {
  973. convertYCbCr: convertYCbCr
  974. };
  975. })();
  976. },{"./depower.js":8}],8:[function(require,module,exports){
  977. /*
  978. Copyright (c) 2014-2016 Brion Vibber <brion@pobox.com>
  979. Permission is hereby granted, free of charge, to any person obtaining a copy of
  980. this software and associated documentation files (the "Software"), to deal in
  981. the Software without restriction, including without limitation the rights to
  982. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  983. the Software, and to permit persons to whom the Software is furnished to do so,
  984. subject to the following conditions:
  985. The above copyright notice and this permission notice shall be included in all
  986. copies or substantial portions of the Software.
  987. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  988. MPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  989. FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  990. COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  991. IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  992. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  993. */
  994. (function() {
  995. "use strict";
  996. /**
  997. * Convert a ratio into a bit-shift count; for instance a ratio of 2
  998. * becomes a bit-shift of 1, while a ratio of 1 is a bit-shift of 0.
  999. *
  1000. * @author Brion Vibber <brion@pobox.com>
  1001. * @copyright 2016
  1002. * @license MIT-style
  1003. *
  1004. * @param {number} ratio - the integer ratio to convert.
  1005. * @returns {number} - number of bits to shift to multiply/divide by the ratio.
  1006. * @throws exception if given a non-power-of-two
  1007. */
  1008. function depower(ratio) {
  1009. var shiftCount = 0,
  1010. n = ratio >> 1;
  1011. while (n != 0) {
  1012. n = n >> 1;
  1013. shiftCount++
  1014. }
  1015. if (ratio !== (1 << shiftCount)) {
  1016. throw 'chroma plane dimensions must be power of 2 ratio to luma plane dimensions; got ' + ratio;
  1017. }
  1018. return shiftCount;
  1019. }
  1020. module.exports = depower;
  1021. })();
  1022. },{}],9:[function(require,module,exports){
  1023. /*
  1024. Copyright (c) 2014-2016 Brion Vibber <brion@pobox.com>
  1025. Permission is hereby granted, free of charge, to any person obtaining a copy of
  1026. this software and associated documentation files (the "Software"), to deal in
  1027. the Software without restriction, including without limitation the rights to
  1028. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  1029. the Software, and to permit persons to whom the Software is furnished to do so,
  1030. subject to the following conditions:
  1031. The above copyright notice and this permission notice shall be included in all
  1032. copies or substantial portions of the Software.
  1033. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1034. MPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  1035. FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  1036. COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  1037. IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  1038. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  1039. */
  1040. (function() {
  1041. "use strict";
  1042. var FrameSink = require('./FrameSink.js'),
  1043. SoftwareFrameSink = require('./SoftwareFrameSink.js'),
  1044. WebGLFrameSink = require('./WebGLFrameSink.js');
  1045. /**
  1046. * @typedef {Object} YUVCanvasOptions
  1047. * @property {boolean} webGL - Whether to use WebGL to draw to the canvas and accelerate color space conversion. If left out, defaults to auto-detect.
  1048. */
  1049. var YUVCanvas = {
  1050. FrameSink: FrameSink,
  1051. SoftwareFrameSink: SoftwareFrameSink,
  1052. WebGLFrameSink: WebGLFrameSink,
  1053. /**
  1054. * Attach a suitable FrameSink instance to an HTML5 canvas element.
  1055. *
  1056. * This will take over the drawing context of the canvas and may turn
  1057. * it into a WebGL 3d canvas if possible. Do not attempt to use the
  1058. * drawing context directly after this.
  1059. *
  1060. * @param {HTMLCanvasElement} canvas - HTML canvas element to attach to
  1061. * @param {YUVCanvasOptions} options - map of options
  1062. * @returns {FrameSink} - instance of suitable subclass.
  1063. */
  1064. attach: function(canvas, options) {
  1065. options = options || {};
  1066. var webGL = ('webGL' in options) ? options.webGL : WebGLFrameSink.isAvailable();
  1067. if (webGL) {
  1068. return new WebGLFrameSink(canvas, options);
  1069. } else {
  1070. return new SoftwareFrameSink(canvas, options);
  1071. }
  1072. }
  1073. };
  1074. module.exports = YUVCanvas;
  1075. })();
  1076. },{"./FrameSink.js":4,"./SoftwareFrameSink.js":5,"./WebGLFrameSink.js":6}]},{},[2]);