/*
Checks fallbacks for video, audio and object elements
976095
protected void checkFallback(String elementType)
  {
    if (hasValidFallback)
    {
      hasValidFallback = false;
    }
    else
    {
      report.message(MessageId.MED_002,
          EPUBLocation.create(path, parser.getLineNumber(), parser.getColumnNumber()), elementType);
    }
  }
1202559
function() {
            this.supported = {};
            // Without support, no formats are supported
            if (!Crafty.support.audio) return;
            var audio = this.audioElement(),
                canplay;
            for (var i in this.codecs) {
                canplay = audio.canPlayType(this.codecs[i]);
                if (canplay !== "" && canplay !== "no") {
                    this.supported[i] = true;
                } else {
                    this.supported[i] = false;
                }
            }
        }
464031
function checkBadness() {
    var b, b1, bad, big, bw, count, h, x, y;
    bad = bw = count = 0;

    // Blocks of same colour.
    for (y = 0; y < width - 1; y++) {
      for (x = 0; x < width - 1; x++) {
            // All foreground colour.
        if ((frameBuffer[x + width * y] &&
             frameBuffer[(x + 1) + width * y] &&
             frameBuffer[x + width * (y + 1)] &&
             frameBuffer[(x + 1) + width * (y + 1)]) ||
            // All background colour.
            !(frameBuffer[x + width * y] ||
              frameBuffer[(x + 1) + width * y] ||
              frameBuffer[x + width * (y + 1)] ||
              frameBuffer[(x + 1) + width * (y + 1)])) {
          bad += N2;
        }
      }
    }

    // X runs.
    for (y = 0; y < width; y++) {
      badBuffer[0] = 0;

      for (h = b = x = 0; x < width; x++) {
        if ((b1 = frameBuffer[x + width * y]) === b) {
          badBuffer[h]++;
        } else {
          badBuffer[++h] = 1;
        }

        b   = b1;
        bw += b ? 1 : -1;
      }

      bad += getBadRuns(h);
    }

    if (bw < 0) bw = -bw;

    big   = bw;
    big  += big << 2;
    big <<= 1;

    while (big > width * width) {
      big -= width * width;
      count++;
    }

    bad += count * N4;

    // Y runs.
    for (x = 0; x < width; x++) {
      badBuffer[0] = 0;

      for (h = b = y = 0; y < width; y++) {
        if ((b1 = frameBuffer[x + width * y]) === b) {
          badBuffer[h]++;
        } else {
          badBuffer[++h] = 1;
        }

        b = b1;
      }

      bad += getBadRuns(h);
    }

    return bad;
  }
250379
function() {

			var enterArray = [];
			var exitArray = [];

			for (var i = 0; i < mediaListeners.length; i++) {
				var brkpt = mediaListeners[i]['breakpoint'];
				var entr = mediaListeners[i]['enter'] || undefined;
				var exit = mediaListeners[i]['exit'] || undefined;

				if (brkpt === '*') {
					if (entr !== undefined) {
						enterArray.push(entr);
					}
					if (exit !== undefined) {
						exitArray.push(exit);
					}
				} else if (testForCurr(brkpt)) {
					if (entr !== undefined && !mediaInit[i]) {
						enterArray.push(entr);
					}
					mediaInit[i] = true;
				} else {
					if (exit !== undefined && mediaInit[i]) {
						exitArray.push(exit);
					}
					mediaInit[i] = false;
				}
			}

			var eventObject = {
				entering : curr,
				exiting : prev
			};

			// loop through exit functions to call
			for (var j = 0; j < exitArray.length; j++) {
				exitArray[j].call(null, eventObject);
			}

			// then loop through enter functions to call
			for (var k = 0; k < enterArray.length; k++) {
				enterArray[k].call(null, eventObject);
			}
		}
606159
function MediaCaptureProxy() {

    var previewContainer,
        capturePreview = null,
        captureCancelButton = null,
        captureSettings = null,
        captureStarted = false,
        capturedPictureFile,
        capturedVideoFile,
        capture = null;

    var CaptureNS = Windows.Media.Capture;

    /**
     * Helper function that toggles visibility of DOM elements with provided ids
     * @param {String} variable number of elements' ids which visibility needs to be toggled 
     */
    function toggleElements() {
        // convert arguments to array
        var args = Array.prototype.slice.call(arguments);
        args.forEach(function(buttonId) {
            var buttonEl = document.getElementById(buttonId);
            if (buttonEl) {
                var curDisplayStyle = buttonEl.style.display;
                buttonEl.style.display = curDisplayStyle === 'none' ? 'block' : 'none';
            }
        });
    }

    /**
     * Creates basic camera UI with preview 'video' element and 'Cancel' button
     * Capture starts, when you clicking on preview.
     */
    function createCameraUI() {

        var buttonStyle = "margin: 7px; border: 2.5px solid white; width: 45%; height: 35px; color: white; background-color: black;";

        previewContainer = document.createElement('div');
        previewContainer.style.cssText = "background-position: 50% 50%; background-repeat: no-repeat; background-size: contain; background-color: black; left: 0px; top: 0px; width: 100%; height: 100%; position: fixed; z-index: 9999";
        previewContainer.innerHTML =
            '<video id="capturePreview" style="width: 100%; height: 100%"></video>' +
            '<div id="previewButtons" style="width: 100%; bottom: 0px; display: flex; position: absolute; justify-content: space-around; background-color: black;">' +
                '<button id="takePicture" style="' + buttonStyle + '">Capture</button>' +
                '<button id="cancelCapture" style="' + buttonStyle + '">Cancel</button>' +
                '<button id="selectPicture" style="display: none; ' + buttonStyle + '">Accept</button>' +
                '<button id="retakePicture" style="display: none; ' + buttonStyle + '">Retake</button>' +
            '</div>';

        document.body.appendChild(previewContainer);

        // Create fullscreen preview
        capturePreview = document.getElementById('capturePreview');

        // Create cancel button
        captureCancelButton = document.getElementById('cancelCapture');

        capture = new CaptureNS.MediaCapture();

        captureSettings = new CaptureNS.MediaCaptureInitializationSettings();
        captureSettings.streamingCaptureMode = CaptureNS.StreamingCaptureMode.audioAndVideo;
    }

    /**
     * Starts camera preview and binds provided callbacks to controls
     * @param  {function} takeCallback   Callback for Take button
     * @param  {function} errorCallback  Callback for Cancel button + default error callback
     * @param  {function} selectCallback Callback for Select button
     * @param  {function} retakeCallback Callback for Retake button
     */
    function startCameraPreview(takeCallback, errorCallback, selectCallback, retakeCallback) {
        // try to select appropriate device for capture
        // rear camera is preferred option
        var expectedPanel = Windows.Devices.Enumeration.Panel.back;
        Windows.Devices.Enumeration.DeviceInformation.findAllAsync(Windows.Devices.Enumeration.DeviceClass.videoCapture).done(function (devices) {
            if (devices.length > 0) {
                devices.forEach(function (currDev) {
                    if (currDev.enclosureLocation && currDev.enclosureLocation.panel && currDev.enclosureLocation.panel == expectedPanel) {
                        captureSettings.videoDeviceId = currDev.id;
                    }
                });

                capture.initializeAsync(captureSettings).done(function () {
                    // This is necessary since WP8.1 MediaCapture outputs video stream rotated 90 degrees CCW
                    // TODO: This can be not consistent across devices, need additional testing on various devices
                    // msdn.microsoft.com/en-us/library/windows/apps/hh452807.aspx
                    capture.setPreviewRotation(Windows.Media.Capture.VideoRotation.clockwise90Degrees);
                    capturePreview.msZoom = true;

                    capturePreview.src = URL.createObjectURL(capture);
                    capturePreview.play();

                    previewContainer.style.display = 'block';

                    // Bind events to controls
                    capturePreview.onclick = takeCallback;
                    document.getElementById('takePicture').onclick = takeCallback;
                    document.getElementById('cancelCapture').onclick = function () {
                        errorCallback(CaptureError.CAPTURE_NO_MEDIA_FILES);
                    };
                    document.getElementById('selectPicture').onclick = selectCallback;
                    document.getElementById('retakePicture').onclick = retakeCallback;
                }, function (err) {
                    destroyCameraPreview();
                    errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
                });
            } else {
                // no appropriate devices found
                destroyCameraPreview();
                errorCallback(CaptureError.CAPTURE_INTERNAL_ERR);
            }
        });
    }

    /**
     * Destroys camera preview, removes all elements created
     */
    function destroyCameraPreview() {
        capturePreview.pause();
        capturePreview.src = null;
        if (previewContainer) {
            document.body.removeChild(previewContainer);
        }
        if (capture) {
            capture.stopRecordAsync();
            capture = null;
        }
    }

    return {
        /**
         * Initiate video capture using MediaCapture class
         * @param  {function} successCallback Called, when user clicked on preview, with captured file object
         * @param  {function} errorCallback   Called on any error
         */
        captureVideo: function (successCallback, errorCallback) {
            try {
                createCameraUI();
                startCameraPreview(function () {
                    // This callback called twice: whem video capture started and when it ended
                    // so we need to check capture status
                    if (!captureStarted) {
                        // remove cancel button and rename 'Take' button to 'Stop'
                        toggleElements('cancelCapture');
                        document.getElementById('takePicture').text = 'Stop';

                        var encodingProperties = Windows.Media.MediaProperties.MediaEncodingProfile.createMp4(Windows.Media.MediaProperties.VideoEncodingQuality.auto),
                            generateUniqueCollisionOption = Windows.Storage.CreationCollisionOption.generateUniqueName,
                            localFolder = Windows.Storage.ApplicationData.current.localFolder;

                        localFolder.createFileAsync("cameraCaptureVideo.mp4", generateUniqueCollisionOption).done(function(capturedFile) {
                            capture.startRecordToStorageFileAsync(encodingProperties, capturedFile).done(function() {
                                capturedVideoFile = capturedFile;
                                captureStarted = true;
                            }, function(err) {
                                destroyCameraPreview();
                                errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
                            });
                        }, function(err) {
                            destroyCameraPreview();
                            errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
                        });
                    } else {
                        capture.stopRecordAsync().done(function () {
                            destroyCameraPreview();
                            successCallback(capturedVideoFile);
                        });
                    }
                }, errorCallback);
            } catch (ex) {
                destroyCameraPreview();
                errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, ex);
            }
        },

        /**
         * Initiate image capture using MediaCapture class
         * @param  {function} successCallback Called, when user clicked on preview, with captured file object
         * @param  {function} errorCallback   Called on any error
         */
        capturePhoto: function (successCallback, errorCallback) {
            try {
                createCameraUI();
                startCameraPreview(
                    // Callback for Take button - captures intermediate image file.
                    function () {
                        var encodingProperties = Windows.Media.MediaProperties.ImageEncodingProperties.createJpeg(),
                            overwriteCollisionOption = Windows.Storage.CreationCollisionOption.replaceExisting,
                            tempFolder = Windows.Storage.ApplicationData.current.temporaryFolder;

                        tempFolder.createFileAsync("cameraCaptureImage.jpg", overwriteCollisionOption).done(function (capturedFile) {
                            capture.capturePhotoToStorageFileAsync(encodingProperties, capturedFile).done(function () {
                                // store intermediate result in object's global variable
                                capturedPictureFile = capturedFile;
                                // show pre-captured image and toggle visibility of all buttons
                                previewContainer.style.backgroundImage = 'url("' + 'ms-appdata:///temp/' + capturedFile.name + '")';
                                toggleElements('capturePreview', 'takePicture', 'cancelCapture', 'selectPicture', 'retakePicture');
                            }, function (err) {
                                destroyCameraPreview();
                                errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
                            });
                        }, function (err) {
                            destroyCameraPreview();
                            errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, err);
                        });
                    },
                    // error + cancel callback
                    function (err) {
                        destroyCameraPreview();
                        errorCallback(err);
                    },
                    // Callback for Select button - copies intermediate file into persistent application's storage
                    function () {
                        var generateUniqueCollisionOption = Windows.Storage.CreationCollisionOption.generateUniqueName,
                            localFolder = Windows.Storage.ApplicationData.current.localFolder;

                        capturedPictureFile.copyAsync(localFolder, capturedPictureFile.name, generateUniqueCollisionOption).done(function (copiedFile) {
                            destroyCameraPreview();
                            successCallback(copiedFile);
                        }, function(err) {
                            destroyCameraPreview();
                            errorCallback(err);
                        });
                    },
                    // Callback for retake button - just toggles visibility of necessary elements
                    function () {
                        toggleElements('capturePreview', 'takePicture', 'cancelCapture', 'selectPicture', 'retakePicture');
                    }
                );
            } catch (ex) {
                destroyCameraPreview();
                errorCallback(CaptureError.CAPTURE_INTERNAL_ERR, ex);
            }
        }
    };
}
942968
function(media) {
      if (options.use_external) {
        media.forEach(function(item) {
          strMediaStyles += processMedia(item);
        });
      } else {
        media.forEach(function(item) {
          strStyles += processMedia(item);
        });
      }

    }
131364
function fallBack () {
      var programFilesVar = "ProgramFiles";
      if (arch === "(64)") {
        console.warn("You are using 32-bit version of Firefox on 64-bit versions of the Windows.\nSome features may not work correctly in this version. You should upgrade Firefox to the latest 64-bit version now!")
        programFilesVar = "ProgramFiles(x86)";
      }
      resolve(path.join(process.env[programFilesVar], appName, "firefox.exe"));
    }
81903
function () {

			var images = {};
			var blobs = {};

			if ( 'Video' in fbxTree.Objects ) {

				var videoNodes = fbxTree.Objects.Video;

				for ( var nodeID in videoNodes ) {

					var videoNode = videoNodes[ nodeID ];

					var id = parseInt( nodeID );

					images[ id ] = videoNode.RelativeFilename || videoNode.Filename;

					// raw image data is in videoNode.Content
					if ( 'Content' in videoNode ) {

						var arrayBufferContent = ( videoNode.Content instanceof ArrayBuffer ) && ( videoNode.Content.byteLength > 0 );
						var base64Content = ( typeof videoNode.Content === 'string' ) && ( videoNode.Content !== '' );

						if ( arrayBufferContent || base64Content ) {

							var image = this.parseImage( videoNodes[ nodeID ] );

							blobs[ videoNode.RelativeFilename || videoNode.Filename ] = image;

						}

					}

				}

			}

			for ( var id in images ) {

				var filename = images[ id ];

				if ( blobs[ filename ] !== undefined ) images[ id ] = blobs[ filename ];
				else images[ id ] = images[ id ].split( '\\' ).pop();

			}

			return images;

		}
1360454
function(f) {
		var isObj = typeof(f) == 'object' ? true : false,
			mime  = isObj ? f.mime : f,
			kind;
		

		if (isObj && f.alias && mime != 'symlink-broken') {
			kind = 'Alias';
		} else if (this.kinds[mime]) {
			if (isObj && mime === 'directory' && (! f.phash || f.isroot)) {
				kind = 'Root';
			} else {
				kind = this.kinds[mime];
			}
		}
		if (! kind) {
			if (mime.indexOf('text') === 0) {
				kind = 'Text';
			} else if (mime.indexOf('image') === 0) {
				kind = 'Image';
			} else if (mime.indexOf('audio') === 0) {
				kind = 'Audio';
			} else if (mime.indexOf('video') === 0) {
				kind = 'Video';
			} else if (mime.indexOf('application') === 0) {
				kind = 'App';
			} else {
				kind = mime;
			}
		}
		
		return this.messages['kind'+kind] ? this.i18n('kind'+kind) : mime;
	}
285952
def validate(self):
        
        from .files import VideoFile, WebVideoFile
        try:
            assert self.kind == content_kinds.VIDEO, "Assumption Failed: Node should be a video"
            assert self.questions == [], "Assumption Failed: Video should not have questions"
            assert len(self.files) > 0, "Assumption Failed: Video must have at least one video file"

            # Check if there are any .mp4 files if there are video files (other video types don't have paths)
            assert any(f for f in self.files if isinstance(f, VideoFile) or isinstance(f, WebVideoFile)), "Assumption Failed: Video should have at least one .mp4 file"

            return super(VideoNode, self).validate()
        except AssertionError as ae:
            raise InvalidNodeException("Invalid node ({}): {} - {}".format(ae.args[0], self.title, self.__dict__))
419359
function() {
		var self = this,
			url_vars;

		this.youtube_loaded = false;

		// Create Dom element
		this._el.content_item	= TL.Dom.create("div", "tl-media-item tl-media-youtube tl-media-shadow", this._el.content);
		this._el.content_item.id = TL.Util.unique_ID(7)

		// URL Vars
		url_vars = TL.Util.getUrlVars(this.data.url);

		// Get Media ID
		this.media_id = {};

		if (this.data.url.match('v=')) {
			this.media_id.id	= url_vars["v"];
		} else if (this.data.url.match('\/embed\/')) {
			this.media_id.id	= this.data.url.split("embed\/")[1].split(/[?&]/)[0];
		} else if (this.data.url.match(/v\/|v=|youtu\.be\//)){
			this.media_id.id	= this.data.url.split(/v\/|v=|youtu\.be\//)[1].split(/[?&]/)[0];
		} else {
			trace("YOUTUBE IN URL BUT NOT A VALID VIDEO");
		}

		// Get start second
		if (this.data.url.match("start=")) {
			this.media_id.start = parseInt(this.data.url.split("start=")[1], 10);
		}
		else if (this.data.url.match("t=")) {
			this.media_id.start = parseInt(this.data.url.split("t=")[1], 10);
		}

		//Get end second
		if (this.data.url.match("end=")) {
			this.media_id.end = parseInt(this.data.url.split("end=")[1], 10);
		}

		this.media_id.hd		= Boolean(typeof(url_vars["hd"]) != 'undefined');


		// API Call
		TL.Load.js('https://www.youtube.com/iframe_api', function() {
			self.createMedia();
		});

	}
240636
void checkLostBlocks(List<Block> blocksLostChecksum,
      List<Block> blocksLostStripe, Path p, Codec codec)
      throws IOException {
    StringBuilder message = new StringBuilder();
    if (blocksLostChecksum.size() > 0) {
      message.append("Lost " + blocksLostChecksum.size() +
          " checksums in blocks:");
      for (Block blk : blocksLostChecksum) {
        message.append(" ");
        message.append(blk.toString());
      }
    }
    if (blocksLostStripe.size() > 0) {
      message.append("Lost " + blocksLostStripe.size() +
          " stripes in blocks:");
      for (Block blk : blocksLostStripe) {
        message.append(" ");
        message.append(blk.toString());
      }
    }
    if (message.length() == 0)
      return;
    message.append(" in file " + p);
    throw new IOException(message.toString());
  }
88800
function onSuccess(stream) {
          videoStream = stream;

          if (window.hasModernUserMedia) {
            videoElem.srcObject = stream;
          } else if (navigator.mozGetUserMedia) {
            // Firefox supports a src object
            videoElem.mozSrcObject = stream;
          } else {
            var vendorURL = window.URL || window.webkitURL;
            videoElem.src = vendorURL.createObjectURL(stream);
          }

          /* Start playing the video to show the stream from the webcam */
          videoElem.play();
          $scope.config.video = videoElem;

          /* Call custom callback */
          if ($scope.onStream) {
            $scope.onStream({stream: stream});
          }
        }
1283780
function videoEnterFullscreen(element) {
		var videoElement = _getVideo(element);

		if (videoElement && videoElement.webkitEnterFullscreen) {
			try {
				if (videoElement.readyState < videoElement.HAVE_METADATA) {
					videoElement.addEventListener('loadedmetadata', function onMetadataLoaded() {
						videoElement.removeEventListener('loadedmetadata', onMetadataLoaded, false);
						videoElement.webkitEnterFullscreen();
						hasControls = !!videoElement.getAttribute('controls');
					}, false);
					videoElement.load();
				}
				else {
					videoElement.webkitEnterFullscreen();
					hasControls = !!videoElement.getAttribute('controls');
				}

				lastVideoElement = videoElement;
			}
			catch (err) {
				return callOnError('not_supported', element);
			}

			return true;
		}

		return callOnError(fn.request === undefined ? 'not_supported' : 'not_enabled', element);
	}
36036
function videoPlaybackNearlyFinished($event){
        $this->waitAnswer();
        $this->setExpectSpeech(false);
        $videoToken = isset($event[0]['token']) ? $event[0]['token'] : '';
        $videoTokenArr = $this->decodeToken($videoToken);

        if(isset($videoTokenArr['id']) && isset($videoTokenArr['index'])){
            $id = $videoTokenArr['id'];
            $id = intval($id) +1;
            $directives = $this->getVideoPlay(strval($id));
            return [
                'directives' => $directives
            ];
        }
    }
736643
protected void nativePlay(Element video) {
        MediaStream stream = null;
        if (Navigator.getUserMedia != null) {
            stream = Navigator.getUserMedia;
            GWT.log("Uses Default user Media");
        } else if (Navigator.webkitGetUserMedia != null) {
            stream = Navigator.webkitGetUserMedia;
            GWT.log("Uses Webkit User Media");
        } else if (Navigator.mozGetUserMedia != null) {
            stream = Navigator.mozGetUserMedia;
            GWT.log("Uses Moz User Media");
        } else if (Navigator.msGetUserMedia != null) {
            stream = Navigator.msGetUserMedia;
            GWT.log("Uses Microsoft user Media");
        } else {
            GWT.log("No supported media found in your browser");
        }

        if (stream != null) {
            Navigator.getMedia = stream;
            Constraints constraints = new Constraints();
            constraints.audio = false;

            MediaTrackConstraints mediaTrackConstraints = new MediaTrackConstraints();
            mediaTrackConstraints.width = width;
            mediaTrackConstraints.height = height;
            mediaTrackConstraints.facingMode = facingMode.getName();
            constraints.video = mediaTrackConstraints;

            Navigator.mediaDevices.getUserMedia(constraints).then(streamObj -> {
                mediaStream = (MediaStream) streamObj;
                if (URL.createObjectURL(mediaStream) != null) {
                    $(video).attr("src", URL.createObjectURL(mediaStream));
                } else if (WebkitURL.createObjectURL(mediaStream) != null) {
                    $(video).attr("src", WebkitURL.createObjectURL(mediaStream));
                }
                if (video instanceof VideoElement) {
                    ((VideoElement) video).play();
                }
                onCameraCaptureLoad();
                return null;
            }).catchException(error -> {
                GWT.log("MaterialCameraCapture: An error occured! " + error);
                onCameraCaptureError(error.toString());
                return null;
            });
        }
    }
834591
function stopAudioCapture() {

        // Disconnect media source node from script processor
        if (source)
            source.disconnect();

        // Disconnect associated script processor node
        if (processor)
            processor.disconnect();

        // Stop capture
        if (mediaStream) {
            var tracks = mediaStream.getTracks();
            for (var i = 0; i < tracks.length; i++)
                tracks[i].stop();
        }

        // Remove references to now-unneeded components
        processor = null;
        source = null;
        mediaStream = null;

        // End stream
        writer.sendEnd();

    }