// GetMPEGAudioDuration reads the first frame in r and returns the audio length with millisecond precision.
// Format details are at http://www.codeproject.com/Articles/8295/MPEG-Audio-Frame-Header.
771182
func GetMPEGAudioDuration(r readerutil.SizeReaderAt) (time.Duration, error) {
	var header uint32
	if err := binary.Read(io.NewSectionReader(r, 0, r.Size()), binary.BigEndian, &header); err != nil {
		return 0, fmt.Errorf("Failed to read MPEG frame header: %v", err)
	}
	getBits := func(startBit, numBits uint) uint32 {
		return (header << startBit) >> (32 - numBits)
	}

	if getBits(0, 11) != 0x7ff {
		return 0, errors.New("Missing sync bits in MPEG frame header")
	}
	var version mpegVersion
	var ok bool
	if version, ok = mpegVersionsByID[getBits(11, 2)]; !ok {
		return 0, errors.New("Invalid MPEG version index")
	}
	var layer mpegLayer
	if layer, ok = mpegLayersByIndex[getBits(13, 2)]; !ok {
		return 0, errors.New("Invalid MPEG layer index")
	}
	bitrate := mpegBitrates[version][layer][getBits(16, 4)]
	if bitrate == 0 {
		return 0, errors.New("Invalid MPEG bitrate")
	}
	samplingRate := mpegSamplingRates[version][getBits(20, 2)]
	if samplingRate == 0 {
		return 0, errors.New("Invalid MPEG sample rate")
	}
	samplesPerFrame := mpegSamplesPerFrame[version][layer]

	var xingHeaderStart int64 = 4
	// Skip "side information".
	if getBits(24, 2) == 0x3 { // Channel mode; 0x3 is mono.
		xingHeaderStart += 17
	} else {
		xingHeaderStart += 32
	}
	// Skip 16-bit CRC if present.
	if getBits(15, 1) == 0x0 { // 0x0 means "has protection".
		xingHeaderStart += 2
	}

	b := make([]byte, 12)
	if _, err := r.ReadAt(b, xingHeaderStart); err != nil {
		return 0, fmt.Errorf("Unable to read Xing header at %d: %v", xingHeaderStart, err)
	}
	var ms int64
	if bytes.Equal(b[0:4], xingHeaderName) || bytes.Equal(b[0:4], infoHeaderName) {
		r := bytes.NewReader(b[4:])
		var xingFlags uint32
		binary.Read(r, binary.BigEndian, &xingFlags)
		if xingFlags&0x1 == 0x0 {
			return 0, fmt.Errorf("Xing header at %d lacks number of frames", xingHeaderStart)
		}
		var numFrames uint32
		binary.Read(r, binary.BigEndian, &numFrames)
		ms = int64(samplesPerFrame) * int64(numFrames) * 1000 / int64(samplingRate)
	} else {
		// Okay, no Xing VBR header. Assume that the file has a constant bitrate.
		// (The other alternative is to read the whole file and examine each frame.)
		ms = r.Size() / int64(bitrate) * 8
	}
	return time.Duration(ms) * time.Millisecond, nil
}
273163
func loadSound() error {

	file, err := os.Open("airhorn.dca")
	if err != nil {
		fmt.Println("Error opening dca file :", err)
		return err
	}

	var opuslen int16

	for {
		// Read opus frame length from dca file.
		err = binary.Read(file, binary.LittleEndian, &opuslen)

		// If this is the end of the file, just return.
		if err == io.EOF || err == io.ErrUnexpectedEOF {
			err := file.Close()
			if err != nil {
				return err
			}
			return nil
		}

		if err != nil {
			fmt.Println("Error reading from dca file :", err)
			return err
		}

		// Read encoded pcm from dca file.
		InBuf := make([]byte, opuslen)
		err = binary.Read(file, binary.LittleEndian, &InBuf)

		// Should not be any end of file errors
		if err != nil {
			fmt.Println("Error reading from dca file :", err)
			return err
		}

		// Append encoded pcm data to the buffer.
		buffer = append(buffer, InBuf)
	}
}
1049729
func (wav *Reader) ReadRawSample() ([]byte, error) {
	if wav.samplesRead > wav.numSamples {
		return nil, io.EOF
	}

	buf := make([]byte, wav.bytesPerSample)
	n, err := wav.input.Read(buf)
	if err != nil {
		return nil, err
	}

	if n != int(wav.bytesPerSample) {
		return nil, fmt.Errorf("Read %d bytes, should have read %d", n, wav.bytesPerSample)
	}

	wav.samplesRead++

	return buf, nil
}
512986
func MonoDownmix(buf *audio.PCMBuffer) error {
	if buf == nil || buf.Format == nil {
		return audio.ErrInvalidBuffer
	}
	nChans := buf.Format.NumChannels
	if nChans < 2 {
		return nil
	}
	nChansF := float64(nChans)

	frameCount := buf.Size()
	newData := make([]float64, frameCount)
	buf.SwitchPrimaryType(audio.Float)
	for i := 0; i < frameCount; i++ {
		newData[i] = 0
		for j := 0; j < nChans; j++ {
			newData[i] += buf.Floats[i*nChans+j]
		}
		newData[i] /= nChansF
	}
	buf.Floats = newData
	buf.Format.NumChannels = 1

	return nil
}
96075
func (p *Parser) ParseDuration() (time.Duration, error) {
	tok, pos, lit := p.ScanIgnoreWhitespace()
	if tok != DURATIONVAL && tok != INF {
		return 0, newParseError(tokstr(tok, lit), []string{"duration"}, pos)
	}

	if tok == INF {
		return 0, nil
	}

	d, err := ParseDuration(lit)
	if err != nil {
		return 0, &ParseError{Message: err.Error(), Pos: pos}
	}

	return d, nil
}
480739
func getTmpDareMetaPath(object, uploadID string) string {
	return path.Join(getGWMetaPath(object), uploadID, gwdareMetaJSON)
}
346185
func strDurationAddDuration(sc *stmtctx.StatementContext, d string, arg1 types.Duration) (string, error) {
	arg0, err := types.ParseDuration(sc, d, types.MaxFsp)
	if err != nil {
		return "", err
	}
	tmpDuration, err := arg0.Add(arg1)
	if err != nil {
		return "", err
	}
	tmpDuration.Fsp = types.MaxFsp
	if tmpDuration.MicroSecond() == 0 {
		tmpDuration.Fsp = types.MinFsp
	}
	return tmpDuration.String(), nil
}
887002
func (m *Manager) GetDuration(key string) time.Duration {
	return cast.ToDuration(m.Get(key))
}
983028
func (_class VIFMetricsClass) GetLastUpdated(sessionID SessionRef, self VIFMetricsRef) (_retval time.Time, _err error) {
	_method := "VIF_metrics.get_last_updated"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertVIFMetricsRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)
	if _err != nil {
		return
	}
	_retval, _err = convertTimeToGo(_method + " -> ", _result.Value)
	return
}
384014
func (w *Window) GetFramebufferSize() (width, height int) {
	var wi, h C.int
	C.glfwGetFramebufferSize(w.data, &wi, &h)
	return int(wi), int(h)
}
757606
func (f *framer) parseSupportedFrame() frame {
	return &supportedFrame{
		frameHeader: *f.header,

		supported: f.readStringMultiMap(),
	}
}
441995
func fmtEtimeDuration(d time.Duration) string {
	days := d / (24 * time.Hour)
	hours := d % (24 * time.Hour)
	minutes := hours % time.Hour
	seconds := math.Mod(minutes.Seconds(), 60)
	var b bytes.Buffer
	if days > 0 {
		fmt.Fprintf(&b, "%02d-", days)
	}
	if hours/time.Hour > 0 {
		fmt.Fprintf(&b, "%02d:", hours/time.Hour)
	}
	fmt.Fprintf(&b, "%02d:", minutes/time.Minute)
	fmt.Fprintf(&b, "%02.0f", seconds)
	return b.String()
}
1352094
func (b *builtinAddDurationAndStringSig) evalDuration(row chunk.Row) (types.Duration, bool, error) {
	arg0, isNull, err := b.args[0].EvalDuration(b.ctx, row)
	if isNull || err != nil {
		return types.ZeroDuration, isNull, err
	}
	s, isNull, err := b.args[1].EvalString(b.ctx, row)
	if isNull || err != nil {
		return types.ZeroDuration, isNull, err
	}
	if !isDuration(s) {
		return types.ZeroDuration, true, nil
	}
	arg1, err := types.ParseDuration(b.ctx.GetSessionVars().StmtCtx, s, types.GetFsp(s))
	if err != nil {
		return types.ZeroDuration, true, err
	}
	result, err := arg0.Add(arg1)
	if err != nil {
		return types.ZeroDuration, true, err
	}
	return result, false, nil
}
1057081
func (p *PerKeyThroughput) GetSampleRate(key string) int {
	p.lock.Lock()
	defer p.lock.Unlock()
	p.currentCounts[key]++
	if rate, found := p.savedSampleRates[key]; found {
		return rate
	}
	return 1
}
569453
func getCompleteMultipartMD5(ctx context.Context, parts []CompletePart) (string, error) {
	var finalMD5Bytes []byte
	for _, part := range parts {
		md5Bytes, err := hex.DecodeString(canonicalizeETag(part.ETag))
		if err != nil {
			logger.LogIf(ctx, err)
			return "", err
		}
		finalMD5Bytes = append(finalMD5Bytes, md5Bytes...)
	}
	s3MD5 := fmt.Sprintf("%s-%d", getMD5Hash(finalMD5Bytes), len(parts))
	return s3MD5, nil
}
1084195
func (m *Monitor) GetVideoMode() *VidMode {
	t := C.glfwGetVideoMode(m.data)
	if t == nil {
		return nil
	}
	panicError()
	return &VidMode{int(t.width), int(t.height), int(t.redBits), int(t.greenBits), int(t.blueBits), int(t.refreshRate)}
}
736339
func (t *SimpleTrack) TimeDuration() time.Duration {
	return time.Duration(t.Duration) * time.Millisecond
}