Index: openacs-4/packages/xowf/lib/inclass-exam.wf =================================================================== RCS file: /usr/local/cvsroot/openacs-4/packages/xowf/lib/Attic/inclass-exam.wf,v diff -u -N -r1.1.2.40 -r1.1.2.41 --- openacs-4/packages/xowf/lib/inclass-exam.wf 4 Aug 2020 16:16:17 -0000 1.1.2.40 +++ openacs-4/packages/xowf/lib/inclass-exam.wf 31 Aug 2020 15:40:24 -0000 1.1.2.41 @@ -634,7 +634,9 @@ set user_id [$i creation_user] set img_url [:pretty_link -query m=proctor-image&user_id=$user_id] - set proctoring_dir [acs_root_dir]/proctoring/${:item_id}/$user_id/ + set proctoring_dir [proctoring::folder \ + -object_id ${:item_id} \ + -user_id $user_id] set files [glob -nocomplain -path $proctoring_dir *.*] #ns_log notice "proctoring_dir $proctoring_dir files $files" @@ -817,19 +819,18 @@ ::xo::cc set_parameter template_file view-plain-master ::xo::cc set_parameter MenuBar 0 - if {[file exists [acs_package_root_dir xowf]/lib/proctored-page.adp]} { + set proctoring_template [acs_package_root_dir proctoring-support]/lib/proctored-page + if {[file exists ${proctoring_template}.adp]} { set object_id ${:item_id} set object_url $link - set upload_url /xowf-proctoring-upload if {[string match *p.try_out_mode=1* $link]} { #set examination_statement_p 0 set examination_statement_url "" } - ${:package_id} return_page -adp /packages/xowf/lib/proctored-page -variables { + ${:package_id} return_page -adp $proctoring_template -variables { object_id object_url - upload_url examination_statement_url } } else { @@ -849,8 +850,9 @@ set ts [${:package_id} query_parameter ts:integer ""] set ext [${:package_id} query_parameter e:wordchar ""] set user_id [${:package_id} query_parameter user_id:integer ""] - set id ${:item_id} - set proctoring_dir [acs_root_dir]/proctoring/$id/$user_id + set proctoring_dir [proctoring::folder \ + -object_id ${:item_id} \ + -user_id $user_id] set png_path $proctoring_dir/$type-$ts.$ext #ns_log notice "image: $png_path ... [ad_file exists $$png_path]" ns_returnfile 200 [ns_guesstype $ts.$ext] $png_path Index: openacs-4/packages/xowf/lib/proctored-page.adp =================================================================== RCS file: /usr/local/cvsroot/openacs-4/packages/xowf/lib/Attic/proctored-page.adp,v diff -u -N --- openacs-4/packages/xowf/lib/proctored-page.adp 27 Jul 2020 11:13:35 -0000 1.1.2.2 +++ /dev/null 1 Jan 1970 00:00:00 -0000 @@ -1,239 +0,0 @@ - - 1 - 0 - 0 - 0 - - - - - -
-
@msg.proctoring_banner@
- -
- -
-
-
- -
- - - Index: openacs-4/packages/xowf/lib/proctored-page.tcl =================================================================== RCS file: /usr/local/cvsroot/openacs-4/packages/xowf/lib/Attic/proctored-page.tcl,v diff -u -N --- openacs-4/packages/xowf/lib/proctored-page.tcl 6 Aug 2020 20:05:30 -0000 1.1.2.2 +++ /dev/null 1 Jan 1970 00:00:00 -0000 @@ -1,208 +0,0 @@ -ad_include_contract { - Embed proctoring support in a page. - - This template creates and empty page embedding specified URL in an - iframe surrounded by proctoring support. - - This kind of proctoring will take snapshots from camera and - desktop at random intervals and upload them to specified URL. - - @param exam_id Id of the exam. This can be e.g. the item_id of the - exam object. - @param exam_url URL of the actual exam, which will be included in - an iframe. - @param min_ms_interval miniumum time to the next snapshot in - missliseconds - @param max_ms_interval maximum time to the next snapshot in - milliseconds. - @param audio_p decides if we record audio. Every time some input - longer than min_audio_duration is detected from the - microphone, a recording will be started and terminated at - the next silence, or once it reaches max_audio_duration - @param min_audio_duration minimum audio duration to start - recording in seconds - @param max_audio_duration max audio duration in seconds. Once - reached, recording will stop and resume at the next - detected audio segment. - @param preview_p if specified, a preview of recorded inputs will - be displayed to users during proctored session - @param proctoring_p Do the actual proctoring. Can be disabled to - display just the exmaination statement - @param examination_statement_p Display the examination statement - @param examination_statement_url URL we are calling in order to - store acceptance of the examination statement. It will - receive 'object_id' as query parameter. - @param upload_url URL for the backend receiving and storing the - collected snapshots. It will receive 'name' (device name, - either camera or desktop), item_id (exam_id), and the - file. Current default URL is real and will store the - pictures in the /proctoring folder under acs_root_dir. - - @author Antonio Pisano (antonio@elettrotecnica.it) - @author Gustaf Neumann -} { - object_url:localurl - object_id:naturalnum,notnull - {min_ms_interval:naturalnum 1000} - {max_ms_interval:naturalnum 60000} - {audio_p:boolean true} - {min_audio_duration:naturalnum 2} - {max_audio_duration:naturalnum 60} - {preview_p:boolean true} - {proctoring_p:boolean true} - {examination_statement_p:boolean true} - {examination_statement_url:localurl "/examination-statement-accept"} - {upload_url:localurl "/proctoring-upload"} -} - -if {0} { - # - # Add the following two files to the www (or subsite/www) - # directory of your site. This should be handled more elegantly, - # probably via registering the handline directly by naviserver - # during package init. - # - #### www/proctoring-upload.adp - - ### www/proctoring-upload.tcl - ad_page_contract { - } { - name:oneof(camera|desktop),notnull - type:oneof(image|audio),notnull - object_id:naturalnum,notnull - file - file.tmpfile - } -} - -if {[apm_package_installed_p tlf-lrn-core]} { - set msg(missing_stream) [_ tlf-lrn-core.proctoring_missing_stream_message] - set msg(proctoring_accept) [_ tlf-lrn-core.proctoring_accept_message] - set msg(exam_mode) [_ tlf-lrn-core.Exam_mode_message] - set msg(proctoring_banner) [_ tlf-lrn-core.proctoring_banner_message] - set msg(accept) [_ tlf-lrn-core.Accept] -} else { - set msg(missing_stream) "missing stream" - set msg(proctoring_accept) { - An automated exam-supervision is activated to detect any - fraudulent examination performance. You and your screen will - be recorded. Your data will only be used for the stated - purpose, will be stored securely and will not be passed on to - third parties. - } - set msg(proctoring_banner) "This browser window is running in exam mode. Close this browser window after the exam." - set msg(accept) "Accept" - set msg(exam_mode) { -

Examination Statement

-
1.) Participation
-

Only students who are officially registered for the course and/or the examination may take the exam.

-

The exam is only graded if all 3 of the following conditions have been fulfilled:

- - -

If you have received the examination but not fulfilled the - identity requirement and/or confirmed your consent to online - supervision, the examination will be declared VOID and will count - as an examination attempt. If you have not confirmed that you have - read and understood this examination statement, your examination - will not be graded and the attempt will not be counted.

- -
2.) Technical requirements
- -

It is your responsibility to ensure that you will not be - disturbed during the examination and that all technical - requirements (as previously announced) are fulfilled (see - "Information on this examination environment" and/or "Confirmation - of access to examination" in your online exam environment).
-  

- -
3.) Starting and terminating/interrupting the examination
- -

By confirming that you have read and understood this - examination statement, you also confirm receipt of the - examination, and the attempt will be counted. The exam will be - graded and counted towards your total number of permissible - examination attempts. This applies even if you terminate the exam - prematurely or do not submit your completed exam.

- -

If you are forced to terminate the exam prematurely or - interrupt the exam due to technical difficulties (e.g. loss of - your internet connection), please contact the person responsible - for the examination without delay. To do so, please use the team - set up in Microsoft Teams specifically for the exam in - question. Report the termination/interruption of your exam in the - channel "Reporting technical difficulties" and be sure to include - the following information:

- - - -

If you are able to solve the problem and continue with the - exam, please report this on the same Microsoft Teams channel with - the message "Examination resumed." You will find the direct link - to Teams in the portlet "Information on this examination - environment" on the starting page of the examination - environment. We recommend downloading and installing the Microsoft - Teams desktop app both on your computer and on your mobile - device.

- -

All instances of termination/interruption reported - through this channel will be reviewed individually to decide if - the examination will be graded and the attempt counted towards the - student's total number of permissible attempts.
 

- -
4.) Cheating and identity confirmation
- -

Any attempt to cheat on the exam (e.g. cell phone, consulting - forbidden materials, consulting other people) will result in the - exam being declared VOID and the examination attempt counted. You - will also be blocked from re-registering to repeat the examination - for a period of 4 months starting from the examination date.

- -

To confirm your identity, you will be required to upload a - photo of your face and the student ID or other official photo ID - to the online examination environment. If anyone attempts to take - an exam on behalf of another person, he or she will - without exception be reported to the public - prosecutor's office for charges of forgery, which may result in a - criminal record.

If announced in advance by the person - responsible for the exam, automated online examination supervision - will be conducted for the duration of the exam. This means that - you and your screen will be monitored by camera and microphone - throughout the exam, and the examiner will be able to see and hear - the recording. You need to consent to this supervision in advance - in the online examination environment under "Consent to automated - online supervision." As soon as you start the exam, you will need - to give your browser permission to access your screen, webcam, and - microphone.
 

- -
5.) Permissible aids
- -

When taking this examination, you may use only the aids - explicitly listed by the person responsible for the examination - under "Information on this online examination environment."

- } -} - -set mobile_p [ad_conn mobile_p] -set preview_p [expr {$preview_p ? true : false}] -set proctoring_p [expr {$proctoring_p ? true : false}] - -# -# Local variables: -# mode: tcl -# tcl-indent-level: 2 -# indent-tabs-mode: nil -# End: Index: openacs-4/packages/xowf/lib/proctoring-upload.tcl =================================================================== RCS file: /usr/local/cvsroot/openacs-4/packages/xowf/lib/Attic/proctoring-upload.tcl,v diff -u -N --- openacs-4/packages/xowf/lib/proctoring-upload.tcl 14 Jul 2020 20:16:18 -0000 1.1.2.1 +++ /dev/null 1 Jan 1970 00:00:00 -0000 @@ -1,67 +0,0 @@ -ad_include_contract { - - Implements the upload backend for proctoring, which can be used as - is or inside e.g. an object method. - - @author Antonio Pisano (antonio@elettrotecnica.it) -} { - name:oneof(camera|desktop),notnull - type:oneof(image|audio),notnull - object_id:naturalnum,notnull - file - file.tmpfile -} - -auth::require_login - -set user_id [ad_conn user_id] - -#set proctoring_dir [::tlf_lrn_core::proctoring::folder \ -# -object_id $object_id -user_id $user_id] -#set gif_path $proctoring_dir/${name}.gif -set proctoring_dir [acs_root_dir]/proctoring/$object_id/$user_id - -# if {[ad_file exists $gif_path]} { -# ns_log warning "Proctoring: gif exists in $gif-path" -# ns_return 200 text/plain "OK" -# ad_script_abort -# } -if {$type eq "audio"} { - set mime_type [exec [util::which file] --mime-type -b ${file.tmpfile}] -} else { - set mime_type [ns_imgmime ${file.tmpfile}] -} -if {($type eq "image" && ![regexp {^image/(.*)$} $mime_type m extension]) || - ($type eq "audio" && ![regexp {^video/(.*)$} $mime_type m extension]) -} { - ns_log warning "Proctoring: user $user_id uploaded a non-$type ($mime_type) file for object $object_id" - ns_return 500 text/plain "KO" - ad_script_abort -} - -set timestamp [clock seconds] -set file_path $proctoring_dir/${name}-${type}-$timestamp.$extension - -file mkdir -- $proctoring_dir -file rename -force -- ${file.tmpfile} $file_path - -catch { - set requestSize [expr {[ns_conn headerlength] + [ns_conn contentlength]}] - ns_log notice "Proctoring: saving file $png_path - REQ size = $requestSize" -} - -set message [subst -nocommands { - {user_id: "$user_id" name: "$name", type: "$type", timestamp: "$timestamp", file: "$file_path"} -}] - -#set message [::ws::build_msg $message] - -set chat proctoring-${object_id} -#ns_log warning "Sending to chat $chat" -#::ws::multicast $chat $message - -set chat proctoring-${object_id}-${user_id} -#ns_log warning "Sending to chat $chat" -#::ws::multicast $chat $message - -ns_return 200 text/plain OK Index: openacs-4/packages/xowf/www/resources/proctoring/gif.js =================================================================== RCS file: /usr/local/cvsroot/openacs-4/packages/xowf/www/resources/proctoring/Attic/gif.js,v diff -u -N --- openacs-4/packages/xowf/www/resources/proctoring/gif.js 14 Jul 2020 20:16:18 -0000 1.1.2.1 +++ /dev/null 1 Jan 1970 00:00:00 -0000 @@ -1,3 +0,0 @@ -// gif.js 0.2.0 - https://github.com/jnordberg/gif.js -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.GIF=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],2:[function(require,module,exports){var UA,browser,mode,platform,ua;ua=navigator.userAgent.toLowerCase();platform=navigator.platform.toLowerCase();UA=ua.match(/(opera|ie|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]([\w\d\.]+)|$)/)||[null,"unknown",0];mode=UA[1]==="ie"&&document.documentMode;browser={name:UA[1]==="version"?UA[3]:UA[1],version:mode||parseFloat(UA[1]==="opera"&&UA[4]?UA[4]:UA[2]),platform:{name:ua.match(/ip(?:ad|od|hone)/)?"ios":(ua.match(/(?:webos|android)/)||platform.match(/mac|win|linux/)||["other"])[0]}};browser[browser.name]=true;browser[browser.name+parseInt(browser.version,10)]=true;browser.platform[browser.platform.name]=true;module.exports=browser},{}],3:[function(require,module,exports){var EventEmitter,GIF,browser,extend=function(child,parent){for(var key in parent){if(hasProp.call(parent,key))child[key]=parent[key]}function ctor(){this.constructor=child}ctor.prototype=parent.prototype;child.prototype=new ctor;child.__super__=parent.prototype;return child},hasProp={}.hasOwnProperty,indexOf=[].indexOf||function(item){for(var i=0,l=this.length;iref;i=0<=ref?++j:--j){results.push(null)}return results}.call(this);numWorkers=this.spawnWorkers();if(this.options.globalPalette===true){this.renderNextFrame()}else{for(i=j=0,ref=numWorkers;0<=ref?jref;i=0<=ref?++j:--j){this.renderNextFrame()}}this.emit("start");return this.emit("progress",0)};GIF.prototype.abort=function(){var worker;while(true){worker=this.activeWorkers.shift();if(worker==null){break}this.log("killing active worker");worker.terminate()}this.running=false;return this.emit("abort")};GIF.prototype.spawnWorkers=function(){var j,numWorkers,ref,results;numWorkers=Math.min(this.options.workers,this.frames.length);(function(){results=[];for(var j=ref=this.freeWorkers.length;ref<=numWorkers?jnumWorkers;ref<=numWorkers?j++:j--){results.push(j)}return results}).apply(this).forEach(function(_this){return function(i){var worker;_this.log("spawning worker "+i);worker=new Worker(_this.options.workerScript);worker.onmessage=function(event){_this.activeWorkers.splice(_this.activeWorkers.indexOf(worker),1);_this.freeWorkers.push(worker);return _this.frameFinished(event.data)};return _this.freeWorkers.push(worker)}}(this));return numWorkers};GIF.prototype.frameFinished=function(frame){var i,j,ref;this.log("frame "+frame.index+" finished - "+this.activeWorkers.length+" active");this.finishedFrames++;this.emit("progress",this.finishedFrames/this.frames.length);this.imageParts[frame.index]=frame;if(this.options.globalPalette===true){this.options.globalPalette=frame.globalPalette;this.log("global palette analyzed");if(this.frames.length>2){for(i=j=1,ref=this.freeWorkers.length;1<=ref?jref;i=1<=ref?++j:--j){this.renderNextFrame()}}}if(indexOf.call(this.imageParts,null)>=0){return this.renderNextFrame()}else{return this.finishRendering()}};GIF.prototype.finishRendering=function(){var data,frame,i,image,j,k,l,len,len1,len2,len3,offset,page,ref,ref1,ref2;len=0;ref=this.imageParts;for(j=0,len1=ref.length;j=this.frames.length){return}frame=this.frames[this.nextFrame++];worker=this.freeWorkers.shift();task=this.getTask(frame);this.log("starting frame "+(task.index+1)+" of "+this.frames.length);this.activeWorkers.push(worker);return worker.postMessage(task)};GIF.prototype.getContextData=function(ctx){return ctx.getImageData(0,0,this.options.width,this.options.height).data};GIF.prototype.getImageData=function(image){var ctx;if(this._canvas==null){this._canvas=document.createElement("canvas");this._canvas.width=this.options.width;this._canvas.height=this.options.height}ctx=this._canvas.getContext("2d");ctx.setFill=this.options.background;ctx.fillRect(0,0,this.options.width,this.options.height);ctx.drawImage(image,0,0);return this.getContextData(ctx)};GIF.prototype.getTask=function(frame){var index,task;index=this.frames.indexOf(frame);task={index:index,last:index===this.frames.length-1,delay:frame.delay,transparent:frame.transparent,width:this.options.width,height:this.options.height,quality:this.options.quality,dither:this.options.dither,globalPalette:this.options.globalPalette,repeat:this.options.repeat,canTransfer:browser.name==="chrome"};if(frame.data!=null){task.data=frame.data}else if(frame.context!=null){task.data=this.getContextData(frame.context)}else if(frame.image!=null){task.data=this.getImageData(frame.image)}else{throw new Error("Invalid frame")}return task};GIF.prototype.log=function(){var args;args=1<=arguments.length?slice.call(arguments,0):[];if(!this.options.debug){return}return console.log.apply(console,args)};return GIF}(EventEmitter);module.exports=GIF},{"./browser.coffee":2,events:1}]},{},[3])(3)}); -//# sourceMappingURL=gif.js.map Index: openacs-4/packages/xowf/www/resources/proctoring/gif.js.map =================================================================== RCS file: /usr/local/cvsroot/openacs-4/packages/xowf/www/resources/proctoring/Attic/gif.js.map,v diff -u -N --- openacs-4/packages/xowf/www/resources/proctoring/gif.js.map 14 Jul 2020 20:16:18 -0000 1.1.2.1 +++ /dev/null 1 Jan 1970 00:00:00 -0000 @@ -1 +0,0 @@ -{"version":3,"sources":["node_modules/browser-pack/_prelude.js","node_modules/events/events.js","src/browser.coffee","src/gif.coffee"],"names":["f","exports","module","define","amd","g","window","global","self","this","GIF","e","t","n","r","s","o","u","a","require","i","Error","code","l","call","length","1","EventEmitter","_events","_maxListeners","undefined","prototype","defaultMaxListeners","setMaxListeners","isNumber","isNaN","TypeError","emit","type","er","handler","len","args","listeners","error","isObject","arguments","err","context","isUndefined","isFunction","Array","slice","apply","addListener","listener","m","newListener","push","warned","console","trace","on","once","fired","removeListener","list","position","splice","removeAllListeners","key","ret","listenerCount","evlistener","emitter","arg","UA","browser","mode","platform","ua","navigator","userAgent","toLowerCase","match","document","documentMode","name","version","parseFloat","parseInt","extend","child","parent","hasProp","ctor","constructor","__super__","superClass","defaults","frameDefaults","workerScript","workers","repeat","background","quality","width","height","transparent","debug","dither","delay","copy","options","base","value","running","frames","freeWorkers","activeWorkers","setOptions","setOption","_canvas","results","addFrame","image","frame","ImageData","data","CanvasRenderingContext2D","WebGLRenderingContext","getContextData","childNodes","getImageData","render","j","numWorkers","ref","nextFrame","finishedFrames","imageParts","spawnWorkers","globalPalette","renderNextFrame","abort","worker","shift","log","terminate","Math","min","forEach","_this","Worker","onmessage","event","indexOf","frameFinished","index","finishRendering","k","len1","len2","len3","offset","page","ref1","ref2","pageSize","cursor","round","Uint8Array","set","Blob","task","getTask","postMessage","ctx","createElement","getContext","setFill","fillRect","drawImage","last","canTransfer"],"mappings":";CAAA,SAAAA,GAAA,SAAAC,WAAA,gBAAAC,UAAA,YAAA,CAAAA,OAAAD,QAAAD,QAAA,UAAAG,UAAA,YAAAA,OAAAC,IAAA,CAAAD,UAAAH,OAAA,CAAA,GAAAK,EAAA,UAAAC,UAAA,YAAA,CAAAD,EAAAC,WAAA,UAAAC,UAAA,YAAA,CAAAF,EAAAE,WAAA,UAAAC,QAAA,YAAA,CAAAH,EAAAG,SAAA,CAAAH,EAAAI,KAAAJ,EAAAK,IAAAV,OAAA,WAAA,GAAAG,QAAAD,OAAAD,OAAA,OAAA,SAAAU,GAAAC,EAAAC,EAAAC,GAAA,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AaP,MAAMD,WAD7B,CAGH,KAAU,IAAAxG,OAAM,iBAElB,MAAOyJ,qBAET3B,IAAK,WACH,GAAAzG,KADIA,MAAA,GAAAI,UAAArB,OAAA2B,MAAA5B,KAAAsB,UAAA,KACJ,KAAcrC,KAACwG,QAAQJ,MAAvB,CAAA,aACAjD,SAAQuF,IAAR9F,MAAAO,QAAYlB,mBA1MEf,aA6MlBzB,QAAOD,QAAUS","sourceRoot":"","sourcesContent":["(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw f.code=\"MODULE_NOT_FOUND\",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(node) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n if (typeof console.trace === 'function') {\n // not supported in IE 10\n console.trace();\n }\n }\n }\n\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n var fired = false;\n\n function g() {\n this.removeListener(type, g);\n\n if (!fired) {\n fired = true;\n listener.apply(this, arguments);\n }\n }\n\n g.listener = listener;\n this.on(type, g);\n\n return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n var list, position, length, i;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events || !this._events[type])\n return this;\n\n list = this._events[type];\n length = list.length;\n position = -1;\n\n if (list === listener ||\n (isFunction(list.listener) && list.listener === listener)) {\n delete this._events[type];\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n\n } else if (isObject(list)) {\n for (i = length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list.length = 0;\n delete this._events[type];\n } else {\n list.splice(position, 1);\n }\n\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n var key, listeners;\n\n if (!this._events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!this._events.removeListener) {\n if (arguments.length === 0)\n this._events = {};\n else if (this._events[type])\n delete this._events[type];\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n for (key in this._events) {\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = {};\n return this;\n }\n\n listeners = this._events[type];\n\n if (isFunction(listeners)) {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n while (listeners.length)\n this.removeListener(type, listeners[listeners.length - 1]);\n }\n delete this._events[type];\n\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n var ret;\n if (!this._events || !this._events[type])\n ret = [];\n else if (isFunction(this._events[type]))\n ret = [this._events[type]];\n else\n ret = this._events[type].slice();\n return ret;\n};\n\nEventEmitter.prototype.listenerCount = function(type) {\n if (this._events) {\n var evlistener = this._events[type];\n\n if (isFunction(evlistener))\n return 1;\n else if (evlistener)\n return evlistener.length;\n }\n return 0;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n return emitter.listenerCount(type);\n};\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\n","### CoffeeScript version of the browser detection from MooTools ###\n\nua = navigator.userAgent.toLowerCase()\nplatform = navigator.platform.toLowerCase()\nUA = ua.match(/(opera|ie|firefox|chrome|version)[\\s\\/:]([\\w\\d\\.]+)?.*?(safari|version[\\s\\/:]([\\w\\d\\.]+)|$)/) or [null, 'unknown', 0]\nmode = UA[1] == 'ie' && document.documentMode\n\nbrowser =\n name: if UA[1] is 'version' then UA[3] else UA[1]\n version: mode or parseFloat(if UA[1] is 'opera' && UA[4] then UA[4] else UA[2])\n\n platform:\n name: if ua.match(/ip(?:ad|od|hone)/) then 'ios' else (ua.match(/(?:webos|android)/) or platform.match(/mac|win|linux/) or ['other'])[0]\n\nbrowser[browser.name] = true\nbrowser[browser.name + parseInt(browser.version, 10)] = true\nbrowser.platform[browser.platform.name] = true\n\nmodule.exports = browser\n","{EventEmitter} = require 'events'\nbrowser = require './browser.coffee'\n\nclass GIF extends EventEmitter\n\n defaults =\n workerScript: 'gif.worker.js'\n workers: 2\n repeat: 0 # repeat forever, -1 = repeat once\n background: '#fff'\n quality: 10 # pixel sample interval, lower is better\n width: null # size derermined from first frame if possible\n height: null\n transparent: null\n debug: false\n dither: false # see GIFEncoder.js for dithering options\n\n frameDefaults =\n delay: 500 # ms\n copy: false\n\n constructor: (options) ->\n @running = false\n\n @options = {}\n @frames = []\n\n @freeWorkers = []\n @activeWorkers = []\n\n @setOptions options\n for key, value of defaults\n @options[key] ?= value\n\n setOption: (key, value) ->\n @options[key] = value\n if @_canvas? and key in ['width', 'height']\n @_canvas[key] = value\n\n setOptions: (options) ->\n @setOption key, value for own key, value of options\n\n addFrame: (image, options={}) ->\n frame = {}\n frame.transparent = @options.transparent\n for key of frameDefaults\n frame[key] = options[key] or frameDefaults[key]\n\n # use the images width and height for options unless already set\n @setOption 'width', image.width unless @options.width?\n @setOption 'height', image.height unless @options.height?\n\n if ImageData? and image instanceof ImageData\n frame.data = image.data\n else if (CanvasRenderingContext2D? and image instanceof CanvasRenderingContext2D) or (WebGLRenderingContext? and image instanceof WebGLRenderingContext)\n if options.copy\n frame.data = @getContextData image\n else\n frame.context = image\n else if image.childNodes?\n if options.copy\n frame.data = @getImageData image\n else\n frame.image = image\n else\n throw new Error 'Invalid image'\n\n @frames.push frame\n\n render: ->\n throw new Error 'Already running' if @running\n\n if not @options.width? or not @options.height?\n throw new Error 'Width and height must be set prior to rendering'\n\n @running = true\n @nextFrame = 0\n @finishedFrames = 0\n\n @imageParts = (null for i in [0...@frames.length])\n numWorkers = @spawnWorkers()\n # we need to wait for the palette\n if @options.globalPalette == true\n @renderNextFrame()\n else\n @renderNextFrame() for i in [0...numWorkers]\n\n @emit 'start'\n @emit 'progress', 0\n\n abort: ->\n loop\n worker = @activeWorkers.shift()\n break unless worker?\n @log 'killing active worker'\n worker.terminate()\n @running = false\n @emit 'abort'\n\n # private\n\n spawnWorkers: ->\n numWorkers = Math.min(@options.workers, @frames.length)\n [@freeWorkers.length...numWorkers].forEach (i) =>\n @log \"spawning worker #{ i }\"\n worker = new Worker @options.workerScript\n worker.onmessage = (event) =>\n @activeWorkers.splice @activeWorkers.indexOf(worker), 1\n @freeWorkers.push worker\n @frameFinished event.data\n @freeWorkers.push worker\n return numWorkers\n\n frameFinished: (frame) ->\n @log \"frame #{ frame.index } finished - #{ @activeWorkers.length } active\"\n @finishedFrames++\n @emit 'progress', @finishedFrames / @frames.length\n @imageParts[frame.index] = frame\n # remember calculated palette, spawn the rest of the workers\n if @options.globalPalette == true\n @options.globalPalette = frame.globalPalette\n @log 'global palette analyzed'\n @renderNextFrame() for i in [1...@freeWorkers.length] if @frames.length > 2\n if null in @imageParts\n @renderNextFrame()\n else\n @finishRendering()\n\n finishRendering: ->\n len = 0\n for frame in @imageParts\n len += (frame.data.length - 1) * frame.pageSize + frame.cursor\n len += frame.pageSize - frame.cursor\n @log \"rendering finished - filesize #{ Math.round(len / 1000) }kb\"\n data = new Uint8Array len\n offset = 0\n for frame in @imageParts\n for page, i in frame.data\n data.set page, offset\n if i is frame.data.length - 1\n offset += frame.cursor\n else\n offset += frame.pageSize\n\n image = new Blob [data],\n type: 'image/gif'\n\n @emit 'finished', image, data\n\n renderNextFrame: ->\n throw new Error 'No free workers' if @freeWorkers.length is 0\n return if @nextFrame >= @frames.length # no new frame to render\n\n frame = @frames[@nextFrame++]\n worker = @freeWorkers.shift()\n task = @getTask frame\n\n @log \"starting frame #{ task.index + 1 } of #{ @frames.length }\"\n @activeWorkers.push worker\n worker.postMessage task#, [task.data.buffer]\n\n getContextData: (ctx) ->\n return ctx.getImageData(0, 0, @options.width, @options.height).data\n\n getImageData: (image) ->\n if not @_canvas?\n @_canvas = document.createElement 'canvas'\n @_canvas.width = @options.width\n @_canvas.height = @options.height\n\n ctx = @_canvas.getContext '2d'\n ctx.setFill = @options.background\n ctx.fillRect 0, 0, @options.width, @options.height\n ctx.drawImage image, 0, 0\n\n return @getContextData ctx\n\n getTask: (frame) ->\n index = @frames.indexOf frame\n task =\n index: index\n last: index is (@frames.length - 1)\n delay: frame.delay\n transparent: frame.transparent\n width: @options.width\n height: @options.height\n quality: @options.quality\n dither: @options.dither\n globalPalette: @options.globalPalette\n repeat: @options.repeat\n canTransfer: (browser.name is 'chrome')\n\n if frame.data?\n task.data = frame.data\n else if frame.context?\n task.data = @getContextData frame.context\n else if frame.image?\n task.data = @getImageData frame.image\n else\n throw new Error 'Invalid frame'\n\n return task\n\n log: (args...) ->\n return unless @options.debug\n console.log args...\n\n\nmodule.exports = GIF\n"]} \ No newline at end of file Index: openacs-4/packages/xowf/www/resources/proctoring/gif.worker.js =================================================================== RCS file: /usr/local/cvsroot/openacs-4/packages/xowf/www/resources/proctoring/Attic/gif.worker.js,v diff -u -N --- openacs-4/packages/xowf/www/resources/proctoring/gif.worker.js 14 Jul 2020 20:16:18 -0000 1.1.2.1 +++ /dev/null 1 Jan 1970 00:00:00 -0000 @@ -1,3 +0,0 @@ -// gif.worker.js 0.2.0 - https://github.com/jnordberg/gif.js -(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o=ByteArray.pageSize)this.newPage();this.pages[this.page][this.cursor++]=val};ByteArray.prototype.writeUTFBytes=function(string){for(var l=string.length,i=0;i=0)this.dispose=disposalCode};GIFEncoder.prototype.setRepeat=function(repeat){this.repeat=repeat};GIFEncoder.prototype.setTransparent=function(color){this.transparent=color};GIFEncoder.prototype.addFrame=function(imageData){this.image=imageData;this.colorTab=this.globalPalette&&this.globalPalette.slice?this.globalPalette:null;this.getImagePixels();this.analyzePixels();if(this.globalPalette===true)this.globalPalette=this.colorTab;if(this.firstFrame){this.writeLSD();this.writePalette();if(this.repeat>=0){this.writeNetscapeExt()}}this.writeGraphicCtrlExt();this.writeImageDesc();if(!this.firstFrame&&!this.globalPalette)this.writePalette();this.writePixels();this.firstFrame=false};GIFEncoder.prototype.finish=function(){this.out.writeByte(59)};GIFEncoder.prototype.setQuality=function(quality){if(quality<1)quality=1;this.sample=quality};GIFEncoder.prototype.setDither=function(dither){if(dither===true)dither="FloydSteinberg";this.dither=dither};GIFEncoder.prototype.setGlobalPalette=function(palette){this.globalPalette=palette};GIFEncoder.prototype.getGlobalPalette=function(){return this.globalPalette&&this.globalPalette.slice&&this.globalPalette.slice(0)||this.globalPalette};GIFEncoder.prototype.writeHeader=function(){this.out.writeUTFBytes("GIF89a")};GIFEncoder.prototype.analyzePixels=function(){if(!this.colorTab){this.neuQuant=new NeuQuant(this.pixels,this.sample);this.neuQuant.buildColormap();this.colorTab=this.neuQuant.getColormap()}if(this.dither){this.ditherPixels(this.dither.replace("-serpentine",""),this.dither.match(/-serpentine/)!==null)}else{this.indexPixels()}this.pixels=null;this.colorDepth=8;this.palSize=7;if(this.transparent!==null){this.transIndex=this.findClosest(this.transparent,true)}};GIFEncoder.prototype.indexPixels=function(imgq){var nPix=this.pixels.length/3;this.indexedPixels=new Uint8Array(nPix);var k=0;for(var j=0;j=0&&x1+x=0&&y1+y>16,(c&65280)>>8,c&255,used)};GIFEncoder.prototype.findClosestRGB=function(r,g,b,used){if(this.colorTab===null)return-1;if(this.neuQuant&&!used){return this.neuQuant.lookupRGB(r,g,b)}var c=b|g<<8|r<<16;var minpos=0;var dmin=256*256*256;var len=this.colorTab.length;for(var i=0,index=0;i=0){disp=dispose&7}disp<<=2;this.out.writeByte(0|disp|0|transp);this.writeShort(this.delay);this.out.writeByte(this.transIndex);this.out.writeByte(0)};GIFEncoder.prototype.writeImageDesc=function(){this.out.writeByte(44);this.writeShort(0);this.writeShort(0);this.writeShort(this.width);this.writeShort(this.height);if(this.firstFrame||this.globalPalette){this.out.writeByte(0)}else{this.out.writeByte(128|0|0|0|this.palSize)}};GIFEncoder.prototype.writeLSD=function(){this.writeShort(this.width);this.writeShort(this.height);this.out.writeByte(128|112|0|this.palSize);this.out.writeByte(0);this.out.writeByte(0)};GIFEncoder.prototype.writeNetscapeExt=function(){this.out.writeByte(33);this.out.writeByte(255);this.out.writeByte(11);this.out.writeUTFBytes("NETSCAPE2.0");this.out.writeByte(3);this.out.writeByte(1);this.writeShort(this.repeat);this.out.writeByte(0)};GIFEncoder.prototype.writePalette=function(){this.out.writeBytes(this.colorTab);var n=3*256-this.colorTab.length;for(var i=0;i>8&255)};GIFEncoder.prototype.writePixels=function(){var enc=new LZWEncoder(this.width,this.height,this.indexedPixels,this.colorDepth);enc.encode(this.out)};GIFEncoder.prototype.stream=function(){return this.out};module.exports=GIFEncoder},{"./LZWEncoder.js":2,"./TypedNeuQuant.js":3}],2:[function(require,module,exports){var EOF=-1;var BITS=12;var HSIZE=5003;var masks=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535];function LZWEncoder(width,height,pixels,colorDepth){var initCodeSize=Math.max(2,colorDepth);var accum=new Uint8Array(256);var htab=new Int32Array(HSIZE);var codetab=new Int32Array(HSIZE);var cur_accum,cur_bits=0;var a_count;var free_ent=0;var maxcode;var clear_flg=false;var g_init_bits,ClearCode,EOFCode;function char_out(c,outs){accum[a_count++]=c;if(a_count>=254)flush_char(outs)}function cl_block(outs){cl_hash(HSIZE);free_ent=ClearCode+2;clear_flg=true;output(ClearCode,outs)}function cl_hash(hsize){for(var i=0;i=0){disp=hsize_reg-i;if(i===0)disp=1;do{if((i-=disp)<0)i+=hsize_reg;if(htab[i]===fcode){ent=codetab[i];continue outer_loop}}while(htab[i]>=0)}output(ent,outs);ent=c;if(free_ent<1<0){outs.writeByte(a_count);outs.writeBytes(accum,0,a_count);a_count=0}}function MAXCODE(n_bits){return(1<0)cur_accum|=code<=8){char_out(cur_accum&255,outs);cur_accum>>=8;cur_bits-=8}if(free_ent>maxcode||clear_flg){if(clear_flg){maxcode=MAXCODE(n_bits=g_init_bits);clear_flg=false}else{++n_bits;if(n_bits==BITS)maxcode=1<0){char_out(cur_accum&255,outs);cur_accum>>=8;cur_bits-=8}flush_char(outs)}}this.encode=encode}module.exports=LZWEncoder},{}],3:[function(require,module,exports){var ncycles=100;var netsize=256;var maxnetpos=netsize-1;var netbiasshift=4;var intbiasshift=16;var intbias=1<>betashift;var betagamma=intbias<>3;var radiusbiasshift=6;var radiusbias=1<>3);var i,v;for(i=0;i>=netbiasshift;network[i][1]>>=netbiasshift;network[i][2]>>=netbiasshift;network[i][3]=i}}function altersingle(alpha,i,b,g,r){network[i][0]-=alpha*(network[i][0]-b)/initalpha;network[i][1]-=alpha*(network[i][1]-g)/initalpha;network[i][2]-=alpha*(network[i][2]-r)/initalpha}function alterneigh(radius,i,b,g,r){var lo=Math.abs(i-radius);var hi=Math.min(i+radius,netsize);var j=i+1;var k=i-1;var m=1;var p,a;while(jlo){a=radpower[m++];if(jlo){p=network[k--];p[0]-=a*(p[0]-b)/alpharadbias;p[1]-=a*(p[1]-g)/alpharadbias;p[2]-=a*(p[2]-r)/alpharadbias}}}function contest(b,g,r){var bestd=~(1<<31);var bestbiasd=bestd;var bestpos=-1;var bestbiaspos=bestpos;var i,n,dist,biasdist,betafreq;for(i=0;i>intbiasshift-netbiasshift);if(biasdist>betashift;freq[i]-=betafreq;bias[i]+=betafreq<>1;for(j=previouscol+1;j>1;for(j=previouscol+1;j<256;j++)netindex[j]=maxnetpos}function inxsearch(b,g,r){var a,p,dist;var bestd=1e3;var best=-1;var i=netindex[g];var j=i-1;while(i=0){if(i=bestd)i=netsize;else{i++;if(dist<0)dist=-dist;a=p[0]-b;if(a<0)a=-a;dist+=a;if(dist=0){p=network[j];dist=g-p[1];if(dist>=bestd)j=-1;else{j--;if(dist<0)dist=-dist;a=p[0]-b;if(a<0)a=-a;dist+=a;if(dist>radiusbiasshift;if(rad<=1)rad=0;for(i=0;i=lengthcount)pix-=lengthcount;i++;if(delta===0)delta=1;if(i%delta===0){alpha-=alpha/alphadec;radius-=radius/radiusdec;rad=radius>>radiusbiasshift;if(rad<=1)rad=0;for(j=0;j= ByteArray.pageSize) this.newPage();\n this.pages[this.page][this.cursor++] = val;\n};\n\nByteArray.prototype.writeUTFBytes = function(string) {\n for (var l = string.length, i = 0; i < l; i++)\n this.writeByte(string.charCodeAt(i));\n};\n\nByteArray.prototype.writeBytes = function(array, offset, length) {\n for (var l = length || array.length, i = offset || 0; i < l; i++)\n this.writeByte(array[i]);\n};\n\nfunction GIFEncoder(width, height) {\n // image size\n this.width = ~~width;\n this.height = ~~height;\n\n // transparent color if given\n this.transparent = null;\n\n // transparent index in color table\n this.transIndex = 0;\n\n // -1 = no repeat, 0 = forever. anything else is repeat count\n this.repeat = -1;\n\n // frame delay (hundredths)\n this.delay = 0;\n\n this.image = null; // current frame\n this.pixels = null; // BGR byte array from frame\n this.indexedPixels = null; // converted frame indexed to palette\n this.colorDepth = null; // number of bit planes\n this.colorTab = null; // RGB palette\n this.neuQuant = null; // NeuQuant instance that was used to generate this.colorTab.\n this.usedEntry = new Array(); // active palette entries\n this.palSize = 7; // color table size (bits-1)\n this.dispose = -1; // disposal code (-1 = use default)\n this.firstFrame = true;\n this.sample = 10; // default sample interval for quantizer\n this.dither = false; // default dithering\n this.globalPalette = false;\n\n this.out = new ByteArray();\n}\n\n/*\n Sets the delay time between each frame, or changes it for subsequent frames\n (applies to last frame added)\n*/\nGIFEncoder.prototype.setDelay = function(milliseconds) {\n this.delay = Math.round(milliseconds / 10);\n};\n\n/*\n Sets frame rate in frames per second.\n*/\nGIFEncoder.prototype.setFrameRate = function(fps) {\n this.delay = Math.round(100 / fps);\n};\n\n/*\n Sets the GIF frame disposal code for the last added frame and any\n subsequent frames.\n\n Default is 0 if no transparent color has been set, otherwise 2.\n*/\nGIFEncoder.prototype.setDispose = function(disposalCode) {\n if (disposalCode >= 0) this.dispose = disposalCode;\n};\n\n/*\n Sets the number of times the set of GIF frames should be played.\n\n -1 = play once\n 0 = repeat indefinitely\n\n Default is -1\n\n Must be invoked before the first image is added\n*/\n\nGIFEncoder.prototype.setRepeat = function(repeat) {\n this.repeat = repeat;\n};\n\n/*\n Sets the transparent color for the last added frame and any subsequent\n frames. Since all colors are subject to modification in the quantization\n process, the color in the final palette for each frame closest to the given\n color becomes the transparent color for that frame. May be set to null to\n indicate no transparent color.\n*/\nGIFEncoder.prototype.setTransparent = function(color) {\n this.transparent = color;\n};\n\n/*\n Adds next GIF frame. The frame is not written immediately, but is\n actually deferred until the next frame is received so that timing\n data can be inserted. Invoking finish() flushes all frames.\n*/\nGIFEncoder.prototype.addFrame = function(imageData) {\n this.image = imageData;\n\n this.colorTab = this.globalPalette && this.globalPalette.slice ? this.globalPalette : null;\n\n this.getImagePixels(); // convert to correct format if necessary\n this.analyzePixels(); // build color table & map pixels\n\n if (this.globalPalette === true) this.globalPalette = this.colorTab;\n\n if (this.firstFrame) {\n this.writeLSD(); // logical screen descriptior\n this.writePalette(); // global color table\n if (this.repeat >= 0) {\n // use NS app extension to indicate reps\n this.writeNetscapeExt();\n }\n }\n\n this.writeGraphicCtrlExt(); // write graphic control extension\n this.writeImageDesc(); // image descriptor\n if (!this.firstFrame && !this.globalPalette) this.writePalette(); // local color table\n this.writePixels(); // encode and write pixel data\n\n this.firstFrame = false;\n};\n\n/*\n Adds final trailer to the GIF stream, if you don't call the finish method\n the GIF stream will not be valid.\n*/\nGIFEncoder.prototype.finish = function() {\n this.out.writeByte(0x3b); // gif trailer\n};\n\n/*\n Sets quality of color quantization (conversion of images to the maximum 256\n colors allowed by the GIF specification). Lower values (minimum = 1)\n produce better colors, but slow processing significantly. 10 is the\n default, and produces good color mapping at reasonable speeds. Values\n greater than 20 do not yield significant improvements in speed.\n*/\nGIFEncoder.prototype.setQuality = function(quality) {\n if (quality < 1) quality = 1;\n this.sample = quality;\n};\n\n/*\n Sets dithering method. Available are:\n - FALSE no dithering\n - TRUE or FloydSteinberg\n - FalseFloydSteinberg\n - Stucki\n - Atkinson\n You can add '-serpentine' to use serpentine scanning\n*/\nGIFEncoder.prototype.setDither = function(dither) {\n if (dither === true) dither = 'FloydSteinberg';\n this.dither = dither;\n};\n\n/*\n Sets global palette for all frames.\n You can provide TRUE to create global palette from first picture.\n Or an array of r,g,b,r,g,b,...\n*/\nGIFEncoder.prototype.setGlobalPalette = function(palette) {\n this.globalPalette = palette;\n};\n\n/*\n Returns global palette used for all frames.\n If setGlobalPalette(true) was used, then this function will return\n calculated palette after the first frame is added.\n*/\nGIFEncoder.prototype.getGlobalPalette = function() {\n return (this.globalPalette && this.globalPalette.slice && this.globalPalette.slice(0)) || this.globalPalette;\n};\n\n/*\n Writes GIF file header\n*/\nGIFEncoder.prototype.writeHeader = function() {\n this.out.writeUTFBytes(\"GIF89a\");\n};\n\n/*\n Analyzes current frame colors and creates color map.\n*/\nGIFEncoder.prototype.analyzePixels = function() {\n if (!this.colorTab) {\n this.neuQuant = new NeuQuant(this.pixels, this.sample);\n this.neuQuant.buildColormap(); // create reduced palette\n this.colorTab = this.neuQuant.getColormap();\n }\n\n // map image pixels to new palette\n if (this.dither) {\n this.ditherPixels(this.dither.replace('-serpentine', ''), this.dither.match(/-serpentine/) !== null);\n } else {\n this.indexPixels();\n }\n\n this.pixels = null;\n this.colorDepth = 8;\n this.palSize = 7;\n\n // get closest match to transparent color if specified\n if (this.transparent !== null) {\n this.transIndex = this.findClosest(this.transparent, true);\n }\n};\n\n/*\n Index pixels, without dithering\n*/\nGIFEncoder.prototype.indexPixels = function(imgq) {\n var nPix = this.pixels.length / 3;\n this.indexedPixels = new Uint8Array(nPix);\n var k = 0;\n for (var j = 0; j < nPix; j++) {\n var index = this.findClosestRGB(\n this.pixels[k++] & 0xff,\n this.pixels[k++] & 0xff,\n this.pixels[k++] & 0xff\n );\n this.usedEntry[index] = true;\n this.indexedPixels[j] = index;\n }\n};\n\n/*\n Taken from http://jsbin.com/iXofIji/2/edit by PAEz\n*/\nGIFEncoder.prototype.ditherPixels = function(kernel, serpentine) {\n var kernels = {\n FalseFloydSteinberg: [\n [3 / 8, 1, 0],\n [3 / 8, 0, 1],\n [2 / 8, 1, 1]\n ],\n FloydSteinberg: [\n [7 / 16, 1, 0],\n [3 / 16, -1, 1],\n [5 / 16, 0, 1],\n [1 / 16, 1, 1]\n ],\n Stucki: [\n [8 / 42, 1, 0],\n [4 / 42, 2, 0],\n [2 / 42, -2, 1],\n [4 / 42, -1, 1],\n [8 / 42, 0, 1],\n [4 / 42, 1, 1],\n [2 / 42, 2, 1],\n [1 / 42, -2, 2],\n [2 / 42, -1, 2],\n [4 / 42, 0, 2],\n [2 / 42, 1, 2],\n [1 / 42, 2, 2]\n ],\n Atkinson: [\n [1 / 8, 1, 0],\n [1 / 8, 2, 0],\n [1 / 8, -1, 1],\n [1 / 8, 0, 1],\n [1 / 8, 1, 1],\n [1 / 8, 0, 2]\n ]\n };\n\n if (!kernel || !kernels[kernel]) {\n throw 'Unknown dithering kernel: ' + kernel;\n }\n\n var ds = kernels[kernel];\n var index = 0,\n height = this.height,\n width = this.width,\n data = this.pixels;\n var direction = serpentine ? -1 : 1;\n\n this.indexedPixels = new Uint8Array(this.pixels.length / 3);\n\n for (var y = 0; y < height; y++) {\n\n if (serpentine) direction = direction * -1;\n\n for (var x = (direction == 1 ? 0 : width - 1), xend = (direction == 1 ? width : 0); x !== xend; x += direction) {\n\n index = (y * width) + x;\n // Get original colour\n var idx = index * 3;\n var r1 = data[idx];\n var g1 = data[idx + 1];\n var b1 = data[idx + 2];\n\n // Get converted colour\n idx = this.findClosestRGB(r1, g1, b1);\n this.usedEntry[idx] = true;\n this.indexedPixels[index] = idx;\n idx *= 3;\n var r2 = this.colorTab[idx];\n var g2 = this.colorTab[idx + 1];\n var b2 = this.colorTab[idx + 2];\n\n var er = r1 - r2;\n var eg = g1 - g2;\n var eb = b1 - b2;\n\n for (var i = (direction == 1 ? 0: ds.length - 1), end = (direction == 1 ? ds.length : 0); i !== end; i += direction) {\n var x1 = ds[i][1]; // *direction; // Should this by timesd by direction?..to make the kernel go in the opposite direction....got no idea....\n var y1 = ds[i][2];\n if (x1 + x >= 0 && x1 + x < width && y1 + y >= 0 && y1 + y < height) {\n var d = ds[i][0];\n idx = index + x1 + (y1 * width);\n idx *= 3;\n\n data[idx] = Math.max(0, Math.min(255, data[idx] + er * d));\n data[idx + 1] = Math.max(0, Math.min(255, data[idx + 1] + eg * d));\n data[idx + 2] = Math.max(0, Math.min(255, data[idx + 2] + eb * d));\n }\n }\n }\n }\n};\n\n/*\n Returns index of palette color closest to c\n*/\nGIFEncoder.prototype.findClosest = function(c, used) {\n return this.findClosestRGB((c & 0xFF0000) >> 16, (c & 0x00FF00) >> 8, (c & 0x0000FF), used);\n};\n\nGIFEncoder.prototype.findClosestRGB = function(r, g, b, used) {\n if (this.colorTab === null) return -1;\n\n if (this.neuQuant && !used) {\n return this.neuQuant.lookupRGB(r, g, b);\n }\n \n var c = b | (g << 8) | (r << 16);\n\n var minpos = 0;\n var dmin = 256 * 256 * 256;\n var len = this.colorTab.length;\n\n for (var i = 0, index = 0; i < len; index++) {\n var dr = r - (this.colorTab[i++] & 0xff);\n var dg = g - (this.colorTab[i++] & 0xff);\n var db = b - (this.colorTab[i++] & 0xff);\n var d = dr * dr + dg * dg + db * db;\n if ((!used || this.usedEntry[index]) && (d < dmin)) {\n dmin = d;\n minpos = index;\n }\n }\n\n return minpos;\n};\n\n/*\n Extracts image pixels into byte array pixels\n (removes alphachannel from canvas imagedata)\n*/\nGIFEncoder.prototype.getImagePixels = function() {\n var w = this.width;\n var h = this.height;\n this.pixels = new Uint8Array(w * h * 3);\n\n var data = this.image;\n var srcPos = 0;\n var count = 0;\n\n for (var i = 0; i < h; i++) {\n for (var j = 0; j < w; j++) {\n this.pixels[count++] = data[srcPos++];\n this.pixels[count++] = data[srcPos++];\n this.pixels[count++] = data[srcPos++];\n srcPos++;\n }\n }\n};\n\n/*\n Writes Graphic Control Extension\n*/\nGIFEncoder.prototype.writeGraphicCtrlExt = function() {\n this.out.writeByte(0x21); // extension introducer\n this.out.writeByte(0xf9); // GCE label\n this.out.writeByte(4); // data block size\n\n var transp, disp;\n if (this.transparent === null) {\n transp = 0;\n disp = 0; // dispose = no action\n } else {\n transp = 1;\n disp = 2; // force clear if using transparent color\n }\n\n if (this.dispose >= 0) {\n disp = dispose & 7; // user override\n }\n disp <<= 2;\n\n // packed fields\n this.out.writeByte(\n 0 | // 1:3 reserved\n disp | // 4:6 disposal\n 0 | // 7 user input - 0 = none\n transp // 8 transparency flag\n );\n\n this.writeShort(this.delay); // delay x 1/100 sec\n this.out.writeByte(this.transIndex); // transparent color index\n this.out.writeByte(0); // block terminator\n};\n\n/*\n Writes Image Descriptor\n*/\nGIFEncoder.prototype.writeImageDesc = function() {\n this.out.writeByte(0x2c); // image separator\n this.writeShort(0); // image position x,y = 0,0\n this.writeShort(0);\n this.writeShort(this.width); // image size\n this.writeShort(this.height);\n\n // packed fields\n if (this.firstFrame || this.globalPalette) {\n // no LCT - GCT is used for first (or only) frame\n this.out.writeByte(0);\n } else {\n // specify normal LCT\n this.out.writeByte(\n 0x80 | // 1 local color table 1=yes\n 0 | // 2 interlace - 0=no\n 0 | // 3 sorted - 0=no\n 0 | // 4-5 reserved\n this.palSize // 6-8 size of color table\n );\n }\n};\n\n/*\n Writes Logical Screen Descriptor\n*/\nGIFEncoder.prototype.writeLSD = function() {\n // logical screen size\n this.writeShort(this.width);\n this.writeShort(this.height);\n\n // packed fields\n this.out.writeByte(\n 0x80 | // 1 : global color table flag = 1 (gct used)\n 0x70 | // 2-4 : color resolution = 7\n 0x00 | // 5 : gct sort flag = 0\n this.palSize // 6-8 : gct size\n );\n\n this.out.writeByte(0); // background color index\n this.out.writeByte(0); // pixel aspect ratio - assume 1:1\n};\n\n/*\n Writes Netscape application extension to define repeat count.\n*/\nGIFEncoder.prototype.writeNetscapeExt = function() {\n this.out.writeByte(0x21); // extension introducer\n this.out.writeByte(0xff); // app extension label\n this.out.writeByte(11); // block size\n this.out.writeUTFBytes('NETSCAPE2.0'); // app id + auth code\n this.out.writeByte(3); // sub-block size\n this.out.writeByte(1); // loop sub-block id\n this.writeShort(this.repeat); // loop count (extra iterations, 0=repeat forever)\n this.out.writeByte(0); // block terminator\n};\n\n/*\n Writes color table\n*/\nGIFEncoder.prototype.writePalette = function() {\n this.out.writeBytes(this.colorTab);\n var n = (3 * 256) - this.colorTab.length;\n for (var i = 0; i < n; i++)\n this.out.writeByte(0);\n};\n\nGIFEncoder.prototype.writeShort = function(pValue) {\n this.out.writeByte(pValue & 0xFF);\n this.out.writeByte((pValue >> 8) & 0xFF);\n};\n\n/*\n Encodes and writes pixel data\n*/\nGIFEncoder.prototype.writePixels = function() {\n var enc = new LZWEncoder(this.width, this.height, this.indexedPixels, this.colorDepth);\n enc.encode(this.out);\n};\n\n/*\n Retrieves the GIF stream\n*/\nGIFEncoder.prototype.stream = function() {\n return this.out;\n};\n\nmodule.exports = GIFEncoder;\n","/*\n LZWEncoder.js\n\n Authors\n Kevin Weiner (original Java version - kweiner@fmsware.com)\n Thibault Imbert (AS3 version - bytearray.org)\n Johan Nordberg (JS version - code@johan-nordberg.com)\n\n Acknowledgements\n GIFCOMPR.C - GIF Image compression routines\n Lempel-Ziv compression based on 'compress'. GIF modifications by\n David Rowley (mgardi@watdcsu.waterloo.edu)\n GIF Image compression - modified 'compress'\n Based on: compress.c - File compression ala IEEE Computer, June 1984.\n By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas)\n Jim McKie (decvax!mcvax!jim)\n Steve Davies (decvax!vax135!petsd!peora!srd)\n Ken Turkowski (decvax!decwrl!turtlevax!ken)\n James A. Woods (decvax!ihnp4!ames!jaw)\n Joe Orost (decvax!vax135!petsd!joe)\n*/\n\nvar EOF = -1;\nvar BITS = 12;\nvar HSIZE = 5003; // 80% occupancy\nvar masks = [0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F,\n 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF,\n 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF];\n\nfunction LZWEncoder(width, height, pixels, colorDepth) {\n var initCodeSize = Math.max(2, colorDepth);\n\n var accum = new Uint8Array(256);\n var htab = new Int32Array(HSIZE);\n var codetab = new Int32Array(HSIZE);\n\n var cur_accum, cur_bits = 0;\n var a_count;\n var free_ent = 0; // first unused entry\n var maxcode;\n\n // block compression parameters -- after all codes are used up,\n // and compression rate changes, start over.\n var clear_flg = false;\n\n // Algorithm: use open addressing double hashing (no chaining) on the\n // prefix code / next character combination. We do a variant of Knuth's\n // algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime\n // secondary probe. Here, the modular division first probe is gives way\n // to a faster exclusive-or manipulation. Also do block compression with\n // an adaptive reset, whereby the code table is cleared when the compression\n // ratio decreases, but after the table fills. The variable-length output\n // codes are re-sized at this point, and a special CLEAR code is generated\n // for the decompressor. Late addition: construct the table according to\n // file size for noticeable speed improvement on small files. Please direct\n // questions about this implementation to ames!jaw.\n var g_init_bits, ClearCode, EOFCode;\n\n // Add a character to the end of the current packet, and if it is 254\n // characters, flush the packet to disk.\n function char_out(c, outs) {\n accum[a_count++] = c;\n if (a_count >= 254) flush_char(outs);\n }\n\n // Clear out the hash table\n // table clear for block compress\n function cl_block(outs) {\n cl_hash(HSIZE);\n free_ent = ClearCode + 2;\n clear_flg = true;\n output(ClearCode, outs);\n }\n\n // Reset code table\n function cl_hash(hsize) {\n for (var i = 0; i < hsize; ++i) htab[i] = -1;\n }\n\n function compress(init_bits, outs) {\n var fcode, c, i, ent, disp, hsize_reg, hshift;\n\n // Set up the globals: g_init_bits - initial number of bits\n g_init_bits = init_bits;\n\n // Set up the necessary values\n clear_flg = false;\n n_bits = g_init_bits;\n maxcode = MAXCODE(n_bits);\n\n ClearCode = 1 << (init_bits - 1);\n EOFCode = ClearCode + 1;\n free_ent = ClearCode + 2;\n\n a_count = 0; // clear packet\n\n ent = nextPixel();\n\n hshift = 0;\n for (fcode = HSIZE; fcode < 65536; fcode *= 2) ++hshift;\n hshift = 8 - hshift; // set hash code range bound\n hsize_reg = HSIZE;\n cl_hash(hsize_reg); // clear hash table\n\n output(ClearCode, outs);\n\n outer_loop: while ((c = nextPixel()) != EOF) {\n fcode = (c << BITS) + ent;\n i = (c << hshift) ^ ent; // xor hashing\n if (htab[i] === fcode) {\n ent = codetab[i];\n continue;\n } else if (htab[i] >= 0) { // non-empty slot\n disp = hsize_reg - i; // secondary hash (after G. Knott)\n if (i === 0) disp = 1;\n do {\n if ((i -= disp) < 0) i += hsize_reg;\n if (htab[i] === fcode) {\n ent = codetab[i];\n continue outer_loop;\n }\n } while (htab[i] >= 0);\n }\n output(ent, outs);\n ent = c;\n if (free_ent < 1 << BITS) {\n codetab[i] = free_ent++; // code -> hashtable\n htab[i] = fcode;\n } else {\n cl_block(outs);\n }\n }\n\n // Put out the final code.\n output(ent, outs);\n output(EOFCode, outs);\n }\n\n function encode(outs) {\n outs.writeByte(initCodeSize); // write \"initial code size\" byte\n remaining = width * height; // reset navigation variables\n curPixel = 0;\n compress(initCodeSize + 1, outs); // compress and write the pixel data\n outs.writeByte(0); // write block terminator\n }\n\n // Flush the packet to disk, and reset the accumulator\n function flush_char(outs) {\n if (a_count > 0) {\n outs.writeByte(a_count);\n outs.writeBytes(accum, 0, a_count);\n a_count = 0;\n }\n }\n\n function MAXCODE(n_bits) {\n return (1 << n_bits) - 1;\n }\n\n // Return the next pixel from the image\n function nextPixel() {\n if (remaining === 0) return EOF;\n --remaining;\n var pix = pixels[curPixel++];\n return pix & 0xff;\n }\n\n function output(code, outs) {\n cur_accum &= masks[cur_bits];\n\n if (cur_bits > 0) cur_accum |= (code << cur_bits);\n else cur_accum = code;\n\n cur_bits += n_bits;\n\n while (cur_bits >= 8) {\n char_out((cur_accum & 0xff), outs);\n cur_accum >>= 8;\n cur_bits -= 8;\n }\n\n // If the next entry is going to be too big for the code size,\n // then increase it, if possible.\n if (free_ent > maxcode || clear_flg) {\n if (clear_flg) {\n maxcode = MAXCODE(n_bits = g_init_bits);\n clear_flg = false;\n } else {\n ++n_bits;\n if (n_bits == BITS) maxcode = 1 << BITS;\n else maxcode = MAXCODE(n_bits);\n }\n }\n\n if (code == EOFCode) {\n // At EOF, write the rest of the buffer.\n while (cur_bits > 0) {\n char_out((cur_accum & 0xff), outs);\n cur_accum >>= 8;\n cur_bits -= 8;\n }\n flush_char(outs);\n }\n }\n\n this.encode = encode;\n}\n\nmodule.exports = LZWEncoder;\n","/* NeuQuant Neural-Net Quantization Algorithm\n * ------------------------------------------\n *\n * Copyright (c) 1994 Anthony Dekker\n *\n * NEUQUANT Neural-Net quantization algorithm by Anthony Dekker, 1994.\n * See \"Kohonen neural networks for optimal colour quantization\"\n * in \"Network: Computation in Neural Systems\" Vol. 5 (1994) pp 351-367.\n * for a discussion of the algorithm.\n * See also http://members.ozemail.com.au/~dekker/NEUQUANT.HTML\n *\n * Any party obtaining a copy of these files from the author, directly or\n * indirectly, is granted, free of charge, a full and unrestricted irrevocable,\n * world-wide, paid up, royalty-free, nonexclusive right and license to deal\n * in this software and documentation files (the \"Software\"), including without\n * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons who receive\n * copies from any such party to do so, with the only requirement being\n * that this copyright notice remain intact.\n *\n * (JavaScript port 2012 by Johan Nordberg)\n */\n\nvar ncycles = 100; // number of learning cycles\nvar netsize = 256; // number of colors used\nvar maxnetpos = netsize - 1;\n\n// defs for freq and bias\nvar netbiasshift = 4; // bias for colour values\nvar intbiasshift = 16; // bias for fractions\nvar intbias = (1 << intbiasshift);\nvar gammashift = 10;\nvar gamma = (1 << gammashift);\nvar betashift = 10;\nvar beta = (intbias >> betashift); /* beta = 1/1024 */\nvar betagamma = (intbias << (gammashift - betashift));\n\n// defs for decreasing radius factor\nvar initrad = (netsize >> 3); // for 256 cols, radius starts\nvar radiusbiasshift = 6; // at 32.0 biased by 6 bits\nvar radiusbias = (1 << radiusbiasshift);\nvar initradius = (initrad * radiusbias); //and decreases by a\nvar radiusdec = 30; // factor of 1/30 each cycle\n\n// defs for decreasing alpha factor\nvar alphabiasshift = 10; // alpha starts at 1.0\nvar initalpha = (1 << alphabiasshift);\nvar alphadec; // biased by 10 bits\n\n/* radbias and alpharadbias used for radpower calculation */\nvar radbiasshift = 8;\nvar radbias = (1 << radbiasshift);\nvar alpharadbshift = (alphabiasshift + radbiasshift);\nvar alpharadbias = (1 << alpharadbshift);\n\n// four primes near 500 - assume no image has a length so large that it is\n// divisible by all four primes\nvar prime1 = 499;\nvar prime2 = 491;\nvar prime3 = 487;\nvar prime4 = 503;\nvar minpicturebytes = (3 * prime4);\n\n/*\n Constructor: NeuQuant\n\n Arguments:\n\n pixels - array of pixels in RGB format\n samplefac - sampling factor 1 to 30 where lower is better quality\n\n >\n > pixels = [r, g, b, r, g, b, r, g, b, ..]\n >\n*/\nfunction NeuQuant(pixels, samplefac) {\n var network; // int[netsize][4]\n var netindex; // for network lookup - really 256\n\n // bias and freq arrays for learning\n var bias;\n var freq;\n var radpower;\n\n /*\n Private Method: init\n\n sets up arrays\n */\n function init() {\n network = [];\n netindex = new Int32Array(256);\n bias = new Int32Array(netsize);\n freq = new Int32Array(netsize);\n radpower = new Int32Array(netsize >> 3);\n\n var i, v;\n for (i = 0; i < netsize; i++) {\n v = (i << (netbiasshift + 8)) / netsize;\n network[i] = new Float64Array([v, v, v, 0]);\n //network[i] = [v, v, v, 0]\n freq[i] = intbias / netsize;\n bias[i] = 0;\n }\n }\n\n /*\n Private Method: unbiasnet\n\n unbiases network to give byte values 0..255 and record position i to prepare for sort\n */\n function unbiasnet() {\n for (var i = 0; i < netsize; i++) {\n network[i][0] >>= netbiasshift;\n network[i][1] >>= netbiasshift;\n network[i][2] >>= netbiasshift;\n network[i][3] = i; // record color number\n }\n }\n\n /*\n Private Method: altersingle\n\n moves neuron *i* towards biased (b,g,r) by factor *alpha*\n */\n function altersingle(alpha, i, b, g, r) {\n network[i][0] -= (alpha * (network[i][0] - b)) / initalpha;\n network[i][1] -= (alpha * (network[i][1] - g)) / initalpha;\n network[i][2] -= (alpha * (network[i][2] - r)) / initalpha;\n }\n\n /*\n Private Method: alterneigh\n\n moves neurons in *radius* around index *i* towards biased (b,g,r) by factor *alpha*\n */\n function alterneigh(radius, i, b, g, r) {\n var lo = Math.abs(i - radius);\n var hi = Math.min(i + radius, netsize);\n\n var j = i + 1;\n var k = i - 1;\n var m = 1;\n\n var p, a;\n while ((j < hi) || (k > lo)) {\n a = radpower[m++];\n\n if (j < hi) {\n p = network[j++];\n p[0] -= (a * (p[0] - b)) / alpharadbias;\n p[1] -= (a * (p[1] - g)) / alpharadbias;\n p[2] -= (a * (p[2] - r)) / alpharadbias;\n }\n\n if (k > lo) {\n p = network[k--];\n p[0] -= (a * (p[0] - b)) / alpharadbias;\n p[1] -= (a * (p[1] - g)) / alpharadbias;\n p[2] -= (a * (p[2] - r)) / alpharadbias;\n }\n }\n }\n\n /*\n Private Method: contest\n\n searches for biased BGR values\n */\n function contest(b, g, r) {\n /*\n finds closest neuron (min dist) and updates freq\n finds best neuron (min dist-bias) and returns position\n for frequently chosen neurons, freq[i] is high and bias[i] is negative\n bias[i] = gamma * ((1 / netsize) - freq[i])\n */\n\n var bestd = ~(1 << 31);\n var bestbiasd = bestd;\n var bestpos = -1;\n var bestbiaspos = bestpos;\n\n var i, n, dist, biasdist, betafreq;\n for (i = 0; i < netsize; i++) {\n n = network[i];\n\n dist = Math.abs(n[0] - b) + Math.abs(n[1] - g) + Math.abs(n[2] - r);\n if (dist < bestd) {\n bestd = dist;\n bestpos = i;\n }\n\n biasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift));\n if (biasdist < bestbiasd) {\n bestbiasd = biasdist;\n bestbiaspos = i;\n }\n\n betafreq = (freq[i] >> betashift);\n freq[i] -= betafreq;\n bias[i] += (betafreq << gammashift);\n }\n\n freq[bestpos] += beta;\n bias[bestpos] -= betagamma;\n\n return bestbiaspos;\n }\n\n /*\n Private Method: inxbuild\n\n sorts network and builds netindex[0..255]\n */\n function inxbuild() {\n var i, j, p, q, smallpos, smallval, previouscol = 0, startpos = 0;\n for (i = 0; i < netsize; i++) {\n p = network[i];\n smallpos = i;\n smallval = p[1]; // index on g\n // find smallest in i..netsize-1\n for (j = i + 1; j < netsize; j++) {\n q = network[j];\n if (q[1] < smallval) { // index on g\n smallpos = j;\n smallval = q[1]; // index on g\n }\n }\n q = network[smallpos];\n // swap p (i) and q (smallpos) entries\n if (i != smallpos) {\n j = q[0]; q[0] = p[0]; p[0] = j;\n j = q[1]; q[1] = p[1]; p[1] = j;\n j = q[2]; q[2] = p[2]; p[2] = j;\n j = q[3]; q[3] = p[3]; p[3] = j;\n }\n // smallval entry is now in position i\n\n if (smallval != previouscol) {\n netindex[previouscol] = (startpos + i) >> 1;\n for (j = previouscol + 1; j < smallval; j++)\n netindex[j] = i;\n previouscol = smallval;\n startpos = i;\n }\n }\n netindex[previouscol] = (startpos + maxnetpos) >> 1;\n for (j = previouscol + 1; j < 256; j++)\n netindex[j] = maxnetpos; // really 256\n }\n\n /*\n Private Method: inxsearch\n\n searches for BGR values 0..255 and returns a color index\n */\n function inxsearch(b, g, r) {\n var a, p, dist;\n\n var bestd = 1000; // biggest possible dist is 256*3\n var best = -1;\n\n var i = netindex[g]; // index on g\n var j = i - 1; // start at netindex[g] and work outwards\n\n while ((i < netsize) || (j >= 0)) {\n if (i < netsize) {\n p = network[i];\n dist = p[1] - g; // inx key\n if (dist >= bestd) i = netsize; // stop iter\n else {\n i++;\n if (dist < 0) dist = -dist;\n a = p[0] - b; if (a < 0) a = -a;\n dist += a;\n if (dist < bestd) {\n a = p[2] - r; if (a < 0) a = -a;\n dist += a;\n if (dist < bestd) {\n bestd = dist;\n best = p[3];\n }\n }\n }\n }\n if (j >= 0) {\n p = network[j];\n dist = g - p[1]; // inx key - reverse dif\n if (dist >= bestd) j = -1; // stop iter\n else {\n j--;\n if (dist < 0) dist = -dist;\n a = p[0] - b; if (a < 0) a = -a;\n dist += a;\n if (dist < bestd) {\n a = p[2] - r; if (a < 0) a = -a;\n dist += a;\n if (dist < bestd) {\n bestd = dist;\n best = p[3];\n }\n }\n }\n }\n }\n\n return best;\n }\n\n /*\n Private Method: learn\n\n \"Main Learning Loop\"\n */\n function learn() {\n var i;\n\n var lengthcount = pixels.length;\n var alphadec = 30 + ((samplefac - 1) / 3);\n var samplepixels = lengthcount / (3 * samplefac);\n var delta = ~~(samplepixels / ncycles);\n var alpha = initalpha;\n var radius = initradius;\n\n var rad = radius >> radiusbiasshift;\n\n if (rad <= 1) rad = 0;\n for (i = 0; i < rad; i++)\n radpower[i] = alpha * (((rad * rad - i * i) * radbias) / (rad * rad));\n\n var step;\n if (lengthcount < minpicturebytes) {\n samplefac = 1;\n step = 3;\n } else if ((lengthcount % prime1) !== 0) {\n step = 3 * prime1;\n } else if ((lengthcount % prime2) !== 0) {\n step = 3 * prime2;\n } else if ((lengthcount % prime3) !== 0) {\n step = 3 * prime3;\n } else {\n step = 3 * prime4;\n }\n\n var b, g, r, j;\n var pix = 0; // current pixel\n\n i = 0;\n while (i < samplepixels) {\n b = (pixels[pix] & 0xff) << netbiasshift;\n g = (pixels[pix + 1] & 0xff) << netbiasshift;\n r = (pixels[pix + 2] & 0xff) << netbiasshift;\n\n j = contest(b, g, r);\n\n altersingle(alpha, j, b, g, r);\n if (rad !== 0) alterneigh(rad, j, b, g, r); // alter neighbours\n\n pix += step;\n if (pix >= lengthcount) pix -= lengthcount;\n\n i++;\n\n if (delta === 0) delta = 1;\n if (i % delta === 0) {\n alpha -= alpha / alphadec;\n radius -= radius / radiusdec;\n rad = radius >> radiusbiasshift;\n\n if (rad <= 1) rad = 0;\n for (j = 0; j < rad; j++)\n radpower[j] = alpha * (((rad * rad - j * j) * radbias) / (rad * rad));\n }\n }\n }\n\n /*\n Method: buildColormap\n\n 1. initializes network\n 2. trains it\n 3. removes misconceptions\n 4. builds colorindex\n */\n function buildColormap() {\n init();\n learn();\n unbiasnet();\n inxbuild();\n }\n this.buildColormap = buildColormap;\n\n /*\n Method: getColormap\n\n builds colormap from the index\n\n returns array in the format:\n\n >\n > [r, g, b, r, g, b, r, g, b, ..]\n >\n */\n function getColormap() {\n var map = [];\n var index = [];\n\n for (var i = 0; i < netsize; i++)\n index[network[i][3]] = i;\n\n var k = 0;\n for (var l = 0; l < netsize; l++) {\n var j = index[l];\n map[k++] = (network[j][0]);\n map[k++] = (network[j][1]);\n map[k++] = (network[j][2]);\n }\n return map;\n }\n this.getColormap = getColormap;\n\n /*\n Method: lookupRGB\n\n looks for the closest *r*, *g*, *b* color in the map and\n returns its index\n */\n this.lookupRGB = inxsearch;\n}\n\nmodule.exports = NeuQuant;\n","GIFEncoder = require './GIFEncoder.js'\n\nrenderFrame = (frame) ->\n encoder = new GIFEncoder frame.width, frame.height\n\n if frame.index is 0\n encoder.writeHeader()\n else\n encoder.firstFrame = false\n\n encoder.setTransparent frame.transparent\n encoder.setRepeat frame.repeat\n encoder.setDelay frame.delay\n encoder.setQuality frame.quality\n encoder.setDither frame.dither\n encoder.setGlobalPalette frame.globalPalette\n encoder.addFrame frame.data\n encoder.finish() if frame.last\n if frame.globalPalette == true\n frame.globalPalette = encoder.getGlobalPalette()\n\n stream = encoder.stream()\n frame.data = stream.pages\n frame.cursor = stream.cursor\n frame.pageSize = stream.constructor.pageSize\n\n if frame.canTransfer\n transfer = (page.buffer for page in frame.data)\n self.postMessage frame, transfer\n else\n self.postMessage frame\n\nself.onmessage = (event) -> renderFrame event.data\n"]} \ No newline at end of file Index: openacs-4/packages/xowf/www/resources/proctoring/proctoring.js =================================================================== RCS file: /usr/local/cvsroot/openacs-4/packages/xowf/www/resources/proctoring/Attic/proctoring.js,v diff -u -N --- openacs-4/packages/xowf/www/resources/proctoring/proctoring.js 14 Jul 2020 20:16:18 -0000 1.1.2.1 +++ /dev/null 1 Jan 1970 00:00:00 -0000 @@ -1,754 +0,0 @@ -// A class to implement lightweight student "proctoring" on -// browser-based applications. -// -// It works by grabbing audio or video input devices in this way: -// 1. audio - when an audio device is grabbed, any noise detected for -// longer than a certain time time threshold will be made -// into an opus-encoded webm audio file and passed to -// configured callbacks -// 2. video - snapshots of configured video devices are captured from -// the browser at random intervals in one or more of -// configured image formats specified and passed to -// configured callbacks -// -// Video capture supports still frame images (as jpeg or png) and also -// animated gifs created by concatenating all frames collected so -// far. Every image is automatically watermarked with current -// timestamp and can be configured to be converted to grayscale -// (useful to generate smaller files at the expense of colors). -// -// Dependencies: gif.js (http://jnordberg.github.io/gif.js/) (only to -// generate animated gifs) -// -// Author: Antonio Pisano (antonio@elettrotecnica.it) -// -// Usage: to start a proctored session, create a new Proctoring -// instance by by passing a configuration object to it. -// -// ## General Configuration Object Attributes ## -// -// - minMsInterval: applies to video stream grabbing. Min -// time interval to pass between two consecutive -// snapshots in milliseconds -// - maxMsInterval: applies to video stream grabbing. Max -// time interval to pass between twp consecutive -// snapshots in milliseconds -// - minAudioDuration: when audio is recorded, any noisy interval -// longer than this number of seconds will be -// transformed in an audio file -// - maxAudioDuration: when audio is recorded, recordings longer than -// this number of seconds will be stopped -// automatically so that no recordings will be -// longer than this value -// - onMissingStreamHandler: this javascript handler will be triggered -// when one on more of the required streams -// becomes unavailable during the proctoring -// session (e.g. user disconnects the -// camera, or other error -// condition). Receives in input -// 'streamName', name of the failing stream -// and 'errMsg', returned error message. -// - onReadyHandler: this javascript handler is triggered as soon as -// the user has given access to all necessary input -// streams so that the proctored session can -// start. Does not receive any argument. -// - mediaConf: a JSON object that can have up to two attributes, -// 'camera', or 'desktop', to define the proctoring -// behavior and multimedia input configuration for the -// two kinds of devices. Each attribute's value is also a -// JSON object, see ("Media Configuration Attributes" section). -// -// ## Media Configuration Attributes ## -// -// Each attribute 'camera' or 'desktop' from mediaConf supports the -// following attributes: -// - required: this boolean flag decides if the stream is required and -// if proctoring should fail whenever this is not -// available. Defaults to false -// - grayscale: boolean flag deciding if the captured images from this -// stream should be converted to grayscale. Defaults to -// false. -// - width / height: forced width and height. Tells the proctoring -// object that images from this stream should be -// forcefully rescaled to this size regardless of -// the size they were captured. Needed to create -// lower resolution images from devices -// (e.g. webcams) that cannot produce images this -// small, as some Apple cameras. -// - imageHandlers: a JSON object defining the handlers to be -// triggered whenever a new image from this stream is -// available. It supports 3 possible attributes, each -// named after the corresponding image type, 'png', -// 'jpeg' and 'gif'. The presence of one of such -// attributes will enable the generation of an image -// in that type whenever a new snapshot is -// taken. Each attribue supports itself two possible -// attributes defining the handler type, 'blob', or -// 'base64'. The value of each of those is a -// javascript handler that expects to receive the -// blob or base64 value respectively of the generated -// image. -// - audioHandlers: a JSON object currently supporting just one 'auto' -// attribute. The value of this attribute is a -// javascript handler called whenever a new audio -// recording is available, receiving the blob file -// containing the audio recording. When this -// attribute is missing, audio will not be recorded. -// - constraints: a MediaTrackConstraints JSON object defining the -// real multimedia constraints for this device. See -// https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints -// -// Example conf: -// -// var conf = { -// minMsInterval: 5000, -// maxMsInterval: 10000, -// minAudioDuration: 1, -// maxAudioDuration: 60, -// onMissingStreamHandler : function(streamName, errMsg) { -// alert("'" + streamName + "' stream is missing. Please reload the page and enable all mandatory input sources."); -// }, -// onReadyHandler : function(streamName, errMsg) { -// console.log("All set!"); -// }, -// mediaConf: { -// camera: { -// required: true, -// grayscale: true, -// width: 320, -// width: 240, -// imageHandlers: { -// gif: { -// base64: function(base64data) { -// // this handler will be triggered -// // everytime a new gif for this stream is -// // rendered and will receive the base64 -// // data in input -// var input = document.querySelector('input[name="proctoring1"]'); -// input.value = base64data; -// } -// }, -// png { -// blob: function(blob) { -// pushImageToServer(blob); -// } -// } -// }, -// audioHandlers = { -// auto: function(blob) { -// // Do something with the audio blob -// } -// }, -// constraints: { -// video: { -// width: { max: 640 }, -// height: { max: 480 } -// } -// } -// }, -// desktop: { -// required: true, -// grayscale: false, -// imageHandlers: { -// gif: { -// base64: function(base64data) { -// // this handler will be triggered -// // everytime a new gif for this stream is -// // rendered and will receive the base64 -// // data in input -// var input = document.querySelector('input[name="proctoring1"]'); -// input.value = base64data; -// } -// }, -// png { -// base64: ...some handler -// blob:... -// }, -// jpeg { -// ... -// ... -// } -// }, -// constraints: { -// video: { -// width: { max: 640 }, -// height: { max: 480 } -// } -// } -// } -// } -// }; -// var proctoring = new Proctoring(conf); -// proctoring.start(); -// - -Date.prototype.toTZISOString = function() { - var tzo = -this.getTimezoneOffset(), - dif = tzo >= 0 ? '+' : '-', - pad = function(num) { - var norm = Math.floor(Math.abs(num)); - return (norm < 10 ? '0' : '') + norm; - }; - return this.getFullYear() + - '-' + pad(this.getMonth() + 1) + - '-' + pad(this.getDate()) + - 'T' + pad(this.getHours()) + - ':' + pad(this.getMinutes()) + - ':' + pad(this.getSeconds()) + - dif + pad(tzo / 60) + - ':' + pad(tzo % 60); -} - -// Implements a recorder automatically grabbing audio samples when -// noise is detected for longer than a specified interval -class AutoAudioRecorder { - constructor(stream, ondataavailable, minDuration=5, maxDuration=60, sampleInterval=50) { - var autorec = this; - this.stream = new MediaStream(); - var audioTracks = stream.getAudioTracks(); - if (audioTracks.length == 0) { - throw "No audio track available in supplied stream"; - } - - // Get only audio tracks from the main stream object - audioTracks.forEach(function(track) { - autorec.stream.addTrack(track); - }); - - this.ondataavailable = ondataavailable; - this.sampleInterval = sampleInterval; - this.minDuration = minDuration; - this.maxDuration = maxDuration; - this.stopHandle = null; - - // Prepare to sample stream properties - this.audioCtx = new (window.AudioContext || window.webkitAudioContext)(); - this.analyser = this.audioCtx.createAnalyser(); - this.source = this.audioCtx.createMediaStreamSource(this.stream); - this.source.connect(this.analyser); - this.analyser.fftSize = 2048; - this.bufferLength = this.analyser.frequencyBinCount; - this.dataArray = new Uint8Array(this.bufferLength); - - this.numPositiveSamples = 0; - this.noise = 0; - // Create an audio recorder - this.recorder = new MediaRecorder(this.stream, { - mimeType: 'audio/webm' - }); - - this.recorder.addEventListener("dataavailable", function(e) { - if (autorec.currentDuration() >= autorec.minDuration) { - autorec.ondataavailable(e.data); - } - autorec.numPositiveSamples = 0; - }); - } - - currentDuration() { - return (this.sampleInterval * this.numPositiveSamples) / 1000; - } - - someNoise() { - this.analyser.getByteTimeDomainData(this.dataArray); - var max = 0; - for(var i = 0; i < this.bufferLength; i++) { - var v = (this.dataArray[i] - 128.0) / 128.0; - if (v > max) { - max = v; - } - } - var decay = 500 / this.sampleInterval; - this.noise = (this.noise * (decay - 1) + max) / decay; - return max > 0.01; - } - - silence() { - // console.log(this.noise); - return this.noise <= 0.01 - } - - autoRecord() { - if (this.someNoise()) { - if (this.recorder.state != "recording") { - this.recorder.start(); - } - this.numPositiveSamples++; - } else if (this.recorder.state != "inactive" && - this.silence()) { - this.recorder.stop(); - } - if (this.recorder.state != "inactive" && - this.currentDuration() >= this.maxDuration) { - this.recorder.stop(); - } - } - - start() { - this.stop(); - this.stopHandle = setInterval(this.autoRecord.bind(this), this.sampleInterval); - } - - stop() { - if (this.stopHandle != null) { - clearInterval(this.stopHandle); - } - if (this.recorder.state != "inactive") { - this.recorder.stop(); - } - } -} - -class Proctoring { - - constructor(conf) { - this.minMsInterval = conf.minMsInterval; - this.maxMsInterval = conf.maxMsInterval; - this.minAudioDuration = conf.minAudioDuration; - this.maxAudioDuration = conf.maxAudioDuration; - this.mediaConf = conf.mediaConf; - - this.streamNames = Object.keys(this.mediaConf); - this.numStreams = this.streamNames.length; - this.numCheckedStreams = 0; - this.numActiveStreams = 0; - - this.onReadyHandler = conf.onReadyHandler; - this.ready = false; - this.onMissingStreamHandler = conf.onMissingStreamHandler; - this.isMissingStreams = false; - this.streamErrors = ["", ""]; - - this.gifs = [null, null]; - this.imageHandlers = [null, null]; - this.audioHandlers = [null, null]; - this.pictures = [[], []]; - this.prevPictures = [null, null]; - this.streams = [null, null]; - this.videos = [null, null]; - - for (var i = 0; i < this.numStreams; i++) { - var conf = this.mediaConf[this.streamNames[i]] - // streams are not required by default - if (conf.required == undefined) { - conf.required = false; - } - if (conf.imageHandlers != undefined) { - this.imageHandlers[i] = conf.imageHandlers; - } - if (conf.audioHandlers != undefined) { - this.audioHandlers[i] = conf.audioHandlers; - } - } - - this.acquireDevices(); - } - - acquireDevices() { - var proctor = this; - - // Cam stream - if (this.mediaConf.camera != undefined) { - if (!navigator.mediaDevices.getUserMedia && - !navigator.getUserMedia) { - var err = "getUserMedia not supported"; - proctor.streamErrors[proctor.streamNames.indexOf("camera")] = err; - console.log("Camera cannot be recorded: " + err); - proctor.numCheckedStreams++; - } else { - var camPromise = navigator.mediaDevices.getUserMedia ? - navigator.mediaDevices.getUserMedia(this.mediaConf.camera.constraints) : - navigator.getUserMedia(this.mediaConf.camera.constraints); - camPromise.then(stream => { - var i = this.streamNames.indexOf("camera"); - if (this.audioHandlers[i] != null) { - new AutoAudioRecorder(stream, - this.audioHandlers[i].auto, - this.minAudioDuration, - this.maxAudioDuration).start(); - } - this.streams[i] = stream; - this.videos[i] = this.createVideo(stream); - this.numActiveStreams++; - this.numCheckedStreams++; - }) - .catch(function (err) { - proctor.streamErrors[proctor.streamNames.indexOf("camera")] = err; - console.log("Camera cannot be recorded: " + err); - if (err.name == 'AbortError') { - proctor.numCheckedStreams = proctor.numStreams; - } else { - proctor.numCheckedStreams++; - } - }); - } - } - - // Desktop stream - if (this.mediaConf.desktop != undefined) { - if (!navigator.mediaDevices.getDisplayMedia && - !navigator.getDisplayMedia) { - var err = "getDisplayMedia not supported"; - proctor.streamErrors[proctor.streamNames.indexOf("desktop")] = err; - console.log("Desktop cannot be recorded: " + err); - proctor.numCheckedStreams++; - } else { - var desktopPromise = navigator.mediaDevices.getDisplayMedia ? - navigator.mediaDevices.getDisplayMedia(this.mediaConf.desktop.constraints) : - navigator.getDisplayMedia(this.mediaConf.desktop.constraints); - desktopPromise.then(stream => { - var requestedStream = this.mediaConf.desktop.constraints.video.displaySurface; - var selectedStream = stream.getVideoTracks()[0].getSettings().displaySurface; - // If displaySurface was specified, browser - // MUST support it and MUST be the right one. - if (requestedStream == undefined || - (selectedStream != undefined && - requestedStream == selectedStream)) { - var i = this.streamNames.indexOf("desktop"); - this.streams[i] = stream; - this.videos[i] = this.createVideo(stream); - this.numActiveStreams++; - } else { - throw "'" + requestedStream +"' was requested, but '" + selectedStream + "' was selected"; - } - proctor.numCheckedStreams++; - }) - .catch(function (err) { - proctor.streamErrors[proctor.streamNames.indexOf("desktop")] = err; - console.log("Desktop cannot be recorded: " + err); - if (err.name == 'AbortError') { - proctor.numCheckedStreams = proctor.numStreams; - } else { - proctor.numCheckedStreams++; - } - }); - } - } - } - - start() { - this.checkMissingStreams(); - this.takePictures(this.minMsInterval, this.maxMsInterval); - } - - reset() { - this.pictures = [[], []]; - } - - streamMuted(stream) { - var muted = false; - var audioTracks = stream.getAudioTracks(); - for (var i = 0; i < audioTracks.length; i++) { - var track = audioTracks[i]; - if (track.muted || - !track.enabled || - track.getSettings().volume == 0) { - muted = true; - break; - } - } - var videoTracks = stream.getVideoTracks(); - for (var i = 0; i < videoTracks.length; i++) { - var track = videoTracks[i]; - if (track.muted || - !track.enabled) { - muted = true; - break; - } - } - return muted; - } - - checkStream(stream, streamName) { - if (stream == null || - !stream.active || - this.streamMuted(stream)) { - if (this.mediaConf[streamName].required) { - return false; - } - } - return true; - } - - checkMissingStreams() { - if (!this.isMissingStreams && - this.numCheckedStreams == this.numStreams) { - for (var i = 0; i < this.streams.length; i++) { - var streamName = this.streamNames[i]; - if (!this.checkStream(this.streams[i], streamName)) { - this.isMissingStreams = true; - if (typeof this.onMissingStreamHandler == 'function') { - var err = this.streamErrors[i]; - this.onMissingStreamHandler(streamName, err); - } - } - } - } - - if (!this.isMissingStreams) { - setTimeout(this.checkMissingStreams.bind(this), 1000); - } - } - - renderGif(frames) { - if (frames.length == 0) { - return; - } - var i = this.pictures.indexOf(frames); - if (this.gifs[i] == null) { - this.gifs[i] = new GIF({ - workers: 2, - quality: 30, - workerScript: Proctoring.webWorkerURL, - width: frames[0].width, - height: frames[0].height - }); - var proctor = this; - var gifs = this.gifs; - gifs[i].on('finished', function(blob) { - var handlers = proctor.imageHandlers[i]; - if (typeof handlers.gif.blob == 'function') { - handlers.gif.blob(blob); - } - if (typeof handlers.gif.base64 == 'function') { - var reader = new FileReader(); - reader.readAsDataURL(blob); - reader.onloadend = function() { - var base64data = reader.result; - handlers.gif.base64(base64data); - } - } - // Stop the workers and kill the gif object - this.abort(); - this.freeWorkers.forEach(w => w.terminate()); - gifs[gifs.indexOf(this)] = null; - }); - } - var gif = this.gifs[i]; - if (!gif.running) { - for (var j = 0; j < frames.length; j++) { - gif.addFrame(frames[j], {delay: 500}); - } - gif.render(); - } - } - - createVideo(stream) { - var video = document.createElement("video"); - video.muted = true; - video.autoplay = "true"; - video.preload = "auto"; - video.srcObject = stream; - video.addEventListener("loadeddata", function(e) { - if (this.paused) { - this.play(); - } - }); - // Try to force that video is never put to sleep - video.addEventListener("pause", function(e) { - this.play(); - }); - - return video; - } - - watermark(canvas, text) { - var ctx = canvas.getContext("2d"); - var fontSize = 0.032*canvas.width; - ctx.font = "10px monospace" ; - ctx.fillStyle = "white"; - ctx.strokeStyle = "black"; - ctx.lineWidth = 0.5; - var metrics = ctx.measureText(text); - var x = canvas.width - metrics.width; - var y = canvas.height - fontSize; - ctx.fillText(text, x, y); - ctx.strokeText(text, x, y); - } - - canvasToGrayscale(canvas) { - var ctx = canvas.getContext("2d"); - var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); - var data = imageData.data; - for (var i = 0; i < data.length; i += 4) { - var avg = (data[i] + data[i + 1] + data[i + 2]) / 3; - data[i] = avg; // red - data[i + 1] = avg; // green - data[i + 2] = avg; // blue - } - ctx.putImageData(imageData, 0, 0); - } - - isCanvasMonochrome(canvas) { - var ctx = canvas.getContext("2d"); - var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); - var data = imageData.data; - var isMonochrome = true; - var firstPx = []; - for (var i = 0; i < data.length; i += 4) { - if (i == 0) { - firstPx[0] = data[i]; - firstPx[1] = data[i+1]; - firstPx[2] = data[i+2]; - } else if (firstPx[0] != data[i] || - firstPx[1] != data[i+1] || - firstPx[2] != data[i+2]) { - isMonochrome = false; - break; - } - } - - return isMonochrome; - } - - areCanvasEquals(canvas1, canvas2) { - var ctx1 = canvas1.getContext("2d"); - var imageData1 = ctx1.getImageData(0, 0, canvas1.width, canvas1.height); - var data1 = imageData1.data; - var ctx2 = canvas2.getContext("2d"); - var imageData2 = ctx2.getImageData(0, 0, canvas2.width, canvas2.height); - var data2 = imageData2.data; - var areEquals = true; - for (var i = 0; i < data1.length; i += 4) { - if (data1[i] != data2[i] || - data1[i+1] != data2[i+1] || - data1[i+2] != data2[i+2]) { - areEquals = false; - break; - } - } - - return areEquals; - } - - - takeShot(stream, grayscale) { - var i = this.streams.indexOf(stream); - var video = this.videos[i]; - - if (!video.paused) { - var streamName = this.streamNames[i]; - var conf = this.mediaConf[streamName]; - // var height = stream.getVideoTracks()[0].getSettings().height; - // var width = stream.getVideoTracks()[0].getSettings().width; - var iHeight = conf.height == undefined ? video.videoHeight : conf.height; - var iWidth = conf.width == undefined ? video.videoWidth : conf.width; - var proctor = this; - var pictures = this.pictures[i]; - var prevPicture = this.prevPictures[i]; - - var canvas = document.createElement("canvas"); - canvas.width = iWidth; - canvas.height = iHeight; - canvas.getContext("2d").drawImage(video, 0, 0, iWidth, iHeight); - - // In the future we might be stricter about black pictures... - // if (this.isCanvasMonochrome(canvas)) { - // var err = "canvas is monochrome"; - // this.onMissingStreamHandler(streamName, err); - // return; - // } - - // Check that camera does not keep sending the same - // picture over and over. - if (streamName == "camera" && - prevPicture != null && - this.areCanvasEquals(canvas, prevPicture)) { - var err = "camera is stuck"; - this.onMissingStreamHandler(streamName, err); - return; - } - this.prevPictures[i] = canvas; - - if (grayscale) { - this.canvasToGrayscale(canvas); - } - - this.watermark(canvas, (new Date()).toTZISOString()); - - var handlers = proctor.imageHandlers[i]; - if (handlers != null) { - if (handlers.png != undefined) { - canvas.toBlob(function(blob) { - if (typeof handlers.png.blob == 'function') { - handlers.png.blob(blob); - } - if (typeof handlers.png.base64 == 'function') { - var reader = new FileReader(); - reader.readAsDataURL(blob); - reader.onloadend = function() { - var base64data = reader.result; - handlers.png.base64(base64data); - } - } - }, "image/png"); - } - if (handlers.jpeg != undefined) { - canvas.toBlob(function(blob) { - if (typeof handlers.jpeg.blob == 'function') { - handlers.jpeg.blob(blob); - } - if (typeof handlers.jpeg.base64 == 'function') { - var reader = new FileReader(); - reader.readAsDataURL(blob); - reader.onloadend = function() { - var base64data = reader.result; - handlers.jpeg.base64(base64data); - } - } - }, "image/jpeg"); - } - if (handlers.gif != undefined) { - pictures.push(canvas); - proctor.renderGif(pictures); - } - } - } - } - - takePictures(minMsInterval, maxMsInterval) { - var interval; - if (!this.isMissingStreams && - this.numCheckedStreams == this.numStreams && - this.numActiveStreams > 0) { - // User already gave access to all requested streams and - // proctoring has successfully started - if (!this.ready) { - // If this is the first picture we take for this - // session, take not of this and trigger the onReady - // handler - if (typeof this.onReadyHandler == 'function') { - this.onReadyHandler(); - } - this.ready = true; - } - // For every configured stream, take a picture - for (var i = 0; i < this.streams.length; i++) { - if (this.streams[i] != null) { - this.takeShot(this.streams[i], this.mediaConf[this.streamNames[i]].grayscale); - } - } - // Set the time to the next snapshot to a random interval - interval = (Math.random() * (maxMsInterval - minMsInterval)) + minMsInterval; - } else { - // Not all streams are available and we cannot take - // snapshots (yet?). Set interval one second from now. - interval = 1000; - console.log("Waiting for streams: " + this.numCheckedStreams + "/" + this.numStreams + " ready."); - } - if (!this.isMissingStreams) { - // No errors, reschedule this function for the computed - // interval - setTimeout(this.takePictures.bind(this), interval, minMsInterval, maxMsInterval); - } else { - // Something went wrong and proctoring cannot proceed - console.log("Stopping..."); - } - } -} - -// We need this trick to get the folder of this very script and build -// from there the URL to the gif worker. -var scripts = document.querySelectorAll("script"); -var loc = scripts[scripts.length - 1].src; -Proctoring.webWorkerURL = loc.substring(0, loc.lastIndexOf('/')) + "/gif.worker.js";