Gets the number of frames in an Opus packet
977487
def packet_get_nb_frames(data, length=None):
    """"""

    data_pointer = ctypes.c_char_p(data)
    if length is None:
        length = len(data)

    result = _packet_get_nb_frames(data_pointer, ctypes.c_int(length))
    if result < 0:
        raise OpusError(result)

    return result
1253807
def get_frame(self, in_data, frame_count, time_info, status):
		
		while self.keep_listening:
			try:
				frame = self.queue.get(False, timeout=queue_timeout)
				return (frame, pyaudio.paContinue)
			except Empty:
				pass
		return (None, pyaudio.paComplete)
920370
def current_frame(self):
		
		if not self.__fps:
			raise RuntimeError("fps not set so current frame number cannot be"
				" calculated")
		else:
			return int(self.__fps * self.time)
724481
def slim_frame_data(frames, frame_allowance=25):
    
    frames_len = 0
    app_frames = []
    system_frames = []
    for frame in frames:
        frames_len += 1
        if frame.get('in_app'):
            app_frames.append(frame)
        else:
            system_frames.append(frame)

    if frames_len <= frame_allowance:
        return frames

    remaining = frames_len - frame_allowance
    app_count = len(app_frames)
    system_allowance = max(frame_allowance - app_count, 0)
    if system_allowance:
        half_max = int(system_allowance / 2)
        # prioritize trimming system frames
        for frame in system_frames[half_max:-half_max]:
            frame.pop('vars', None)
            frame.pop('pre_context', None)
            frame.pop('post_context', None)
            remaining -= 1

    else:
        for frame in system_frames:
            frame.pop('vars', None)
            frame.pop('pre_context', None)
            frame.pop('post_context', None)
            remaining -= 1

    if remaining:
        app_allowance = app_count - remaining
        half_max = int(app_allowance / 2)

        for frame in app_frames[half_max:-half_max]:
            frame.pop('vars', None)
            frame.pop('pre_context', None)
            frame.pop('post_context', None)

    return frames
750789
def _read_midi_length(fileobj):
    """"""

    TEMPO, MIDI = range(2)

    def read_chunk(fileobj):
        info = fileobj.read(8)
        if len(info) != 8:
            raise SMFError("truncated")
        chunklen = struct.unpack(">I", info[4:])[0]
        data = fileobj.read(chunklen)
        if len(data) != chunklen:
            raise SMFError("truncated")
        return info[:4], data

    identifier, chunk = read_chunk(fileobj)
    if identifier != b"MThd":
        raise SMFError("Not a MIDI file")

    if len(chunk) != 6:
        raise SMFError("truncated")

    format_, ntracks, tickdiv = struct.unpack(">HHH", chunk)
    if format_ > 1:
        raise SMFError("Not supported format %d" % format_)

    if tickdiv >> 15:
        # fps = (-(tickdiv >> 8)) & 0xFF
        # subres = tickdiv & 0xFF
        # never saw one of those
        raise SMFError("Not supported timing interval")

    # get a list of events and tempo changes for each track
    tracks = []
    first_tempos = None
    for tracknum in xrange(ntracks):
        identifier, chunk = read_chunk(fileobj)
        if identifier != b"MTrk":
            continue
        events, tempos = _read_track(chunk)

        # In case of format == 1, copy the first tempo list to all tracks
        first_tempos = first_tempos or tempos
        if format_ == 1:
            tempos = list(first_tempos)
        events += tempos
        events.sort()
        tracks.append(events)

    # calculate the duration of each track
    durations = []
    for events in tracks:
        tempo = 500000
        parts = []
        deltasum = 0
        for (dummy, type_, data) in events:
            if type_ == TEMPO:
                parts.append((deltasum, tempo))
                tempo = data
                deltasum = 0
            else:
                deltasum += data
        parts.append((deltasum, tempo))

        duration = 0
        for (deltasum, tempo) in parts:
            quarter, tpq = deltasum / float(tickdiv), tempo
            duration += (quarter * tpq)
        duration /= 10 ** 6

        durations.append(duration)

    # return the longest one
    return max(durations)
802123
public int calculate_framesize()
	{

	 if (h_layer == 1)
	 {
	   framesize = (12 * bitrates[h_version][0][h_bitrate_index]) /
	               frequencies[h_version][h_sample_frequency];
	   if (h_padding_bit != 0 ) framesize++;
	   framesize <<= 2;		// one slot is 4 bytes long
	   nSlots = 0;
	 }
	 else
	 {
	   framesize = (144 * bitrates[h_version][h_layer - 1][h_bitrate_index]) /
	               frequencies[h_version][h_sample_frequency];
	   if (h_version == MPEG2_LSF || h_version == MPEG25_LSF) framesize >>= 1;	// SZD
	   if (h_padding_bit != 0) framesize++;
	   // Layer III slots
	   if (h_layer == 3)
	   {
	     if (h_version == MPEG1)
	     {
	  		 nSlots = framesize - ((h_mode == SINGLE_CHANNEL) ? 17 : 32) // side info size
	  								  -  ((h_protection_bit!=0) ? 0 : 2) 		       // CRC size
	  								  - 4; 								             // header size
	     }
	     else
		 {  // MPEG-2 LSF, SZD: MPEG-2.5 LSF
	        nSlots = framesize - ((h_mode == SINGLE_CHANNEL) ?  9 : 17) // side info size
	  					   		  -  ((h_protection_bit!=0) ? 0 : 2) 		       // CRC size
	  								  - 4; 								             // header size
	     }
	   }
	   else
	   {
	  	 nSlots = 0;
	   }
	 }
	 framesize -= 4;             // subtract header size
	 return framesize;
	}
306334
def getVideoStreamTextureSize(self, nDeviceIndex, eFrameType):
        """"""

        fn = self.function_table.getVideoStreamTextureSize
        pTextureBounds = VRTextureBounds_t()
        pnWidth = c_uint32()
        pnHeight = c_uint32()
        result = fn(nDeviceIndex, eFrameType, byref(pTextureBounds), byref(pnWidth), byref(pnHeight))
        return result, pTextureBounds, pnWidth.value, pnHeight.value
668019
def samplerate(self):
        """"""
        if hasattr(self.mgfile.info, 'sample_rate'):
            return self.mgfile.info.sample_rate
        elif self.type == 'opus':
            # Opus is always 48kHz internally.
            return 48000
        return 0
289699
def print_packet_count():
    """"""
    for name in archive.list_packet_names():
        packet_count = 0
        for group in archive.list_packet_histogram(name):
            for rec in group.records:
                packet_count += rec.count
        print('  {: <40} {: >20}'.format(name, packet_count))
368125
def get_parameters(self, packet_count=None):
        
        params = super(PipeCapture, self).get_parameters(packet_count=packet_count)
        params += ['-r', '-']
        return params
937922
def get_frameshift_lengths(num_bins):
    
    fs_len = []
    i = 1
    tmp_bins = 0
    while(tmp_bins<num_bins):
        if i%3:
            fs_len.append(i)
            tmp_bins += 1
        i += 1
    return fs_len
1056622
def count(procfile):
        
        """

        state_tcp = {
            '01': 'ESTABLISHED',
            '02': 'SYN_SENT',
            '03': 'SYN_RECV',
            '04': 'FIN_WAIT1',
            '05': 'FIN_WAIT2',
            '06': 'TIME_WAIT',
            '07': 'CLOSE',
            '08': 'CLOSE_WAIT',
            '09': 'LAST_ACK',
            '0A': 'LISTEN',
            '0B': 'CLOSING',
        }

        protocol = os.path.basename(procfile.name)

        state = []
        stats = {}

        # read procfile. e.g: /proc/net/tcp -> ['0A', '0A', '06', '01', '0A']
        for line in procfile.readlines():
            state.append(line.split()[3])

        for state_type, state_name in state_tcp.items():
            key = 'linux.net.{proto}[{state}]'.format(proto=protocol,
                                                      state=state_name
                                                      )
            value = state.count(state_type)
            stats[key] = value

        procfile.close()
        return stats
977512
def stft(self, samples: np.ndarray):
        
        window = self.window_function(self.window_size)
        hop_size = self.hop_size

        if len(samples) < self.window_size:
            samples = np.append(samples, np.zeros(self.window_size - len(samples)))

        num_frames = max(1, (len(samples) - self.window_size) // hop_size + 1)

        # Get frames as numpy view with stride_tricks to save RAM
        # Same as: frames = [padded_samples[i*hop_size:i*hop_size+self.window_size] for i in range(num_frames)]
        shape = (num_frames, self.window_size)
        strides = (hop_size * samples.strides[-1], samples.strides[-1])
        frames = np.lib.stride_tricks.as_strided(samples, shape=shape, strides=strides)

        result = np.fft.fft(frames * window, self.window_size) / np.atleast_1d(self.window_size)
        return result
117690
def get_frame(self, outdata, frames, timedata, status):
		

		if not self.keep_listening:
			raise sd.CallbackStop
		
		try:
			chunk = self.queue.get_nowait()
			# Check if the chunk contains the expected number of frames
			# The callback function raises a ValueError otherwise.
			if chunk.shape[0] == frames:
				outdata[:] = chunk
			else:
				outdata.fill(0)
		except Empty:
			outdata.fill(0)
156315
def play_internal
      count = 0
      @playing = true

      # Default play length (ms), will be adjusted later
      @length = IDEAL_LENGTH

      self.speaking = true
      loop do
        # Starting from the tenth packet, perform length adjustment every 100 packets (2 seconds)
        should_adjust_this_packet = (count % @adjust_interval == @adjust_offset)

        # If we should adjust, start now
        @length_adjust = Time.now.nsec if should_adjust_this_packet

        break unless @playing

        # If we should skip, get some data, discard it and go to the next iteration
        if @skips.positive?
          @skips -= 1
          yield
          next
        end

        # Track packet count, sequence and time (Discord requires this)
        count += 1
        increment_packet_headers

        # Get packet data
        buf = yield

        # Stop doing anything if the stop signal was sent
        break if buf == :stop

        # Proceed to the next packet if we got nil
        next unless buf

        # Track intermediate adjustment so we can measure how much encoding contributes to the total time
        @intermediate_adjust = Time.now.nsec if should_adjust_this_packet

        # Send the packet
        @udp.send_audio(buf, @sequence, @time)

        # Set the stream time (for tracking how long we've been playing)
        @stream_time = count * @length / 1000

        if @length_override # Don't do adjustment because the user has manually specified an override value
          @length = @length_override
        elsif @length_adjust # Perform length adjustment
          # Define the time once so it doesn't get inaccurate
          now = Time.now.nsec

          # Difference between length_adjust and now in ms
          ms_diff = (now - @length_adjust) / 1_000_000.0
          if ms_diff >= 0
            @length = if @adjust_average
                        (IDEAL_LENGTH - ms_diff + @length) / 2.0
                      else
                        IDEAL_LENGTH - ms_diff
                      end

            # Track the time it took to encode
            encode_ms = (@intermediate_adjust - @length_adjust) / 1_000_000.0
            @bot.debug("Length adjustment: new length #{@length} (measured #{ms_diff}, #{(100 * encode_ms) / ms_diff}% encoding)") if @adjust_debug
          end
          @length_adjust = nil
        end

        # If paused, wait
        sleep 0.1 while @paused

        if @length.positive?
          # Wait `length` ms, then send the next packet
          sleep @length / 1000.0
        else
          Discordrb::LOGGER.warn('Audio encoding and sending together took longer than Discord expects one packet to be (20 ms)! This may be indicative of network problems.')
        end
      end

      @bot.debug('Sending five silent frames to clear out buffers')

      5.times do
        increment_packet_headers
        @udp.send_audio(Encoder::OPUS_SILENCE, @sequence, @time)

        # Length adjustments don't matter here, we can just wait 20 ms since nobody is going to hear it anyway
        sleep IDEAL_LENGTH / 1000.0
      end

      @bot.debug('Performing final cleanup after stream ended')

      # Final cleanup
      stop_playing

      # Notify any stop_playing methods running right now that we have actually stopped
      @has_stopped_playing = true
    end
544638
function (result) {
            if (result.stat('googFrameRateSent')) {
              currentStats.videoSentBytes = Number(result.stat('bytesSent'));
              currentStats.videoSentPackets = Number(result.stat('packetsSent'));
              currentStats.videoSentPacketsLost = Number(result.stat('packetsLost'));
              currentStats.videoRtt = Number(result.stat('googRtt'));
              currentStats.videoFrameRate = Number(result.stat('googFrameRateInput'));
              currentStats.videoWidth = Number(result.stat('googFrameWidthSent'));
              currentStats.videoHeight = Number(result.stat('googFrameHeightSent'));
              currentStats.videoCodec = result.stat('googCodecName');
            } else if (result.stat('googFrameRateReceived')) {
              currentStats.videoRecvBytes = Number(result.stat('bytesReceived'));
              currentStats.videoRecvPackets = Number(result.stat('packetsReceived'));
              currentStats.videoRecvPacketsLost = Number(result.stat('packetsLost'));
              currentStats.videoFrameRate = Number(result.stat('googFrameRateOutput'));
              currentStats.videoWidth = Number(result.stat('googFrameWidthReceived'));
              currentStats.videoHeight = Number(result.stat('googFrameHeightReceived'));
              currentStats.videoCodec = result.stat('googCodecName');
            }
            return null;
          }
1031346
def getFrameTiming(self, unFramesAgo):
        

        fn = self.function_table.getFrameTiming
        pTiming = Compositor_FrameTiming()
        result = fn(byref(pTiming), unFramesAgo)
        return result, pTiming