// very simple program that wraps ffmpeg and outputs raw opus data frames
// with a uint16 header for each frame with the frame length in bytes
552358
func main() {

	//////////////////////////////////////////////////////////////////////////
	// BLOCK : Basic setup and validation
	//////////////////////////////////////////////////////////////////////////

	// If only one argument provided assume it's a filename.
	if len(os.Args) == 2 {
		InFile = os.Args[1]
	}

	// If reading from a file, verify it exists.
	if InFile != "pipe:0" {
		if _, err := os.Stat(InFile); os.IsNotExist(err) {
			fmt.Fprintln(os.Stderr, "warning: infile does not exist as a file on this system, will still continue on incase this is something else that ffmpeg accepts")
		}
	}

	// If reading from pipe, make sure pipe is open
	if InFile == "pipe:0" {
		fi, err := os.Stdin.Stat()
		if err != nil {
			fmt.Println(err)
			return
		}

		if (fi.Mode() & os.ModeCharDevice) == 0 {
		} else {
			fmt.Fprintln(os.Stderr, "error: stdin is not a pipe.")
			flag.Usage()
			return
		}
	}

	if Bitrate < 1 || Bitrate > 512 {
		Bitrate = 64 // Set to Discord default
	}

	//////////////////////////////////////////////////////////////////////////
	// BLOCK : Start reader and writer workers
	//////////////////////////////////////////////////////////////////////////

	options := &dca.EncodeOptions{
		Volume:        Volume,
		Channels:      Channels,
		FrameRate:     FrameRate,
		FrameDuration: FrameDuration,
		Bitrate:       Bitrate,
		RawOutput:     RawOutput,
		Application:   dca.AudioApplication(Application),
		CoverFormat:   CoverFormat,
		VBR:           VBR,
		Comment:       Comment,
		Threads:       Threads,
	}

	var session *dca.EncodeSession
	var output = os.Stdout

	if InFile == "pipe:0" {
		session, err = dca.EncodeMem(os.Stdin, options)
	} else {
		session, err = dca.EncodeFile(InFile, options)
	}

	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed creating an encoding session: ", err)
		os.Exit(1)
	}

	if !Quiet {
		go statusPrinter(session)
	}

	_, err := io.Copy(output, session)
	if err != nil {
		fmt.Fprintln(os.Stderr, "\nError writing:", err)
		os.Exit(1)
	} else if !Quiet {
		fmt.Fprintf(os.Stderr, "\nFinished encoding\n")
		fmt.Fprint(os.Stderr, "ffmpeg output\n\n", session.FFMPEGMessages())
	}
}
234639
func (rf *RawFrame) ToFrame(out *Frame) error {
	if err := ParseTelemetry(rf[:], &out.Status); err != nil {
		return err
	}

	rawPix := rf[telemetryPacketCount*vospiDataSize:]
	i := 0
	for y := 0; y < FrameRows; y++ {
		for x := 0; x < FrameCols; x++ {
			out.Pix[y][x] = binary.BigEndian.Uint16(rawPix[i : i+2])
			i += 2
		}
	}
	return nil
}
1113015
func GnuplotBin(buf *audio.PCMBuffer, path string) error {
	if buf == nil || buf.Format == nil {
		return audio.ErrInvalidBuffer
	}
	out, err := os.Create(path)
	if err != nil {
		return err
	}
	defer out.Close()
	for _, s := range buf.AsFloat32s() {
		if err = binary.Write(out, binary.BigEndian, s); err != nil {
			break
		}
	}
	return err
}
823164
func sampleFloat64DecodeFunc(bitsPerSample int) (func([]byte) float64, error) {
	bytesPerSample := bitsPerSample / 8
	switch bytesPerSample {
	case 1:
		// 8bit values are unsigned
		return func(s []byte) float64 {
			return float64(uint8(s[0]))
		}, nil
	case 2:
		return func(s []byte) float64 {
			return float64(int(s[0]) + int(s[1])<<8)
		}, nil
	case 3:
		return func(s []byte) float64 {
			var output int32
			output |= int32(s[2]) << 0
			output |= int32(s[1]) << 8
			output |= int32(s[0]) << 16
			return float64(output)
		}, nil
	case 4:
		// TODO: fix the float64 conversion (current int implementation)
		return func(s []byte) float64 {
			return float64(int(s[0]) + int(s[1])<<8 + int(s[2])<<16 + int(s[3])<<24)
		}, nil
	default:
		return nil, fmt.Errorf("unhandled byte depth:%d", bitsPerSample)
	}
}
208491
func (g *GroupComposer) Raw() interface{} {
	if len(g.messages) == 1 && g.messages[0].Loggable() {
		return g.messages[0].Raw()
	}

	out := []interface{}{}
	for _, m := range g.messages {
		if m == nil {
			continue
		}
		if m.Loggable() {
			out = append(out, m.Raw())
		}
	}

	return out
}
163099
func dct16(data *[16]float32) {
	var even, odd [8]float32
	for i := 0; i < 8; i++ {
		even[i] = data[i] + data[15-i]
		odd[i] = (data[i] - data[15-i]) * dct16c[i]
	}

	dct8(&even)
	dct8(&odd)

	for i := 0; i < 7; i++ {
		odd[i] += odd[i+1]
	}

	for i := 0; i < 8; i++ {
		data[2*i] = even[i]
		data[2*i+1] = odd[i]
	}
}
175097
func (d *Decoder) PCMBuffer(buf *audio.PCMBuffer) error {
	if buf == nil {
		return nil
	}

	if !d.pcmDataAccessed {
		if d.Debug {
			fmt.Println("forwarding to PCM Data")
		}
		err := d.FwdToPCM()
		if err != nil {
			return d.err
		}
	}

	// TODO: avoid a potentially unecessary allocation
	format := &audio.Format{
		NumChannels: int(d.NumChans),
		SampleRate:  int(d.SampleRate),
		BitDepth:    int(d.BitDepth),
		Endianness:  binary.LittleEndian,
	}

	decodeF, err := sampleDecodeFunc(int(d.BitDepth))
	if err != nil {
		return fmt.Errorf("could not get sample decode func %v", err)
	}

	// Note that we populate the buffer even if the
	// size of the buffer doesn't fit an even number of frames.
	if d.Debug {
		fmt.Println("populating %d samples", len(buf.Ints))
	}
	for i := 0; i < len(buf.Ints); i++ {
		buf.Ints[i], err = decodeF(d.r)
		if err != nil {
			break
		}
	}
	if err == io.EOF {
		err = nil
	}
	buf.Format = format
	if buf.DataType != audio.Integer {
		buf.DataType = audio.Integer
	}

	return err
}
778360
func DumpFunction(fun ZlispFunction, pc int) {
	blank := "      "
	extra := blank
	for i, instr := range fun {
		if i == pc {
			extra = " PC-> "
		} else {
			extra = blank
		}
		fmt.Printf("%s %d: %s\n", extra, i, instr.InstrString())
	}
	if pc == len(fun) {
		fmt.Printf(" PC just past end at %d -----\n\n", pc)
	}
}
933504
func WriteFrame(w io.Writer, f Frame) error {
	err := WriteHeader(w, f.Header)
	if err != nil {
		return err
	}
	_, err = w.Write(f.Payload)
	return err
}
71032
func parseFieldDataLength(data []byte) (uint16, error) {
	if len(data) != 2 {
		return 0, fmt.Errorf("data length must be 2 bytes, was %d",
			len(data))
	}

	return uint16(data[0])<<5 | uint16(data[1]), nil
}
498332
func (s *Application) InitCodec(hashKey []byte, blockKey []byte) {
	s.Codec = codec.New(hashKey, blockKey)
}
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
}
1201726
func BenchmarkEncoder(input []byte, enc Encoder, lvl int) testing.BenchmarkResult {
	return testing.Benchmark(func(b *testing.B) {
		b.StopTimer()
		if enc == nil {
			b.Fatalf("unexpected error: nil Encoder")
		}
		runtime.GC()
		b.StartTimer()
		for i := 0; i < b.N; i++ {
			wr := enc(ioutil.Discard, lvl)
			_, err := io.Copy(wr, bytes.NewBuffer(input))
			if err := wr.Close(); err != nil {
				b.Fatalf("unexpected error: %v", err)
			}
			if err != nil {
				b.Fatalf("unexpected error: %v", err)
			}
			b.SetBytes(int64(len(input)))
		}
	})
}
617277
func Uint16(v uint16) *uint16 {
	p := new(uint16)
	*p = v
	return p
}
772357
func protoc(goOut string, includes, fnames []string) ([]byte, error) {
	args := []string{"--go_out=plugins=grpc:" + goOut}
	for _, inc := range includes {
		args = append(args, "-I", inc)
	}
	args = append(args, fnames...)
	return exec.Command("protoc", args...).CombinedOutput()
}
505931
func (r *renderedFrame) dumpTo(w io.Writer, idx int) (n int, err error) {
	return iotools.WriteTracker(w, func(rawWriter io.Writer) error {
		w := &indented.Writer{Writer: rawWriter, UseSpaces: true}

		fmt.Fprintf(w, "#%d %s/%s:%d - %s()\n", idx, r.pkg, r.file,
			r.lineNum, r.funcName)
		w.Level += 2
		switch len(r.annotations) {
		case 0:
			// pass
		case 1:
			for _, line := range r.annotations[0] {
				fmt.Fprintf(w, "%s\n", line)
			}
		default:
			for i, ann := range r.annotations {
				fmt.Fprintf(w, "annotation #%d:\n", i)
				w.Level += 2
				for _, line := range ann {
					fmt.Fprintf(w, "%s\n", line)
				}
				w.Level -= 2
			}
		}
		return nil
	})
}
979867
func (fs *FSObjects) encodePartFile(partNumber int, etag string, actualSize int64) string {
	return fmt.Sprintf("%.5d.%s.%d", partNumber, etag, actualSize)
}