// Demux a 2 channel audio file and save the left channel as a mono file
// http://blog.bjornroche.com/2013/05/the-abcs-of-pcm-uncompressed-digital.html
488254
func main() {
	if len(os.Args) != 2 {
		fmt.Fprintf(os.Stderr, "Usage: demux <file.wav>\n")
		os.Exit(1)
	}

	testInfo, err := os.Stat(os.Args[1])
	checkErr(err)

	testWav, err := os.Open(os.Args[1])
	checkErr(err)

	wavReader, err := wav.NewReader(testWav, testInfo.Size())
	checkErr(err)

	fileMeta := wavReader.GetFile()
	fmt.Println(dump(fileMeta))

	if fileMeta.Channels != 2 {
		log.Fatal("Please use a 2-channel audio file")
	}

	// A slice of many 1-4 byte samples
	var left [][]byte
	left = make([][]byte, fileMeta.NumberOfSamples/2)

	var i uint32
	var buf []byte
	for i = 0; i < fileMeta.NumberOfSamples/2; i++ {

		buf, err = wavReader.ReadRawSample()
		checkErr(err)
		left[i] = buf

		// Throw the right-channel away
		_, err = wavReader.ReadRawSample()
		checkErr(err)
	}

	filename := "mono-" + testInfo.Name()
	os.Remove(filename)

	f, err := os.Create(filename)
	checkErr(err)

	// Create the headers for our new mono file
	meta := wav.File{
		Channels:        1,
		SampleRate:      fileMeta.SampleRate,
		SignificantBits: fileMeta.SignificantBits,
	}

	writer, err := meta.NewWriter(f)
	checkErr(err)

	// Write to file
	for _, sample := range left {
		err = writer.WriteSample(sample)
		checkErr(err)
	}

	err = writer.Close()
	checkErr(err)

	fmt.Println("Created Mono File", f.Name())

	f, err = os.Open(f.Name())
	checkErr(err)

	stat, err := f.Stat()
	checkErr(err)

	wavReader, err = wav.NewReader(f, stat.Size())
	checkErr(err)

	fileMeta = wavReader.GetFile()
	fmt.Println(dump(fileMeta))
}
1347365
func MixAudioFormat(dst, src *uint8, format AudioFormat, len uint32, volume int) {
	_dst := (*C.Uint8)(unsafe.Pointer(dst))
	_src := (*C.Uint8)(unsafe.Pointer(src))
	C.SDL_MixAudioFormat(_dst, _src, format.c(), C.Uint32(len), C.int(volume))
}
795759
func (def *Synthdef) flatten(params Params) *Synthdef {
	def.addParams(params)

	// Get a topologically sorted ugens list.
	ugenNodes := def.topsort(&def.root)

	for _, ugenNode := range ugenNodes {
		// add ugen to synthdef
		ugen, _, seen := def.addUgen(ugenNode)
		if seen {
			continue
		}
		// Add inputs to synthdef and to ugen.
		for _, input := range ugenNode.inputs {
			def.flattenInput(params, ugen, input)
		}
	}
	return def
}
1211409
func ExtractCompressedPublicKey(pm string) string {
	key := ExtractKeyFromPem(pm)
	pub := key.PubKey()
	comp := pub.SerializeCompressed()
	hexb := hex.EncodeToString(comp)
	return hexb
}
809409
func DiffActionSymbol(action plans.Action) string {
	switch action {
	case plans.DeleteThenCreate:
		return "[red]-[reset]/[green]+[reset]"
	case plans.CreateThenDelete:
		return "[green]+[reset]/[red]-[reset]"
	case plans.Create:
		return "  [green]+[reset]"
	case plans.Delete:
		return "  [red]-[reset]"
	case plans.Read:
		return " [cyan]<=[reset]"
	case plans.Update:
		return "  [yellow]~[reset]"
	default:
		return "  ?"
	}
}
182094
func (s *Segment) DictAddr(field string) (uint64, error) {
	fieldIDPlus1, ok := s.fieldsMap[field]
	if !ok {
		return 0, fmt.Errorf("no such field '%s'", field)
	}

	return s.dictLocs[fieldIDPlus1-1], nil
}
398596
func looksLikeDemangledCPlusPlus(demangled string) bool {
	if strings.Contains(demangled, ".<") { // Skip java names of the form "class.<init>"
		return false
	}
	return strings.ContainsAny(demangled, "<>[]") || strings.Contains(demangled, "::")
}
1267079
func (d *Decoder) PCMBuffer(buf *audio.PCMBuffer) error {
	if buf == nil {
		return nil
	}

	if !d.pcmDataAccessed {
		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.BigEndian,
	}

	bytesPerSample := (d.BitDepth-1)/8 + 1
	sampleBufData := make([]byte, bytesPerSample)
	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.
	for i := 0; i < len(buf.Ints); i++ {
		_, err = d.PCMChunk.Read(sampleBufData)
		if err != nil {
			break
		}
		buf.Ints[i] = decodeF(sampleBufData)
	}
	if err == io.EOF {
		err = nil
	}
	buf.Format = format
	if buf.DataType != audio.Integer {
		buf.DataType = audio.Integer
	}

	return err
}
851001
func (d *Decoder) Format() *audio.Format {
	if d == nil {
		return nil
	}
	return &audio.Format{
		NumChannels: int(d.NumChans),
		SampleRate:  int(d.SampleRate),
		BitDepth:    int(d.BitDepth),
		Endianness:  binary.BigEndian,
	}
}
132958
func (mvcc *MVCCLevelDB) DeleteRange(startKey, endKey []byte) error {
	return mvcc.doRawDeleteRange(codec.EncodeBytes(nil, startKey), codec.EncodeBytes(nil, endKey))
}
841842
func (stream *AudioStream) Flush() (err error) {
	ret := int(C.SDL_AudioStreamFlush(stream.cptr()))
	err = errorFromInt(ret)
	return
}
907563
func (d *Decoder) PCMBuffer(buf *audio.IntBuffer) (n int, err error) {
	if buf == nil {
		return 0, nil
	}

	if !d.pcmDataAccessed {
		err := d.FwdToPCM()
		if err != nil {
			return 0, d.err
		}
	}
	if d.PCMChunk == nil {
		return 0, ErrPCMChunkNotFound
	}

	format := &audio.Format{
		NumChannels: int(d.NumChans),
		SampleRate:  int(d.SampleRate),
	}

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

	bPerSample := bytesPerSample(int(d.BitDepth))
	// populate a file buffer to avoid multiple very small reads
	// we need to cap the buffer size to not be bigger than the pcm chunk.
	size := len(buf.Data) * bPerSample
	tmpBuf := make([]byte, size)
	var m int
	m, err = d.PCMChunk.R.Read(tmpBuf)
	if err != nil {
		if err == io.EOF {
			return m, nil
		}
		return m, err
	}
	if m == 0 {
		return m, nil
	}
	bufR := bytes.NewReader(tmpBuf[:m])
	sampleBuf := make([]byte, bPerSample, bPerSample)
	var misaligned bool
	if m%bPerSample > 0 {
		misaligned = true
	}

	// Note that we populate the buffer even if the
	// size of the buffer doesn't fit an even number of frames.
	for n = 0; n < len(buf.Data); n++ {
		buf.Data[n], err = decodeF(bufR, sampleBuf)
		if err != nil {
			// the last sample isn't a full sample but just padding.
			if misaligned {
				n--
			}
			break
		}
	}
	buf.Format = format
	if err == io.EOF {
		err = nil
	}

	return n, err
}
127601
func MakeLeveledMutex(level MutexLevel, locker sync.Locker) LeveledMutex {
	return LeveledMutex{
		level:  level,
		locker: locker,
	}
}
1305025
func MixAudio(dst, src *uint8, len uint32, volume int) {
	_dst := (*C.Uint8)(unsafe.Pointer(dst))
	_src := (*C.Uint8)(unsafe.Pointer(src))
	C.SDL_MixAudio(_dst, _src, C.Uint32(len), C.int(volume))
}
1211598
func NewDemuxer(t Type, r io.Reader) *Demuxer {
	max := MaxPackedSize64k
	if t == Sideband {
		max = MaxPackedSize
	}

	return &Demuxer{
		t:   t,
		r:   r,
		max: max,
		s:   pktline.NewScanner(r),
	}
}
1030237
func DecodeMulti(name string, value string, dst interface{}, codecs ...Codec) error {
	if len(codecs) == 0 {
		return errNoCodecs
	}

	var errors MultiError
	for _, codec := range codecs {
		err := codec.Decode(name, value, dst)
		if err == nil {
			return nil
		}
		errors = append(errors, err)
	}
	return errors
}
1215783
func WeakMultiplex(output SimpleInChannel, inputs ...SimpleOutChannel) {
	if len(inputs) == 0 {
		panic("channels: WeakMultiplex requires at least one input")
	}
	go multiplex(output, inputs, false)
}