<commit_before>/* Routines for receiving & transmitting & processing audio.
 */
package rxtx

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"log"
	"math"
	"net"
	"os"
	"time"
)
import . "log"

const (
	PowerFlag = 0x01
	TxFlag    = 0x02
	AudioFlag = 0x04
	WhoFlag   = 0x08
)

const VERSION = 11411
const SamplesPerSec = 8000
const SamplesPerPacket = 200

var ENDIAN = binary.BigEndian

type Header struct {
	Version int16
	Length  int16
	Time    int32
	Seq     byte
	Flags   byte
	Source  byte
	Dest    byte
	// TODO -- authenticate after payload.
}

type Station struct {
	Id     byte
	Latest time.Time // Latest time from this station.
	Seq    byte      // Latest sequence from this station.
	Addr   *net.UDPAddr
}

type Socket struct {
	Addr   *net.UDPAddr
	Conn   *net.UDPConn
	Engine *Engine
}

type Engine struct {
	Me       int
	Other    int
	Stations map[byte]*Station
	// PrevSecs int
	// PrevSeq  int
	Sock      *Socket
	ProxyAddr *net.UDPAddr
	Audio     *os.File
}

func NewEngine(me int, proxyAddrString string) *Engine {
	a, err := net.ResolveUDPAddr("udp", proxyAddrString)
	if err != nil {
		panic(err)
	}
	return &Engine{
		Me:        me,
		Stations:  make(map[byte]*Station),
		ProxyAddr: a,
	}
}

func (e *Engine) RegisterStation(id byte, addr string) *Station {
	a, err := net.ResolveUDPAddr("udp", addr)
	if err != nil {
		panic(err)
	}
	station := &Station{
		Id:   id,
		Addr: a,
	}
	e.Stations[id] = station
	return station
}

func (e *Engine) InitSocket(localAddr string) {
	addr, err := net.ResolveUDPAddr("udp", localAddr)
	if err != nil {
		panic(err)
	}
	conn, err := net.ListenUDP("udp", addr)
	if err != nil {
		panic(err)
	}
	e.Sock = &Socket{
		Addr:   addr,
		Conn:   conn,
		Engine: e,
	}
}

func (e *Engine) ForgeHeader() *Header {
	now := time.Now().Unix()
	h := &Header{
		Version: VERSION,
		Length:  0,
		Time:    int32(now),
		Seq:     0, // TODO
		Flags:   0, // TODO
		Source:  byte(e.Me),
		Dest:    byte(255),
	}
	return h
}

func (e *Engine) WritePacket(h *Header, segment []byte, dest *net.UDPAddr) {
	h.Length = int16(len(segment))
	sz := binary.Size(h)
	w := bytes.NewBuffer(nil)
	err := binary.Write(w, ENDIAN, h)
	if err != nil {
		panic(err)
	}
	z := make([]byte, sz+len(segment))
	copy(z[:sz], w.String())
	copy(z[sz:], segment)

	n, err := e.Sock.Conn.WriteToUDP(z, dest)

	if err != nil {
		log.Panicf("WritePacket: Cannot WriteToUDP: %v", err)
	}
	if n != len(z) {
		log.Panicf("WritePacket: Wrote %d bytes, expected %d", n, len(z))
	}
}

func (e *Engine) ReadPacket(segment []byte) *Header {
	packet := make([]byte, 512)
	size, _, err := e.Sock.Conn.ReadFromUDP(packet)
	if err != nil {
		panic(err)
	}
	//println("size", size)

	h := new(Header)
	hSize := binary.Size(h)
	//println("hSize", hSize)
	if hSize < 0 {
		panic("hSize")
	}

	if size < hSize {
		panic(size)
	}

	r := bytes.NewReader(packet)
	err = binary.Read(r, binary.BigEndian, h)
	if err != nil {
		panic(err)
	}
	// e.MarkStation(h, addr)

	// TODO: Authenticate.
	// actualPayload := int(size) - hSize
	//println("actualPayload", actualPayload)
	// fmt.Printf("%#v\n", *h)
	/*
		if actualPayload != int(h.Length) {
			Panicf("Got %d payload bytes; expected %d", actualPayload, h.Length)
		}

		if h.Length > 0 {
			if h.Length != SamplesPerPacket {
				Panicf("Got payload length %d wanted %d", h.Length, SamplesPerPacket)
			}
		}
	*/

	copy(segment, packet[hSize:])

	return h
}

func (e *Engine) InitAudio(path string) {
	audio, err := os.OpenFile(path, os.O_RDWR, 0666)
	if err != nil {
		panic(err)
	}
	e.Audio = audio
}

func ShowBytes(bb []byte) string {
	z := bytes.NewBufferString("[")
	prev := -1
	for _, e := range bb {
		if int(e) == prev {
			z.WriteRune('*')
		} else {
			fmt.Fprintf(z, "%d,", e)
		}
		prev = int(e)
	}
	z.WriteRune(']')
	return z.String()
}

func (e *Engine) ProxyCommand() {
	packet := make([]byte, 512)
	pals := make(map[string]*net.UDPAddr)<commit_msg>Init HSIZE<commit_after>/* Routines for receiving & transmitting & processing audio.
 */
package rxtx

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"log"
	"math"
	"net"
	"os"
	"time"
)
import . "log"

const (
	PowerFlag = 0x01
	TxFlag    = 0x02
	AudioFlag = 0x04
	WhoFlag   = 0x08
)

const VERSION = 11411
const SamplesPerSec = 8000
const SamplesPerPacket = 200

var ENDIAN = binary.BigEndian
var HSIZE = binary.Size(new(Header))

func init() {
	if HSIZE < 0 {
		panic("HSIZE")
	}
}

type Header struct {
	Version int16
	Length  int16
	Time    int32
	Seq     byte
	Flags   byte
	Source  byte
	Dest    byte
	// TODO -- authenticate after payload.
}

type Station struct {
	Id     byte
	Latest time.Time // Latest time from this station.
	Seq    byte      // Latest sequence from this station.
	Addr   *net.UDPAddr
}

type Socket struct {
	Addr   *net.UDPAddr
	Conn   *net.UDPConn
	Engine *Engine
}

type Engine struct {
	Me       int
	Other    int
	Stations map[byte]*Station
	// PrevSecs int
	// PrevSeq  int
	Sock      *Socket
	ProxyAddr *net.UDPAddr
	Audio     *os.File
}

func NewEngine(me int, proxyAddrString string) *Engine {
	a, err := net.ResolveUDPAddr("udp", proxyAddrString)
	if err != nil {
		panic(err)
	}
	return &Engine{
		Me:        me,
		Stations:  make(map[byte]*Station),
		ProxyAddr: a,
	}
}

func (e *Engine) RegisterStation(id byte, addr string) *Station {
	a, err := net.ResolveUDPAddr("udp", addr)
	if err != nil {
		panic(err)
	}
	station := &Station{
		Id:   id,
		Addr: a,
	}
	e.Stations[id] = station
	return station
}

func (e *Engine) InitSocket(localAddr string) {
	addr, err := net.ResolveUDPAddr("udp", localAddr)
	if err != nil {
		panic(err)
	}
	conn, err := net.ListenUDP("udp", addr)
	if err != nil {
		panic(err)
	}
	e.Sock = &Socket{
		Addr:   addr,
		Conn:   conn,
		Engine: e,
	}
}

func (e *Engine) ForgeHeader() *Header {
	now := time.Now().Unix()
	h := &Header{
		Version: VERSION,
		Length:  0,
		Time:    int32(now),
		Seq:     0, // TODO
		Flags:   0, // TODO
		Source:  byte(e.Me),
		Dest:    byte(255),
	}
	return h
}

func (e *Engine) WritePacket(h *Header, segment []byte, dest *net.UDPAddr) {
	h.Length = int16(len(segment))
	sz := binary.Size(h)
	w := bytes.NewBuffer(nil)
	err := binary.Write(w, ENDIAN, h)
	if err != nil {
		panic(err)
	}
	z := make([]byte, sz+len(segment))
	copy(z[:sz], w.String())
	copy(z[sz:], segment)

	n, err := e.Sock.Conn.WriteToUDP(z, dest)

	if err != nil {
		log.Panicf("WritePacket: Cannot WriteToUDP: %v", err)
	}
	if n != len(z) {
		log.Panicf("WritePacket: Wrote %d bytes, expected %d", n, len(z))
	}
}

func (e *Engine) ReadPacket(segment []byte) *Header {
	packet := make([]byte, 512)
	size, _, err := e.Sock.Conn.ReadFromUDP(packet)
	if err != nil {
		panic(err)
	}

	if size < HSIZE {
		panic(size)
	}

	r := bytes.NewReader(packet)
	h := new(Header)
	err = binary.Read(r, binary.BigEndian, h)
	if err != nil {
		panic(err)
	}

	actualPayload := int(size) - HSIZE

	if actualPayload != int(h.Length) {
		Panicf("Got %d payload bytes; expected %d", actualPayload, h.Length)
	}

	if h.Length > 0 {
		if h.Length != SamplesPerPacket {
			Panicf("Got payload length %d wanted %d", h.Length, SamplesPerPacket)
		}
		copy(segment, packet[HSIZE:])
	}
	return h
}

func (e *Engine) InitAudio(path string) {
	audio, err := os.OpenFile(path, os.O_RDWR, 0666)
	if err != nil {
		panic(err)
	}
	e.Audio = audio
}

func ShowBytes(bb []byte) string {
	z := bytes.NewBufferString("[")
	prev := -1
	for _, e := range bb {
		if int(e) == prev {
			z.WriteRune('*')
		} else {
			fmt.Fprintf(z, "%d,", e)
		}
		prev = int(e)
	}
	z.WriteRune(']')
	return z.String()
}

func (e *Engine) ProxyCommand() {
	packet := make([]byte, 512)
	pals := make(map[string]*net.UDPAddr)
{'fraction_non_alphanumeric': 0.15756467206689312, 'fraction_numerical': 0.013848967859942513, 'mean_word_length': 3.146803900325027, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1124592', 'n_tokens_mistral': 3278, 'n_tokens_neox': 3074, 'n_words': 793}