Create a SimpleBlock keyframe header using these fields:
timecode    - Time of this keyframe
trackNumber - Track number from 1 to 126 (inclusive)
frame       - Raw frame data payload string

Returns an EBML element.
350211
function createKeyframeBlock(keyframe) {
                var
                    bufferStream = new ArrayBufferDataStream(1 + 2 + 1);
                
                if (!(keyframe.trackNumber > 0 && keyframe.trackNumber < 127)) {
                    throw "TrackNumber must be > 0 and < 127";
                }
    
                bufferStream.writeEBMLVarInt(keyframe.trackNumber); // Always 1 byte since we limit the range of trackNumber
                bufferStream.writeU16BE(keyframe.timecode);
                
                // Flags byte
                bufferStream.writeByte(
                    1 << 7 // Keyframe
                );
                
                return {
                    "id": 0xA3, // SimpleBlock
                    "data": [
                         bufferStream.getAsDataArray(),
                         keyframe.frame
                    ]
                };
            }
601169
def _standard_frame_length(header):
    
    frame_length = 4  # Sequence Number
    frame_length += header.algorithm.iv_len  # IV
    frame_length += header.frame_length  # Encrypted Content
    frame_length += header.algorithm.auth_len  # Authentication Tag
    return frame_length
192882
public AmqpFrame getFrame()
    {    
        int pos = this.position();       
        AmqpMethod method = new AmqpMethod();
        int classIndex;
        AmqpFrame frame = new AmqpFrame(); 
                 
        // If there is at least one Frame in the buffer, attempt to decode it.
        if (this.remaining() > 7)
        {            
            frame.setHeader(this.getFrameHeader());           
            frame.setChannelId((short) frame.getHeader().channel);           
            frame.setType((short) frame.getHeader().frameType);           
            // the buffer must have an additional byte for the Frame end marker 
            
            if (this.remaining() >= frame.getHeader().size + 1)
            {                
                switch (frame.getType())
                {                
                    case AmqpConstants.FRAME_BODY:                        
                        WrappedByteBuffer body = new AmqpBuffer();
                        // copy body into new Buffer
                        int end = this.position() + (int)frame.getHeader().size;
                        while (position() < end)
                        {
                            body.put(get());
                        }
                        frame.setBody(body);
                        frame.setMethodName("body");                        
                        break;

                    case AmqpConstants.FRAME_HEADER:                        
                        classIndex = this.getUnsignedShort();
                        @SuppressWarnings("unused")
                        short weight = (short)this.getUnsignedShort();
                        @SuppressWarnings("unused")
                        long bodySize = this.getUnsignedLong();                            
                        
                        frame.setContentProperties(this.getContentProperties());
                        frame.setMethodName("header");                        
                        break;

                    case AmqpConstants.FRAME_METHOD:
                         classIndex = this.getUnsignedShort();
                        int methodIndex = this.getUnsignedShort();
                        String indexes = String.valueOf(classIndex) + String.valueOf(methodIndex);                      
                        method = MethodLookup.LookupMethod(indexes);
                        
                        // pull parameter list off of method
                        List<Parameter> params = method.allParameters;

                        frame.setMethodName(method.name);
                        frame.setArgs(this.getMethodArguments(params));                        
                        break;

                    case AmqpConstants.FRAME_HEARTBEAT:
                    case AmqpConstants.FRAME_RABBITMQ_HEARTBEAT:
                    	throw new IllegalStateException("Received heartbeat frame even though the client has expressed no interest in heartbeat via tune-ok method.");

                    default:
                    	throw new IllegalStateException("Unrecognized AMQP 0-9-1 Frame type = " + frame.getType());
                }
                
                short frameEnd = (short) this.getUnsigned();                
                if (frameEnd != AmqpConstants.FRAME_END)
                {                    
                    throw new IllegalStateException("Invalid end of AMQP method frame");
                }
            }
            else
            {                
                this.position(pos);
                return null;
            }
            return frame;
        }
        return null;
    }
67215
def get_bar(self, code, time):
        
        try:
            return self.data.loc[(pd.Timestamp(time), code)]
        except:
            raise ValueError(
                'DATASTRUCT CURRENTLY CANNOT FIND THIS BAR WITH {} {}'.format(
                    code,
                    time
                )
            )
1320808
def stream_header(self, f):
        """"""
        stream_struct("L##L", f, self.version, self.previous_block_hash,
                      self.merkle_root, self.height)
        f.write(b'\0' * 28)
        stream_struct("LL#S", f, self.timestamp, self.difficulty, self.nonce, self.solution)
395066
private RTPFormat createVideoFormat(int payload, Text description) {
        Iterator<Text> it = description.split('/').iterator();

        //encoding name
        Text token = it.next();
        token.trim();
        EncodingName name = new EncodingName(token);

        //clock rate
        //TODO : convert to frame rate
        token = it.next();
        token.trim();
        int clockRate = token.toInteger();

        RTPFormat rtpFormat = getFormat(payload);
        if (rtpFormat == null) {
            formats.add(new RTPFormat(payload, FormatFactory.createVideoFormat(name, clockRate)));
        } else {
            //TODO: recreate format anyway. it is illegal to use clock rate as frame rate
            ((VideoFormat)rtpFormat.getFormat()).setName(name);
            ((VideoFormat)rtpFormat.getFormat()).setFrameRate(clockRate);
        }

        return rtpFormat;
    }
910768
def encode(self, frame: Frame) -> Frame:
        
        # Skip control frames.
        if frame.opcode in CTRL_OPCODES:
            return frame

        # Since we always encode and never fragment messages, there's no logic
        # similar to decode() here at this time.

        if frame.opcode != OP_CONT:
            # Re-initialize per-message decoder.
            if self.local_no_context_takeover:
                self.encoder = zlib.compressobj(
                    wbits=-self.local_max_window_bits, **self.compress_settings
                )

        # Compress data frames.
        data = self.encoder.compress(frame.data) + self.encoder.flush(zlib.Z_SYNC_FLUSH)
        if frame.fin and data.endswith(_EMPTY_UNCOMPRESSED_BLOCK):
            data = data[:-4]

        # Allow garbage collection of the encoder if it won't be reused.
        if frame.fin and self.local_no_context_takeover:
            del self.encoder

        return frame._replace(data=data, rsv1=True)
1050618
public String getStartTimecode()
	{
		final Element element = getElement("Time_code_of_first_frame", 0);

		if (element != null)
		{
			return element.getText();
		}
		else
		{
			return null;
		}
	}
1325193
function toWebM(frames, outputAsArray) {
    var info = checkFrames(frames);

    //max duration by cluster in milliseconds
    var CLUSTER_MAX_DURATION = 30000;

    var EBML = [{
        "id": 0x1a45dfa3, // EBML
        "data": [{
            "data": 1,
            "id": 0x4286 // EBMLVersion
          }, {
            "data": 1,
            "id": 0x42f7 // EBMLReadVersion
          }, {
            "data": 4,
            "id": 0x42f2 // EBMLMaxIDLength
          }, {
            "data": 8,
            "id": 0x42f3 // EBMLMaxSizeLength
          }, {
            "data": "webm",
            "id": 0x4282 // DocType
          }, {
            "data": 2,
            "id": 0x4287 // DocTypeVersion
          }, {
            "data": 2,
            "id": 0x4285 // DocTypeReadVersion
          }
        ]
      }, {
        "id": 0x18538067, // Segment
        "data": [{
            "id": 0x1549a966, // Info
            "data": [{
                "data": 1e6, //do things in millisecs (num of nanosecs for duration scale)
                "id": 0x2ad7b1 // TimecodeScale
              }, {
                "data": "whammy",
                "id": 0x4d80 // MuxingApp
              }, {
                "data": "whammy",
                "id": 0x5741 // WritingApp
              }, {
                "data": doubleToString(info.duration),
                "id": 0x4489 // Duration
              }
            ]
          }, {
            "id": 0x1654ae6b, // Tracks
            "data": [{
                "id": 0xae, // TrackEntry
                "data": [{
                    "data": 1,
                    "id": 0xd7 // TrackNumber
                  }, {
                    "data": 1,
                    "id": 0x63c5 // TrackUID
                  }, {
                    "data": 0,
                    "id": 0x9c // FlagLacing
                  }, {
                    "data": "und",
                    "id": 0x22b59c // Language
                  }, {
                    "data": "V_VP8",
                    "id": 0x86 // CodecID
                  }, {
                    "data": "VP8",
                    "id": 0x258688 // CodecName
                  }, {
                    "data": 1,
                    "id": 0x83 // TrackType
                  }, {
                    "id": 0xe0, // Video
                    "data": [{
                        "data": info.width,
                        "id": 0xb0 // PixelWidth
                      }, {
                        "data": info.height,
                        "id": 0xba // PixelHeight
                      }
                    ]
                  }
                ]
              }
            ]
          },

          //cluster insertion point
        ]
      }
    ];


    //Generate clusters (max duration)
    var frameNumber = 0;
    var clusterTimecode = 0;
    while (frameNumber < frames.length) {

      var clusterFrames = [];
      var clusterDuration = 0;
      do {
        clusterFrames.push(frames[frameNumber]);
        clusterDuration += frames[frameNumber].duration;
        frameNumber++;
      } while (frameNumber < frames.length && clusterDuration < CLUSTER_MAX_DURATION);

      var clusterCounter = 0;
      var cluster = {
        "id": 0x1f43b675, // Cluster
        "data": [{
            "data": clusterTimecode,
            "id": 0xe7 // Timecode
          }
        ].concat(clusterFrames.map(function (webp) {
          var block = makeSimpleBlock({
            discardable: 0,
            frame: webp.data.slice(4),
            invisible: 0,
            keyframe: 1,
            lacing: 0,
            trackNum: 1,
            timecode: Math.round(clusterCounter)
          });
          clusterCounter += webp.duration;
          return {
            data: block,
            id: 0xa3
          };
        }))
      }

      //Add cluster to segment
      EBML[1].data.push(cluster);
      clusterTimecode += clusterDuration;
    }

    return generateEBML(EBML, outputAsArray)
  }
1238901
@Override
    public KeyFrameMeta analyzeKeyFrames() {
        if (keyframeMeta != null) {
            return keyframeMeta;
        }
        try {
            lock.lockInterruptibly();
            // check for cached keyframe informations
            if (keyframeCache != null) {
                keyframeMeta = keyframeCache.loadKeyFrameMeta(file);
                if (keyframeMeta != null) {
                    // Keyframe data loaded, create other mappings
                    duration = keyframeMeta.duration;
                    posTimeMap = new HashMap<>();
                    for (int i = 0; i < keyframeMeta.positions.length; i++) {
                        posTimeMap.put(keyframeMeta.positions[i], (long) keyframeMeta.timestamps[i]);
                    }
                    return keyframeMeta;
                }
            }
            // create a holder for the metadata
            keyframeMeta = new KeyFrameMeta();
            // Lists of video positions and timestamps
            List<Long> positionList = new ArrayList<>();
            List<Integer> timestampList = new ArrayList<>();
            // Lists of audio positions and timestamps
            List<Long> audioPositionList = new ArrayList<>();
            List<Integer> audioTimestampList = new ArrayList<>();
            long origPos = getCurrentPosition();
            // point to the first tag
            setCurrentPosition(9);
            // number of tags read
            int totalValidTags = 0;
            // start off as audio only
            boolean audioOnly = true;
            while (hasMoreTags()) {
                long pos = getCurrentPosition();
                // read tag header and duration
                ITag tmpTag = null;
                try {
                    tmpTag = readTagHeader();
                } catch (UnsupportedDataTypeException e) {
                    log.warn("analyzeKeyFrames", e);
                }
                if (tmpTag != null) {
                    totalValidTags++;
                } else {
                    break;
                }
                duration = tmpTag.getTimestamp();
                if (tmpTag.getDataType() == IoConstants.TYPE_VIDEO) {
                    if (audioOnly) {
                        audioOnly = false;
                        audioPositionList.clear();
                        audioTimestampList.clear();
                    }
                    if (firstVideoTag == -1) {
                        firstVideoTag = pos;
                    }
                    // Grab Frame type
                    fillBuffer(1);
                    int frametype = in.get();
                    if (keyframeMeta.videoCodecId == -1) {
                        keyframeMeta.videoCodecId = frametype & MASK_VIDEO_CODEC;
                    }
                    if (((frametype & MASK_VIDEO_FRAMETYPE) >> 4) == FLAG_FRAMETYPE_KEYFRAME) {
                        positionList.add(pos);
                        timestampList.add(tmpTag.getTimestamp());
                    }
                } else if (tmpTag.getDataType() == IoConstants.TYPE_AUDIO) {
                    if (firstAudioTag == -1) {
                        firstAudioTag = pos;
                    }
                    // Grab Frame type
                    fillBuffer(1);
                    int frametype = in.get() & 0xff;
                    if (keyframeMeta.audioCodecId == -1) {
                        keyframeMeta.audioCodecId = (frametype & MASK_SOUND_FORMAT) >> 4;
                    }
                    if (audioOnly) {
                        audioPositionList.add(pos);
                        audioTimestampList.add(tmpTag.getTimestamp());
                    }
                }
                // XXX Paul: this 'properly' handles damaged FLV files - as far as duration/size is concerned
                long newPosition = pos + tmpTag.getBodySize() + 15;
                // log.debug("---->" + in.remaining() + " limit=" + in.limit() + "
                // new pos=" + newPosition);
                if (newPosition >= getTotalBytes()) {
                    log.error("New position exceeds limit");
                    if (log.isDebugEnabled()) {
                        log.debug("-----\nKeyframe analysis\n\tdata type={} bodysize={}\n\tremaining={} limit={}\n\tnew pos={} pos={}\n-----", 
                                new Object[] { tmpTag.getDataType(), tmpTag.getBodySize(), getRemainingBytes(), getTotalBytes(), newPosition, pos });
                    }
                    //XXX Paul: A runtime exception is probably not needed here
                    log.info("New position {} exceeds limit {}", newPosition, getTotalBytes());
                    //just break from the loop
                    break;
                } else {
                    setCurrentPosition(newPosition);
                }
            }
            // restore the pos
            setCurrentPosition(origPos);
            log.debug("Total valid tags found: {}", totalValidTags);
            keyframeMeta.duration = duration;
            posTimeMap = new HashMap<Long, Long>();
            if (audioOnly) {
                // The flv only contains audio tags, use their lists
                // to support pause and seeking
                positionList = audioPositionList;
                timestampList = audioTimestampList;
            }
            keyframeMeta.audioOnly = audioOnly;
            keyframeMeta.positions = new long[positionList.size()];
            keyframeMeta.timestamps = new int[timestampList.size()];
            for (int i = 0; i < keyframeMeta.positions.length; i++) {
                keyframeMeta.positions[i] = positionList.get(i);
                keyframeMeta.timestamps[i] = timestampList.get(i);
                posTimeMap.put((long) positionList.get(i), (long) timestampList.get(i));
            }
            if (keyframeCache != null) {
                keyframeCache.saveKeyFrameMeta(file, keyframeMeta);
            }
        } catch (InterruptedException e) {
            log.warn("Exception acquiring lock", e);
        } finally {
            if (lock.isLocked()) {
                lock.unlock();
            }
        }
        return keyframeMeta;
    }
159777
def write(self, handle):
        '''
        '''
        if not self._frames:
            return

        def add(name, desc, bpe, format, bytes, *dimensions):
            group.add_param(name,
                            desc=desc,
                            bytes_per_element=bpe,
                            bytes=struct.pack(format, bytes),
                            dimensions=list(dimensions))

        def add_str(name, desc, bytes, *dimensions):
            group.add_param(name,
                            desc=desc,
                            bytes_per_element=-1,
                            bytes=bytes.encode('utf-8'),
                            dimensions=list(dimensions))

        def add_empty_array(name, desc, bpe):
            group.add_param(name, desc=desc, bytes_per_element=bpe, dimensions=[0])

        points, analog = self._frames[0]
        ppf = len(points)

        # POINT group
        group = self.add_group(1, 'POINT', 'POINT group')
        add('USED', 'Number of 3d markers', 2, '<H', ppf)
        add('FRAMES', 'frame count', 2, '<H', min(65535, len(self._frames)))
        add('DATA_START', 'data block number', 2, '<H', 0)
        add('SCALE', '3d scale factor', 4, '<f', self._point_scale)
        add('RATE', '3d data capture rate', 4, '<f', self._point_rate)
        add_str('X_SCREEN', 'X_SCREEN parameter', '+X', 2)
        add_str('Y_SCREEN', 'Y_SCREEN parameter', '+Y', 2)
        add_str('UNITS', '3d data units', self._point_units, len(self._point_units))
        add_str('LABELS', 'labels', ''.join('M%03d ' % i for i in range(ppf)), 5, ppf)
        add_str('DESCRIPTIONS', 'descriptions', ' ' * 16 * ppf, 16, ppf)

        # ANALOG group
        group = self.add_group(2, 'ANALOG', 'ANALOG group')
        add('USED', 'analog channel count', 2, '<H', analog.shape[0])
        add('RATE', 'analog samples per 3d frame', 4, '<f', analog.shape[1])
        add('GEN_SCALE', 'analog general scale factor', 4, '<f', self._gen_scale)
        add_empty_array('SCALE', 'analog channel scale factors', 4)
        add_empty_array('OFFSET', 'analog channel offsets', 2)

        # TRIAL group
        group = self.add_group(3, 'TRIAL', 'TRIAL group')
        add('ACTUAL_START_FIELD', 'actual start frame', 2, '<I', 1, 2)
        add('ACTUAL_END_FIELD', 'actual end frame', 2, '<I', len(self._frames), 2)

        # sync parameter information to header.
        blocks = self.parameter_blocks()
        self.get('POINT:DATA_START').bytes = struct.pack('<H', 2 + blocks)

        self.header.data_block = 2 + blocks
        self.header.frame_rate = self._point_rate
        self.header.last_frame = min(len(self._frames), 65535)
        self.header.point_count = ppf
        self.header.analog_count = np.prod(analog.shape)
        self.header.analog_per_frame = analog.shape[0]
        self.header.scale_factor = self._point_scale

        self._write_metadata(handle)
        self._write_frames(handle)
37479
public Timecode build()
	{
		// If drop-frame is not specified (and timebase is drop frame capable) default to true
		final boolean dropFrame = (this.dropFrame != null) ? this.dropFrame.booleanValue() : getRate().canBeDropFrame();

		return new Timecode(negative, days, hours, minutes, seconds, frames, rate, dropFrame);
	}
1359397
def create_frames(self, channel_id, buf, frame_max):
        '''
        
        '''
        size = frame_max - 8   # 8 bytes overhead for frame header and footer
        offset = 0
        while True:
            payload = buf[offset:(offset + size)]
            if len(payload) == 0:
                break
            offset += size

            yield ContentFrame(channel_id, payload)
            if offset >= len(buf):
                break
1027997
def _create_pax_generic_header(cls, pax_headers, type=tarfile.XHDTYPE):
    
    records = []
    for keyword, value in pax_headers.iteritems():

        try:
            keyword = keyword.encode("utf8")
        except Exception:
            pass

        try:
            value = value.encode("utf8")
        except Exception:
            pass

        l = len(keyword) + len(value) + 3   # ' ' + '=' + '\n'
        n = p = 0
        while True:
            n = l + len(str(p))
            if n == p:
                break
            p = n
        records.append("%d %s=%s\n" % (p, keyword, value))
    records = "".join(records)

    # We use a hardcoded "././@PaxHeader" name like star does
    # instead of the one that POSIX recommends.
    info = {}
    info["name"] = "././@PaxHeader"
    info["type"] = type
    info["size"] = len(records)
    info["magic"] = tarfile.POSIX_MAGIC

    # Create pax header + record blocks.
    return cls._create_header(info, tarfile.USTAR_FORMAT) + \
        cls._create_payload(records)
773362
public Frame process(Frame frame) {
    	sourceLen=frame.getLength();
    	destinationLen=sourceLen * 2;
        Frame res = Memory.allocate(destinationLen);
        
        byte[] data=frame.getData();
        byte[] resData=res.getData();
        
        for (i = 0,j = 0; i < sourceLen; i++) 
        {
        	currentIndex = data[i] & 0xff;
            resData[j++] = aLawDecompressTable_low[currentIndex];
            resData[j++] = aLawDecompressTable_high[currentIndex];
        }
        
        res.setOffset(0);
        res.setLength(destinationLen);
        res.setTimestamp(frame.getTimestamp());
        res.setDuration(frame.getDuration());
        res.setSequenceNumber(frame.getSequenceNumber());
        res.setEOM(frame.isEOM());
        res.setFormat(linear);
        res.setHeader(frame.getHeader());
        return res;
    }
1299208
def time_to_first_byte(self):
        
        # The unknown page is just a placeholder for entries with no page ID.
        # As such, it would not have a TTFB
        if self.page_id == 'unknown':
            return None
        ttfb = 0
        for entry in self.entries:
            if entry['response']['status'] == 200:
                for k, v in iteritems(entry['timings']):
                    if k != 'receive':
                        if v > 0:
                            ttfb += v
                break
            else:
                ttfb += entry['time']

        return ttfb
41097
def _create_pax_generic_header(cls, pax_headers, type, encoding):
        
        # Check if one of the fields contains surrogate characters and thereby
        # forces hdrcharset=BINARY, see _proc_pax() for more information.
        binary = False
        for keyword, value in pax_headers.items():
            try:
                value.encode("utf8", "strict")
            except UnicodeEncodeError:
                binary = True
                break

        records = b""
        if binary:
            # Put the hdrcharset field at the beginning of the header.
            records += b"21 hdrcharset=BINARY\n"

        for keyword, value in pax_headers.items():
            keyword = keyword.encode("utf8")
            if binary:
                # Try to restore the original byte representation of `value'.
                # Needless to say, that the encoding must match the string.
                value = value.encode(encoding, "surrogateescape")
            else:
                value = value.encode("utf8")

            l = len(keyword) + len(value) + 3   # ' ' + '=' + '\n'
            n = p = 0
            while True:
                n = l + len(str(p))
                if n == p:
                    break
                p = n
            records += bytes(str(p), "ascii") + b" " + keyword + b"=" + value + b"\n"

        # We use a hardcoded "././@PaxHeader" name like star does
        # instead of the one that POSIX recommends.
        info = {}
        info["name"] = "././@PaxHeader"
        info["type"] = type
        info["size"] = len(records)
        info["magic"] = POSIX_MAGIC

        # Create pax header + record blocks.
        return cls._create_header(info, USTAR_FORMAT, "ascii", "replace") + \
                cls._create_payload(records)