Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
requirebin sketch
var media = require('rtc-media');
var processor = require('rtc-videoproc');
var vid;
function handleDraw(imageData) {
var channels = imageData.data;
var rgb = [];
var rgbAvg;
var alpha;
var ii;
// check that we have channels is divisible by four (just as a safety)
if (channels.length % 4 !== 0) {
return;
}
// iterate through the data
// NOTE: decrementing loops are fast but you need to know that you will
// hit 0 using this logic otherwise it will run forever (only 0 is falsy)
for (ii = channels.length; ii -= 4; ) {
// get the rgb tuple
rgb = [channels[ii], channels[ii + 1], channels[ii + 2]];
// get the alpha value
alpha = channels[ii + 3];
// calculate the rgb average
rgbAvg = (rgb[0] + rgb[1] + rgb[2] ) / 3;
// update the values to the rgb average
channels[ii] = channels[ii + 1] = channels[ii + 2] = rgbAvg;
}
return true;
}
// capture media
media().render(vid = processor(document.body, {fps:0.2}));
// handle draw events on the fake video
vid.pipeline.add(handleDraw);
function handleDraw(e){var t,n,r,i=e.data,o=[];if(0===i.length%4){for(r=i.length;r-=4;)o=[i[r],i[r+1],i[r+2]],n=i[r+3],t=(o[0]+o[1]+o[2])/3,i[r]=i[r+1]=i[r+2]=t;return!0}}require=function e(t,n,r){function i(s,a){if(!n[s]){if(!t[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);throw Error("Cannot find module '"+s+"'")}var c=n[s]={exports:{}};t[s][0].call(c.exports,function(e){var n=t[s][1][e];return i(n?n:e)},c,c.exports,e,t,n,r)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;r.length>s;s++)i(r[s]);return i}({rP2IBn:[function(e,t){"use strict";function n(e){return this instanceof n?(o.call(this),e&&e instanceof MediaStream&&(e={stream:e,capture:!1,muted:!1}),e&&(e.audio||e.video)&&(e={constraints:e}),e=r({},{capture:!0,muted:!0,constraints:{video:{mandatory:{},optional:[]},audio:!0}},e),this.constraints=e.constraints,this.name=e.name,this.stream=e.stream||null,this.muted=e.muted===void 0||e.muted,this._bindings=[],e.capture&&setTimeout(this.capture.bind(this),0),void 0):new n(e)}e("cog/logger")("media");var r=e("cog/extend"),i=e("rtc-core/detect"),o=e("events").EventEmitter,s=e("util");navigator.getUserMedia=navigator.getUserMedia||i.call(navigator,"getUserMedia"),window.URL=window.URL||i("URL"),window.MediaStream=i("MediaStream"),s.inherits(n,o),t.exports=n,n.prototype.capture=function(e,t){var n=this,r=this.emit.bind(this,"end");this.stream||("function"==typeof e&&(t=e,e=this.constraints),"function"==typeof t&&this.once("capture",t.bind(this)),navigator.getUserMedia(e||this.constraints,function(e){"function"==typeof e.addEventListener?e.addEventListener("ended",r):e.onended=r,n.stream=e,n.emit("capture",e)},this._handleFail.bind(this)))},n.prototype.render=function(e,t,n){return Array.isArray(e)&&(console.log("WARNING: rtc-media render (as of 1.x) expects a single target"),e=e[0]),"function"==typeof t&&(n=t,t={}),t=t||{},e=this._prepareElement(t,e),this.stream?this._bindStream(this.stream):this.once("capture",this._bindStream.bind(this)),"function"==typeof n&&this.once("render",n),e},n.prototype.stop=function(e){var t=this;this.stream&&(this._unbind(e),this.stream.stop(),this.once("capture",t._bindStream.bind(t)),this.stream=null)},n.prototype._prepareElement=function(e,t){var n,r=t instanceof HTMLVideoElement||t instanceof HTMLAudioElement,i=e.preserveAspectRatio===void 0||e.preserveAspectRatio;return r=r||"function"==typeof t.play&&(t.mozSrcObject!==void 0||t.src!==void 0),r||(n=t,t=document.createElement("video"),i&&t.setAttribute("preserveAspectRatio",""),n.appendChild(t),t.setAttribute("data-playing",!1)),t&&this.muted&&t.setAttribute("muted",""),this._bindings.push({el:t,opts:e}),t},n.prototype._bindStream=function(e){function t(){0===o.length&&i.length>0&&(r.emit("render",i[0]),i.map(function(e){e.setAttribute("data-playing",!0)}))}function n(e){var r=e.target||e.srcElement,s=i.indexOf(r);s>=0&&o.splice(s,1),r.removeEventListener("playing",n),t()}var r=this,i=[],o=[];i=this._bindings.map(function(t){return t.el.mozSrcObject!==void 0?t.el.mozSrcObject=e:t.el.src=r._createObjectURL(e)||e,"function"==typeof t.el.play&&t.el.play(),t.el}),o=i.filter(function(e){return 3>e.readyState}),o.map(function(e){e.addEventListener("playing",n,!1)}),t()},n.prototype._unbind=function(e){e=e||{},this._bindings.forEach(function(e){var t=e.el;t.src=null,t.mozSrcObject&&(t.mozSrcObject=null),t.currentSrc&&(t.currentSrc=null)})},n.prototype._createObjectURL=function(e){try{return window.URL.createObjectURL(e)}catch(t){}},n.prototype._handleSuccess=function(e){this.stream=e,this.emit("stream",e)},n.prototype._handleFail=function(e){this.emit("error",e)}},{"cog/extend":3,"cog/logger":4,events:6,"rtc-core/detect":5,util:10}],"rtc-media":[function(e,t){t.exports=e("rP2IBn")},{}],3:[function(e,t){"use strict";t.exports=function(e){return[].slice.call(arguments,1).forEach(function(t){if(t)for(var n in t)e[n]=t[n]}),e}},{}],4:[function(e,t){"use strict";var n=[],r=[],i=[console],o=t.exports=function(e){function t(){return o=n.indexOf("*")>=0||n.indexOf(e)>=0}var o=t();return r[r.length]=t,function(){var t=[].slice.call(arguments);("string"==typeof t[0]||t[0]instanceof String)&&(t[0]=e+": "+t[0]),o&&i.forEach(function(e){e.log.apply(e,t)})}};o.reset=function(){return i=[],n=[],o.enable()},o.to=function(e){return i=i.concat(e||[]),o},o.enable=function(){return n=n.concat([].slice.call(arguments)),r.forEach(function(e){e()}),o}},{}],5:[function(e,t){"use strict";var n={chrome:/Chrom(?:e|ium)\/([0-9]+)\./,firefox:/Firefox\/([0-9]+)\./,opera:/Opera\/([0-9]+)\./},r=t.exports=function(e,t){var n,i,o,s=this||("undefined"!=typeof window?window:void 0);if(s)for(t=(t||["ms","o","moz","webkit"]).concat(""),n=t.length;n--;)if(i=t[n],o=i+(i?e.charAt(0).toUpperCase()+e.slice(1):e),s[o]!==void 0)return r.browser=r.browser||i.toLowerCase(),s[e]=s[o]};r.moz="undefined"!=typeof navigator&&!!navigator.mozGetUserMedia,"undefined"!=typeof navigator?Object.keys(n).forEach(function(e){var t=n[e].exec(navigator.userAgent);t&&(r.browser=e,r.browserVersion=r.version=parseInt(t[1],10))}):(r.browser="node",r.browserVersion=r.version="?")},{}],6:[function(e,t,n){var r=e("__browserify_process");r.EventEmitter||(r.EventEmitter=function(){});var i=n.EventEmitter=r.EventEmitter,o="function"==typeof Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},s=10;i.prototype.setMaxListeners=function(e){this._events||(this._events={}),this._events.maxListeners=e},i.prototype.emit=function(e){if("error"===e&&(!this._events||!this._events.error||o(this._events.error)&&!this._events.error.length))throw arguments[1]instanceof Error?arguments[1]:Error("Uncaught, unspecified 'error' event.");if(!this._events)return!1;var t=this._events[e];if(!t)return!1;if("function"==typeof t){switch(arguments.length){case 1:t.call(this);break;case 2:t.call(this,arguments[1]);break;case 3:t.call(this,arguments[1],arguments[2]);break;default:var n=Array.prototype.slice.call(arguments,1);t.apply(this,n)}return!0}if(o(t)){for(var n=Array.prototype.slice.call(arguments,1),r=t.slice(),i=0,s=r.length;s>i;i++)r[i].apply(this,n);return!0}return!1},i.prototype.addListener=function(e,t){if("function"!=typeof t)throw Error("addListener only takes instances of Function");if(this._events||(this._events={}),this.emit("newListener",e,t),this._events[e])if(o(this._events[e])){if(!this._events[e].warned){var n;n=void 0!==this._events.maxListeners?this._events.maxListeners:s,n&&n>0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),console.trace())}this._events[e].push(t)}else this._events[e]=[this._events[e],t];else this._events[e]=t;return this},i.prototype.on=i.prototype.addListener,i.prototype.once=function(e,t){var n=this;return n.on(e,function r(){n.removeListener(e,r),t.apply(this,arguments)}),this},i.prototype.removeListener=function(e,t){if("function"!=typeof t)throw Error("removeListener only takes instances of Function");if(!this._events||!this._events[e])return this;var n=this._events[e];if(o(n)){var r=n.indexOf(t);if(0>r)return this;n.splice(r,1),0==n.length&&delete this._events[e]}else this._events[e]===t&&delete this._events[e];return this},i.prototype.removeAllListeners=function(e){return e&&this._events&&this._events[e]&&(this._events[e]=null),this},i.prototype.listeners=function(e){return this._events||(this._events={}),this._events[e]||(this._events[e]=[]),o(this._events[e])||(this._events[e]=[this._events[e]]),this._events[e]}},{__browserify_process:8}],7:[function(e,t){t.exports="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},{}],8:[function(e,t){var n=t.exports={};n.nextTick=function(){var e="undefined"!=typeof window&&window.setImmediate,t="undefined"!=typeof window&&window.postMessage&&window.addEventListener;if(e)return function(e){return window.setImmediate(e)};if(t){var n=[];return window.addEventListener("message",function(e){if(e.source===window&&"process-tick"===e.data&&(e.stopPropagation(),n.length>0)){var t=n.shift();t()}},!0),function(e){n.push(e),window.postMessage("process-tick","*")}}return function(e){setTimeout(e,0)}}(),n.title="browser",n.browser=!0,n.env={},n.argv=[],n.binding=function(){throw Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(){throw Error("process.chdir is not supported")}},{}],9:[function(e,t){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.binarySlice}},{}],10:[function(e,t,n){function r(e,t){var r={seen:[],stylize:o};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),h(t)?r.showHidden=t:t&&n._extend(r,t),b(r.showHidden)&&(r.showHidden=!1),b(r.depth)&&(r.depth=2),b(r.colors)&&(r.colors=!1),b(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=i),a(r,e,r.depth)}function i(e,t){var n=r.styles[t];return n?"["+r.colors[n][0]+"m"+e+"["+r.colors[n][1]+"m":e}function o(e){return e}function s(e){var t={};return e.forEach(function(e){t[e]=!0}),t}function a(e,t,r){if(e.customInspect&&t&&S(t.inspect)&&t.inspect!==n.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(r,e);return y(i)||(i=a(e,i,r)),i}var o=u(e,t);if(o)return o;var h=Object.keys(t),v=s(h);if(e.showHidden&&(h=Object.getOwnPropertyNames(t)),0===h.length){if(S(t)){var m=t.name?": "+t.name:"";return e.stylize("[Function"+m+"]","special")}if(_(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(x(t))return e.stylize(Date.prototype.toString.call(t),"date");if(O(t))return c(t)}var g="",w=!1,b=["{","}"];if(d(t)&&(w=!0,b=["[","]"]),S(t)){var E=t.name?": "+t.name:"";g=" [Function"+E+"]"}if(_(t)&&(g=" "+RegExp.prototype.toString.call(t)),x(t)&&(g=" "+Date.prototype.toUTCString.call(t)),O(t)&&(g=" "+c(t)),0===h.length&&(!w||0==t.length))return b[0]+g+b[1];if(0>r)return _(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);var j;return j=w?f(e,t,r,v,h):h.map(function(n){return p(e,t,r,v,n,w)}),e.seen.pop(),l(j,g,b)}function u(e,t){if(b(t))return e.stylize("undefined","undefined");if(y(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return g(t)?e.stylize(""+t,"number"):h(t)?e.stylize(""+t,"boolean"):v(t)?e.stylize("null","null"):void 0}function c(e){return"["+Error.prototype.toString.call(e)+"]"}function f(e,t,n,r,i){for(var o=[],s=0,a=t.length;a>s;++s)M(t,s+"")?o.push(p(e,t,n,r,s+"",!0)):o.push("");return i.forEach(function(i){i.match(/^\d+$/)||o.push(p(e,t,n,r,i,!0))}),o}function p(e,t,n,r,i,o){var s,u,c;if(c=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]},c.get?u=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(u=e.stylize("[Setter]","special")),M(r,i)||(s="["+i+"]"),u||(0>e.seen.indexOf(c.value)?(u=v(n)?a(e,c.value,null):a(e,c.value,n-1),u.indexOf("\n")>-1&&(u=o?u.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+u.split("\n").map(function(e){return" "+e}).join("\n"))):u=e.stylize("[Circular]","special")),b(s)){if(o&&i.match(/^\d+$/))return u;s=JSON.stringify(""+i),s.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=e.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=e.stylize(s,"string"))}return s+": "+u}function l(e,t,n){var r=0,i=e.reduce(function(e,t){return r++,t.indexOf("\n")>=0&&r++,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);return i>60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}function d(e){return Array.isArray(e)}function h(e){return"boolean"==typeof e}function v(e){return null===e}function m(e){return null==e}function g(e){return"number"==typeof e}function y(e){return"string"==typeof e}function w(e){return"symbol"==typeof e}function b(e){return void 0===e}function _(e){return E(e)&&"[object RegExp]"===L(e)}function E(e){return"object"==typeof e&&null!==e}function x(e){return E(e)&&"[object Date]"===L(e)}function O(e){return E(e)&&("[object Error]"===L(e)||e instanceof Error)}function S(e){return"function"==typeof e}function j(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||e===void 0}function L(e){return Object.prototype.toString.call(e)}function z(e){return 10>e?"0"+e.toString(10):e.toString(10)}function A(){var e=new Date,t=[z(e.getHours()),z(e.getMinutes()),z(e.getSeconds())].join(":");return[e.getDate(),I[e.getMonth()],t].join(" ")}function M(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var R=e("__browserify_process"),U="undefined"!=typeof self?self:"undefined"!=typeof window?window:{},k=/%[sdj%]/g;n.format=function(e){if(!y(e)){for(var t=[],n=0;arguments.length>n;n++)t.push(r(arguments[n]));return t.join(" ")}for(var n=1,i=arguments,o=i.length,s=(e+"").replace(k,function(e){if("%%"===e)return"%";if(n>=o)return e;switch(e){case"%s":return i[n++]+"";case"%d":return Number(i[n++]);case"%j":try{return JSON.stringify(i[n++])}catch(t){return"[Circular]"}default:return e}}),a=i[n];o>n;a=i[++n])s+=v(a)||!E(a)?" "+a:" "+r(a);return s},n.deprecate=function(e,t){function r(){if(!i){if(R.throwDeprecation)throw Error(t);R.traceDeprecation?console.trace(t):console.error(t),i=!0}return e.apply(this,arguments)}if(b(U.process))return function(){return n.deprecate(e,t).apply(this,arguments)};if(R.noDeprecation===!0)return e;var i=!1;return r};var D,C={};n.debuglog=function(e){if(b(D)&&(D=R.env.NODE_DEBUG||""),e=e.toUpperCase(),!C[e])if(RegExp("\\b"+e+"\\b","i").test(D)){var t=R.pid;C[e]=function(){var r=n.format.apply(n,arguments);console.error("%s %d: %s",e,t,r)}}else C[e]=function(){};return C[e]},n.inspect=r,r.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},r.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"},n.isArray=d,n.isBoolean=h,n.isNull=v,n.isNullOrUndefined=m,n.isNumber=g,n.isString=y,n.isSymbol=w,n.isUndefined=b,n.isRegExp=_,n.isObject=E,n.isDate=x,n.isError=O,n.isFunction=S,n.isPrimitive=j,n.isBuffer=e("./support/isBuffer");var I=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];n.log=function(){console.log("%s - %s",A(),n.format.apply(n,arguments))},n.inherits=e("inherits"),n._extend=function(e,t){if(!t||!E(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e}},{"./support/isBuffer":9,__browserify_process:8,inherits:7}]},{},[]),require=function e(t,n,r){function i(s,a){if(!n[s]){if(!t[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);throw Error("Cannot find module '"+s+"'")}var c=n[s]={exports:{}};t[s][0].call(c.exports,function(e){var n=t[s][1][e];return i(n?n:e)},c,c.exports,e,t,n,r)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;r.length>s;s++)i(r[s]);return i}({tPek8I:[function(e,t){"use strict";function n(e,t,n){function o(e){b=w.push(e)}function s(n){var r,o,a;if(d){if(n=n||Date.now(),n-h>m){if(l.drawImage(t,g,y,u,c),a=_&&new CustomEvent("frame",{detail:{tick:n}}),a&&e.dispatchEvent(a),b){for(r=l.getImageData(0,0,u,c),o=!1,p=0;b>p;p++)o=w[p](r,l,e,f)||o;o&&l.putImageData(r,0,0)}h=n}i(s)}}function a(){var n,r,o;(0===e.width||0===e.height)&&(e.width=t.videoWidth,e.height=t.videoHeight),0!==e.width&&0!==e.height&&(n=Math.min(r=e.width/t.videoWidth,o=e.height/t.videoHeight),u=0|t.videoWidth*n,c=0|t.videoHeight*n,g=e.width-u>>1,y=e.height-c>>1,f={x:g,y:y,width:u,height:c},d=!0,i(s))}var u,c,f,p,l=e.getContext("2d"),d=!1,h=0,v=(n||{}).fps||r,m=0|1e3/v,g=0,y=0,w=[],b=0,_="undefined"!=typeof CustomEvent;return t.addEventListener("playing",a),["mozSrcObject","src"].forEach(function(n){void 0!==t[n]&&Object.defineProperty(e,n,{get:function(){return t[n]},set:function(e){t[n]=e}})}),e.play=function(){t.play()},{add:o}}var r=25,i=e("fdom/raf");t.exports=function(e,t){var r=e instanceof HTMLCanvasElement?e:document.createElement("canvas"),i=e instanceof HTMLVideoElement?e:document.createElement("video");return e===i?i.parentNode.insertBefore(r,i):e!==r&&e.appendChild(r),r.width=(t||{}).width||0,r.height=(t||{}).height||0,i.style.display="none",r.pipeline=n(r,i,t),r}},{"fdom/raf":3}],"rtc-videoproc":[function(e,t){t.exports=e("tPek8I")},{}],3:[function(e,t){"use strict";var n=["r","webkitR","mozR","oR","msR"];t.exports="undefined"!=typeof window&&function(){for(var e=0;n.length>e;e++)window.animFrame=window.animFrame||window[n[e]+"equestAnimationFrame"];return animFrame}()},{}]},{},[]);var media=require("rtc-media"),processor=require("rtc-videoproc"),vid;media().render(vid=processor(document.body,{fps:.2})),vid.pipeline.add(handleDraw);
<style type='text/css'>html, body { margin: 0; padding: 0; border: 0; }
body, html { height: 100%; width: 100%; }</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment