radio-stream-recorder/vorbis/vorbis.go

82 lines
1.9 KiB
Go
Raw Normal View History

2021-06-03 19:07:27 +02:00
package vorbis
import (
"bytes"
"errors"
"io"
"strconv"
"strings"
2021-06-03 19:07:27 +02:00
)
var (
ErrNoHeaderSegment = errors.New("vorbis: no header segment")
2021-06-03 19:07:27 +02:00
)
type Extractor struct {
2021-06-03 19:07:27 +02:00
hasMetadata bool
metadata *VorbisComment // Used for filename.
checksum uint32 // Used for an alternate filename when there's no metadata.
2021-06-03 19:07:27 +02:00
}
func NewExtractor() (*Extractor, error) {
return new(Extractor), nil
2021-06-03 19:07:27 +02:00
}
func (d *Extractor) ReadBlock(reader io.Reader, w io.Writer) (isFirst bool, err error) {
// Everything we read here is part of the music data so we can just use a
// tee reader.
r := io.TeeReader(reader, w)
2021-06-03 19:07:27 +02:00
// Decode page.
page, err := OggDecode(r)
2021-06-03 19:07:27 +02:00
if err != nil {
return false, err
2021-06-03 19:07:27 +02:00
}
// We need to be able to access `page.Segments[0]`.
if len(page.Segments) == 0 {
return false, ErrNoHeaderSegment
2021-06-03 19:07:27 +02:00
}
// Decode Vorbis header, stored in `page.Segments[0]`.
hdr, err := VorbisHeaderDecode(bytes.NewBuffer(page.Segments[0]))
2021-06-03 19:07:27 +02:00
if err != nil {
return false, err
2021-06-03 19:07:27 +02:00
}
// Extract potential metadata.
if hdr.PackType == PackTypeComment {
d.hasMetadata = true
d.metadata = hdr.Comment
d.checksum = page.Header.Checksum
2021-06-03 19:07:27 +02:00
}
// Return true for isFirst if this block is the beginning of a new file.
return (page.Header.HeaderType & FHeaderTypeBOS) > 0, nil
2021-06-03 19:07:27 +02:00
}
func (d *Extractor) TryGetFilename() (filename string, hasFilename bool) {
2021-06-03 19:07:27 +02:00
if !d.hasMetadata {
return "", false
2021-06-03 19:07:27 +02:00
}
d.hasMetadata = false
// Use relevant metadata to create a filename.
var base string // Filename without extension.
artist, artistOk := d.metadata.FieldByName("Artist")
title, titleOk := d.metadata.FieldByName("Title")
if artistOk || titleOk {
if !artistOk {
artist = "Unknown"
} else if !titleOk {
title = "Unknown"
2021-06-03 19:07:27 +02:00
}
base = artist + " -- " + title
} else {
base = "Unknown_" + strconv.FormatInt(int64(d.checksum), 10)
2021-06-03 19:07:27 +02:00
}
base = strings.ReplaceAll(base, "/", "_") // Replace invalid characters.
2021-06-03 19:07:27 +02:00
return base + ".ogg", true
2021-06-03 19:07:27 +02:00
}