package formats

import (
	"bytes"
	"fmt"
	"github.com/bluenviron/mediacommon/v2/pkg/codecs/g711"
	"github.com/gen2brain/aac-go"
)

// ConvertG711ToLPCM converts G711 to LPCM.
func ConvertG711ToLPCM(g711Samples []byte, mulaw bool) []byte {
	var pcmSamples []byte
	if mulaw {
		pcmSamples = g711.DecodeMulaw(g711Samples)
	} else {
		pcmSamples = g711.DecodeAlaw(g711Samples)
	}

	return pcmSamples
}

// ConvertLPCMToAAC converts G711 to AAC.
func ConvertLPCMToAAC(pcmSamples []byte) ([]byte, error) {
	var buf bytes.Buffer
	opts := &aac.Options{
		SampleRate:  8000, // Исходная частота G711
		NumChannels: 1,
	}

	enc, err := aac.NewEncoder(&buf, opts)
	if err != nil {
		return nil, fmt.Errorf("error creating encoder: %v", err)
	}
	defer enc.Close()

	r := bytes.NewReader(pcmSamples)
	if err := enc.Encode(r); err != nil {
		return nil, fmt.Errorf("error encoding: %v", err)
	}

	return buf.Bytes(), nil
}
