1
0

Implementation of a simple OGG tag reader.

This commit is contained in:
Alexander Andreev 2023-10-01 03:34:16 +04:00
parent ca33de09cc
commit 18bd1fb12d
Signed by: Arav
GPG Key ID: D22A817D95815393
2 changed files with 58 additions and 0 deletions

23
pkg/oggtag/oggtag.go Normal file
View File

@ -0,0 +1,23 @@
package oggtag
/* oggtag is a naive implementation of OGG tag's reader that is just looking
for certain tag names ending with an = character, e.g. artist= and title=.
*/
import (
"bytes"
)
// OggGetTag is searching for a certain tag in a given buffer buf and returns
// its value.
//
// It is a simple implementation that doesn't parse a header and instead just
// looking for a certain tag preceded with three zero bytes and ends with
// an = character.
func OggGetTag(buf []byte, tag string) string {
tagIdx := bytes.Index(buf, append([]byte{0, 0, 0}, (tag+"=")...)) + 3
tagNameLen := len(tag) + 1
valStart := tagIdx + tagNameLen
valLen := int(buf[tagIdx-4]) - tagNameLen
return string(buf[valStart : valStart+valLen])
}

35
pkg/oggtag/oggtag_test.go Normal file
View File

@ -0,0 +1,35 @@
package oggtag
import (
"os"
"testing"
)
const bufferSize = 4096
const sampleSong = "/mnt/data/appdata/radio/fallback.ogg"
const sampleArtist = "breskina"
const sampleTitle = "Песня про мечты"
func TestOggGetTag(t *testing.T) {
f, _ := os.Open(sampleSong)
buf := make([]byte, bufferSize)
f.Read(buf)
tag := OggGetTag(buf, "artist")
if tag != sampleArtist {
t.Error(tag, "!=", sampleArtist)
}
tag = OggGetTag(buf, "title")
if tag != sampleTitle {
t.Error(tag, "!=", sampleTitle)
}
}
func BenchmarkOggGetTag(b *testing.B) {
f, _ := os.Open(sampleSong)
buf := make([]byte, bufferSize)
f.Read(buf)
b.ResetTimer()
for i := 0; i < b.N; i++ {
OggGetTag(buf, "artist")
}
}