id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
12,200
mattheath/base62
base62.go
pad
func (e *Encoding) pad(s string, minlen int) string { if len(s) >= minlen { return s } format := fmt.Sprint(`%0`, strconv.Itoa(minlen), "s") return fmt.Sprintf(format, s) }
go
func (e *Encoding) pad(s string, minlen int) string { if len(s) >= minlen { return s } format := fmt.Sprint(`%0`, strconv.Itoa(minlen), "s") return fmt.Sprintf(format, s) }
[ "func", "(", "e", "*", "Encoding", ")", "pad", "(", "s", "string", ",", "minlen", "int", ")", "string", "{", "if", "len", "(", "s", ")", ">=", "minlen", "{", "return", "s", "\n", "}", "\n\n", "format", ":=", "fmt", ".", "Sprint", "(", "`%0`", ",", "strconv", ".", "Itoa", "(", "minlen", ")", ",", "\"", "\"", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "format", ",", "s", ")", "\n", "}" ]
// pad a string to a minimum length with zero characters
[ "pad", "a", "string", "to", "a", "minimum", "length", "with", "zero", "characters" ]
b80cdc656a7a61702f293555d54777d6ff617eb7
https://github.com/mattheath/base62/blob/b80cdc656a7a61702f293555d54777d6ff617eb7/base62.go#L195-L202
12,201
libp2p/go-libp2p-pnet
generate.go
GenerateV1PSK
func GenerateV1PSK() (io.Reader, error) { psk, err := GenerateV1Bytes() if err != nil { return nil, err } hexPsk := make([]byte, len(psk)*2) hex.Encode(hexPsk, psk[:]) // just a shortcut to NewReader nr := func(b []byte) io.Reader { return bytes.NewReader(b) } return io.MultiReader(nr(pathPSKv1), newLine(), nr([]byte("/base16/")), newLine(), nr(hexPsk)), nil }
go
func GenerateV1PSK() (io.Reader, error) { psk, err := GenerateV1Bytes() if err != nil { return nil, err } hexPsk := make([]byte, len(psk)*2) hex.Encode(hexPsk, psk[:]) // just a shortcut to NewReader nr := func(b []byte) io.Reader { return bytes.NewReader(b) } return io.MultiReader(nr(pathPSKv1), newLine(), nr([]byte("/base16/")), newLine(), nr(hexPsk)), nil }
[ "func", "GenerateV1PSK", "(", ")", "(", "io", ".", "Reader", ",", "error", ")", "{", "psk", ",", "err", ":=", "GenerateV1Bytes", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "hexPsk", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "psk", ")", "*", "2", ")", "\n", "hex", ".", "Encode", "(", "hexPsk", ",", "psk", "[", ":", "]", ")", "\n\n", "// just a shortcut to NewReader", "nr", ":=", "func", "(", "b", "[", "]", "byte", ")", "io", ".", "Reader", "{", "return", "bytes", ".", "NewReader", "(", "b", ")", "\n", "}", "\n", "return", "io", ".", "MultiReader", "(", "nr", "(", "pathPSKv1", ")", ",", "newLine", "(", ")", ",", "nr", "(", "[", "]", "byte", "(", "\"", "\"", ")", ")", ",", "newLine", "(", ")", ",", "nr", "(", "hexPsk", ")", ")", ",", "nil", "\n", "}" ]
// GenerateV1PSK generates new PSK key that can be used with NewProtector
[ "GenerateV1PSK", "generates", "new", "PSK", "key", "that", "can", "be", "used", "with", "NewProtector" ]
804a7ba9d464f79a6ff464d67f781fc8351ed498
https://github.com/libp2p/go-libp2p-pnet/blob/804a7ba9d464f79a6ff464d67f781fc8351ed498/generate.go#L15-L29
12,202
libp2p/go-libp2p-pnet
protector.go
NewProtector
func NewProtector(input io.Reader) (ipnet.Protector, error) { psk, err := decodeV1PSK(input) if err != nil { return nil, fmt.Errorf("malformed private network key: %s", err) } return NewV1ProtectorFromBytes(psk) }
go
func NewProtector(input io.Reader) (ipnet.Protector, error) { psk, err := decodeV1PSK(input) if err != nil { return nil, fmt.Errorf("malformed private network key: %s", err) } return NewV1ProtectorFromBytes(psk) }
[ "func", "NewProtector", "(", "input", "io", ".", "Reader", ")", "(", "ipnet", ".", "Protector", ",", "error", ")", "{", "psk", ",", "err", ":=", "decodeV1PSK", "(", "input", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "NewV1ProtectorFromBytes", "(", "psk", ")", "\n", "}" ]
// NewProtector creates ipnet.Protector instance from a io.Reader stream // that should include Multicodec encoded V1 PSK.
[ "NewProtector", "creates", "ipnet", ".", "Protector", "instance", "from", "a", "io", ".", "Reader", "stream", "that", "should", "include", "Multicodec", "encoded", "V1", "PSK", "." ]
804a7ba9d464f79a6ff464d67f781fc8351ed498
https://github.com/libp2p/go-libp2p-pnet/blob/804a7ba9d464f79a6ff464d67f781fc8351ed498/protector.go#L15-L21
12,203
libp2p/go-libp2p-pnet
protector.go
NewV1ProtectorFromBytes
func NewV1ProtectorFromBytes(psk *[32]byte) (ipnet.Protector, error) { return &protector{ psk: psk, fingerprint: fingerprint(psk), }, nil }
go
func NewV1ProtectorFromBytes(psk *[32]byte) (ipnet.Protector, error) { return &protector{ psk: psk, fingerprint: fingerprint(psk), }, nil }
[ "func", "NewV1ProtectorFromBytes", "(", "psk", "*", "[", "32", "]", "byte", ")", "(", "ipnet", ".", "Protector", ",", "error", ")", "{", "return", "&", "protector", "{", "psk", ":", "psk", ",", "fingerprint", ":", "fingerprint", "(", "psk", ")", ",", "}", ",", "nil", "\n", "}" ]
// NewV1ProtectorFromBytes creates ipnet.Protector of the V1 version.
[ "NewV1ProtectorFromBytes", "creates", "ipnet", ".", "Protector", "of", "the", "V1", "version", "." ]
804a7ba9d464f79a6ff464d67f781fc8351ed498
https://github.com/libp2p/go-libp2p-pnet/blob/804a7ba9d464f79a6ff464d67f781fc8351ed498/protector.go#L24-L29
12,204
globalsign/certlint
checks/certificate.go
RegisterCertificateCheck
func RegisterCertificateCheck(name string, filter *Filter, f func(*certdata.Data) *errors.Errors) { certMutex.Lock() Certificate = append(Certificate, certificateCheck{name, filter, f}) certMutex.Unlock() }
go
func RegisterCertificateCheck(name string, filter *Filter, f func(*certdata.Data) *errors.Errors) { certMutex.Lock() Certificate = append(Certificate, certificateCheck{name, filter, f}) certMutex.Unlock() }
[ "func", "RegisterCertificateCheck", "(", "name", "string", ",", "filter", "*", "Filter", ",", "f", "func", "(", "*", "certdata", ".", "Data", ")", "*", "errors", ".", "Errors", ")", "{", "certMutex", ".", "Lock", "(", ")", "\n", "Certificate", "=", "append", "(", "Certificate", ",", "certificateCheck", "{", "name", ",", "filter", ",", "f", "}", ")", "\n", "certMutex", ".", "Unlock", "(", ")", "\n", "}" ]
// RegisterCertificateCheck adds a new check to Cerificates
[ "RegisterCertificateCheck", "adds", "a", "new", "check", "to", "Cerificates" ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/checks/certificate.go#L24-L28
12,205
globalsign/certlint
checks/certificate.go
Check
func (c certificate) Check(d *certdata.Data) *errors.Errors { var e = errors.New(nil) for _, cc := range c { if cc.filter != nil && !cc.filter.Check(d) { continue } e.Append(cc.f(d)) } return e }
go
func (c certificate) Check(d *certdata.Data) *errors.Errors { var e = errors.New(nil) for _, cc := range c { if cc.filter != nil && !cc.filter.Check(d) { continue } e.Append(cc.f(d)) } return e }
[ "func", "(", "c", "certificate", ")", "Check", "(", "d", "*", "certdata", ".", "Data", ")", "*", "errors", ".", "Errors", "{", "var", "e", "=", "errors", ".", "New", "(", "nil", ")", "\n\n", "for", "_", ",", "cc", ":=", "range", "c", "{", "if", "cc", ".", "filter", "!=", "nil", "&&", "!", "cc", ".", "filter", ".", "Check", "(", "d", ")", "{", "continue", "\n", "}", "\n", "e", ".", "Append", "(", "cc", ".", "f", "(", "d", ")", ")", "\n", "}", "\n\n", "return", "e", "\n", "}" ]
// Check runs all the registered certificate checks
[ "Check", "runs", "all", "the", "registered", "certificate", "checks" ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/checks/certificate.go#L31-L42
12,206
globalsign/certlint
asn1/asn1.go
CheckStruct
func (l *Linter) CheckStruct(der []byte) *errors.Errors { l.walk(der) if l.e.IsError() { return &l.e } return nil }
go
func (l *Linter) CheckStruct(der []byte) *errors.Errors { l.walk(der) if l.e.IsError() { return &l.e } return nil }
[ "func", "(", "l", "*", "Linter", ")", "CheckStruct", "(", "der", "[", "]", "byte", ")", "*", "errors", ".", "Errors", "{", "l", ".", "walk", "(", "der", ")", "\n", "if", "l", ".", "e", ".", "IsError", "(", ")", "{", "return", "&", "l", ".", "e", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckStruct returns a list of errors based on strict checks on the raw ASN1 // encoding of the input der.
[ "CheckStruct", "returns", "a", "list", "of", "errors", "based", "on", "strict", "checks", "on", "the", "raw", "ASN1", "encoding", "of", "the", "input", "der", "." ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/asn1/asn1.go#L15-L21
12,207
globalsign/certlint
asn1/asn1.go
walk
func (l *Linter) walk(der []byte) { var err error var d asn1.RawValue for len(der) > 0 { der, err = asn1.Unmarshal(der, &d) if err != nil { // Errors should be included in the report, but allow format checking when // data has been decoded. l.e.Err(err.Error()) if len(d.Bytes) == 0 { return } } // A compound is an ASN.1 container that contains other structs. if d.IsCompound { l.walk(d.Bytes) } else { l.CheckFormat(d) } } }
go
func (l *Linter) walk(der []byte) { var err error var d asn1.RawValue for len(der) > 0 { der, err = asn1.Unmarshal(der, &d) if err != nil { // Errors should be included in the report, but allow format checking when // data has been decoded. l.e.Err(err.Error()) if len(d.Bytes) == 0 { return } } // A compound is an ASN.1 container that contains other structs. if d.IsCompound { l.walk(d.Bytes) } else { l.CheckFormat(d) } } }
[ "func", "(", "l", "*", "Linter", ")", "walk", "(", "der", "[", "]", "byte", ")", "{", "var", "err", "error", "\n", "var", "d", "asn1", ".", "RawValue", "\n\n", "for", "len", "(", "der", ")", ">", "0", "{", "der", ",", "err", "=", "asn1", ".", "Unmarshal", "(", "der", ",", "&", "d", ")", "\n", "if", "err", "!=", "nil", "{", "// Errors should be included in the report, but allow format checking when", "// data has been decoded.", "l", ".", "e", ".", "Err", "(", "err", ".", "Error", "(", ")", ")", "\n", "if", "len", "(", "d", ".", "Bytes", ")", "==", "0", "{", "return", "\n", "}", "\n", "}", "\n\n", "// A compound is an ASN.1 container that contains other structs.", "if", "d", ".", "IsCompound", "{", "l", ".", "walk", "(", "d", ".", "Bytes", ")", "\n", "}", "else", "{", "l", ".", "CheckFormat", "(", "d", ")", "\n", "}", "\n", "}", "\n", "}" ]
// walk is a recursive call that walks over the ASN1 structured data until no // remaining bytes are left. For each non compound it will call the ASN1 format // checker.
[ "walk", "is", "a", "recursive", "call", "that", "walks", "over", "the", "ASN1", "structured", "data", "until", "no", "remaining", "bytes", "are", "left", ".", "For", "each", "non", "compound", "it", "will", "call", "the", "ASN1", "format", "checker", "." ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/asn1/asn1.go#L26-L48
12,208
globalsign/certlint
checks/certificate/internal/dnsnames.go
checkInternalName
func checkInternalName(fqdn string) bool { if ip := net.ParseIP(fqdn); ip != nil { return checkInternalIP(ip) } suffix := strings.Split(strings.ToLower(fqdn), ".") _, icann := psl.PublicSuffix(suffix[len(suffix)-1]) if icann { return false } return true }
go
func checkInternalName(fqdn string) bool { if ip := net.ParseIP(fqdn); ip != nil { return checkInternalIP(ip) } suffix := strings.Split(strings.ToLower(fqdn), ".") _, icann := psl.PublicSuffix(suffix[len(suffix)-1]) if icann { return false } return true }
[ "func", "checkInternalName", "(", "fqdn", "string", ")", "bool", "{", "if", "ip", ":=", "net", ".", "ParseIP", "(", "fqdn", ")", ";", "ip", "!=", "nil", "{", "return", "checkInternalIP", "(", "ip", ")", "\n", "}", "\n\n", "suffix", ":=", "strings", ".", "Split", "(", "strings", ".", "ToLower", "(", "fqdn", ")", ",", "\"", "\"", ")", "\n", "_", ",", "icann", ":=", "psl", ".", "PublicSuffix", "(", "suffix", "[", "len", "(", "suffix", ")", "-", "1", "]", ")", "\n", "if", "icann", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// All official domain suffixes are registered by icann, but because some // subdomains are not only check against the last part of the fqdn.
[ "All", "official", "domain", "suffixes", "are", "registered", "by", "icann", "but", "because", "some", "subdomains", "are", "not", "only", "check", "against", "the", "last", "part", "of", "the", "fqdn", "." ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/checks/certificate/internal/dnsnames.go#L12-L23
12,209
globalsign/certlint
certdata/certificate.go
Load
func Load(der []byte) (*Data, error) { var err error d := new(Data) d.Cert, err = x509.ParseCertificate(der) if err != nil { return nil, err } if err = d.setCertificateType(); err != nil { fmt.Println(err) } return d, nil }
go
func Load(der []byte) (*Data, error) { var err error d := new(Data) d.Cert, err = x509.ParseCertificate(der) if err != nil { return nil, err } if err = d.setCertificateType(); err != nil { fmt.Println(err) } return d, nil }
[ "func", "Load", "(", "der", "[", "]", "byte", ")", "(", "*", "Data", ",", "error", ")", "{", "var", "err", "error", "\n\n", "d", ":=", "new", "(", "Data", ")", "\n", "d", ".", "Cert", ",", "err", "=", "x509", ".", "ParseCertificate", "(", "der", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", "=", "d", ".", "setCertificateType", "(", ")", ";", "err", "!=", "nil", "{", "fmt", ".", "Println", "(", "err", ")", "\n", "}", "\n\n", "return", "d", ",", "nil", "\n", "}" ]
// Load raw certificate bytes into a Data struct
[ "Load", "raw", "certificate", "bytes", "into", "a", "Data", "struct" ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/certdata/certificate.go#L17-L31
12,210
globalsign/certlint
errors/errors.go
List
func (e *Errors) List(p ...Priority) []Err { if len(p) == 0 { return e.err } // filter errors to given priorities var l []Err for _, e := range e.err { for _, priority := range p { if e.p == priority { l = append(l, e) } } } return l }
go
func (e *Errors) List(p ...Priority) []Err { if len(p) == 0 { return e.err } // filter errors to given priorities var l []Err for _, e := range e.err { for _, priority := range p { if e.p == priority { l = append(l, e) } } } return l }
[ "func", "(", "e", "*", "Errors", ")", "List", "(", "p", "...", "Priority", ")", "[", "]", "Err", "{", "if", "len", "(", "p", ")", "==", "0", "{", "return", "e", ".", "err", "\n", "}", "\n\n", "// filter errors to given priorities", "var", "l", "[", "]", "Err", "\n", "for", "_", ",", "e", ":=", "range", "e", ".", "err", "{", "for", "_", ",", "priority", ":=", "range", "p", "{", "if", "e", ".", "p", "==", "priority", "{", "l", "=", "append", "(", "l", ",", "e", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "l", "\n", "}" ]
// List returns all errors of a given priority, if no priority is given all // errors are returned.
[ "List", "returns", "all", "errors", "of", "a", "given", "priority", "if", "no", "priority", "is", "given", "all", "errors", "are", "returned", "." ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/errors/errors.go#L75-L90
12,211
globalsign/certlint
errors/errors.go
Append
func (e *Errors) Append(err *Errors) error { if err == nil { return nil } e.m.Lock() // append Errors at the end of the current list e.err = append(e.err, err.err...) // set highest priority if err.p > e.p { e.p = err.p } e.m.Unlock() return nil }
go
func (e *Errors) Append(err *Errors) error { if err == nil { return nil } e.m.Lock() // append Errors at the end of the current list e.err = append(e.err, err.err...) // set highest priority if err.p > e.p { e.p = err.p } e.m.Unlock() return nil }
[ "func", "(", "e", "*", "Errors", ")", "Append", "(", "err", "*", "Errors", ")", "error", "{", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "e", ".", "m", ".", "Lock", "(", ")", "\n\n", "// append Errors at the end of the current list", "e", ".", "err", "=", "append", "(", "e", ".", "err", ",", "err", ".", "err", "...", ")", "\n\n", "// set highest priority", "if", "err", ".", "p", ">", "e", ".", "p", "{", "e", ".", "p", "=", "err", ".", "p", "\n", "}", "\n\n", "e", ".", "m", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Append add all Errors to existing Errors
[ "Append", "add", "all", "Errors", "to", "existing", "Errors" ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/errors/errors.go#L93-L110
12,212
globalsign/certlint
errors/errors.go
Emerg
func (e *Errors) Emerg(format string, a ...interface{}) error { return e.add(Emergency, format, a...) }
go
func (e *Errors) Emerg(format string, a ...interface{}) error { return e.add(Emergency, format, a...) }
[ "func", "(", "e", "*", "Errors", ")", "Emerg", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "error", "{", "return", "e", ".", "add", "(", "Emergency", ",", "format", ",", "a", "...", ")", "\n", "}" ]
// Emerg log an error with severity Emergency
[ "Emerg", "log", "an", "error", "with", "severity", "Emergency" ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/errors/errors.go#L113-L115
12,213
globalsign/certlint
errors/errors.go
Alert
func (e *Errors) Alert(format string, a ...interface{}) error { return e.add(Alert, format, a...) }
go
func (e *Errors) Alert(format string, a ...interface{}) error { return e.add(Alert, format, a...) }
[ "func", "(", "e", "*", "Errors", ")", "Alert", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "error", "{", "return", "e", ".", "add", "(", "Alert", ",", "format", ",", "a", "...", ")", "\n", "}" ]
// Alert log an error with severity Alert
[ "Alert", "log", "an", "error", "with", "severity", "Alert" ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/errors/errors.go#L118-L120
12,214
globalsign/certlint
errors/errors.go
Crit
func (e *Errors) Crit(format string, a ...interface{}) error { return e.add(Critical, format, a...) }
go
func (e *Errors) Crit(format string, a ...interface{}) error { return e.add(Critical, format, a...) }
[ "func", "(", "e", "*", "Errors", ")", "Crit", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "error", "{", "return", "e", ".", "add", "(", "Critical", ",", "format", ",", "a", "...", ")", "\n", "}" ]
// Crit log an error with severity Critical
[ "Crit", "log", "an", "error", "with", "severity", "Critical" ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/errors/errors.go#L123-L125
12,215
globalsign/certlint
errors/errors.go
Err
func (e *Errors) Err(format string, a ...interface{}) error { return e.add(Error, format, a...) }
go
func (e *Errors) Err(format string, a ...interface{}) error { return e.add(Error, format, a...) }
[ "func", "(", "e", "*", "Errors", ")", "Err", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "error", "{", "return", "e", ".", "add", "(", "Error", ",", "format", ",", "a", "...", ")", "\n", "}" ]
// Err log an error with severity Error
[ "Err", "log", "an", "error", "with", "severity", "Error" ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/errors/errors.go#L128-L130
12,216
globalsign/certlint
errors/errors.go
Warning
func (e *Errors) Warning(format string, a ...interface{}) error { return e.add(Warning, format, a...) }
go
func (e *Errors) Warning(format string, a ...interface{}) error { return e.add(Warning, format, a...) }
[ "func", "(", "e", "*", "Errors", ")", "Warning", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "error", "{", "return", "e", ".", "add", "(", "Warning", ",", "format", ",", "a", "...", ")", "\n", "}" ]
// Warning log an error with severity Warning
[ "Warning", "log", "an", "error", "with", "severity", "Warning" ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/errors/errors.go#L133-L135
12,217
globalsign/certlint
errors/errors.go
Notice
func (e *Errors) Notice(format string, a ...interface{}) error { return e.add(Notice, format, a...) }
go
func (e *Errors) Notice(format string, a ...interface{}) error { return e.add(Notice, format, a...) }
[ "func", "(", "e", "*", "Errors", ")", "Notice", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "error", "{", "return", "e", ".", "add", "(", "Notice", ",", "format", ",", "a", "...", ")", "\n", "}" ]
// Notice log an error with severity Notice
[ "Notice", "log", "an", "error", "with", "severity", "Notice" ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/errors/errors.go#L138-L140
12,218
globalsign/certlint
errors/errors.go
Info
func (e *Errors) Info(format string, a ...interface{}) error { return e.add(Info, format, a...) }
go
func (e *Errors) Info(format string, a ...interface{}) error { return e.add(Info, format, a...) }
[ "func", "(", "e", "*", "Errors", ")", "Info", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "error", "{", "return", "e", ".", "add", "(", "Info", ",", "format", ",", "a", "...", ")", "\n", "}" ]
// Info log an error with severity Info
[ "Info", "log", "an", "error", "with", "severity", "Info" ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/errors/errors.go#L143-L145
12,219
globalsign/certlint
errors/errors.go
Debug
func (e *Errors) Debug(format string, a ...interface{}) error { return e.add(Debug, format, a...) }
go
func (e *Errors) Debug(format string, a ...interface{}) error { return e.add(Debug, format, a...) }
[ "func", "(", "e", "*", "Errors", ")", "Debug", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "error", "{", "return", "e", ".", "add", "(", "Debug", ",", "format", ",", "a", "...", ")", "\n", "}" ]
// Debug log an error with severity Debug
[ "Debug", "log", "an", "error", "with", "severity", "Debug" ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/errors/errors.go#L148-L150
12,220
globalsign/certlint
asn1/format.go
isNumericString
func isNumericString(b []byte) bool { for len(b) > 0 { r, size := utf8.DecodeRune(b) if !unicode.IsNumber(r) && !unicode.IsSpace(r) { return false } b = b[size:] } return true }
go
func isNumericString(b []byte) bool { for len(b) > 0 { r, size := utf8.DecodeRune(b) if !unicode.IsNumber(r) && !unicode.IsSpace(r) { return false } b = b[size:] } return true }
[ "func", "isNumericString", "(", "b", "[", "]", "byte", ")", "bool", "{", "for", "len", "(", "b", ")", ">", "0", "{", "r", ",", "size", ":=", "utf8", ".", "DecodeRune", "(", "b", ")", "\n", "if", "!", "unicode", ".", "IsNumber", "(", "r", ")", "&&", "!", "unicode", ".", "IsSpace", "(", "r", ")", "{", "return", "false", "\n", "}", "\n", "b", "=", "b", "[", "size", ":", "]", "\n", "}", "\n", "return", "true", "\n", "}" ]
// 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, and SPACE
[ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "and", "SPACE" ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/asn1/format.go#L179-L188
12,221
globalsign/certlint
asn1/format.go
isForbiddenString
func isForbiddenString(b []byte) bool { for len(b) == 0 { return false } switch strings.ToLower(string(b)) { case "n/a": return true } for len(b) > 0 { r, size := utf8.DecodeRune(b) if !((r >= 32 && r <= 47) || (r >= 58 && r <= 64) || (r >= 91 && r <= 96) || (r >= 123 && r <= 126)) { // non metadata character included in value return false } b = b[size:] } return true }
go
func isForbiddenString(b []byte) bool { for len(b) == 0 { return false } switch strings.ToLower(string(b)) { case "n/a": return true } for len(b) > 0 { r, size := utf8.DecodeRune(b) if !((r >= 32 && r <= 47) || (r >= 58 && r <= 64) || (r >= 91 && r <= 96) || (r >= 123 && r <= 126)) { // non metadata character included in value return false } b = b[size:] } return true }
[ "func", "isForbiddenString", "(", "b", "[", "]", "byte", ")", "bool", "{", "for", "len", "(", "b", ")", "==", "0", "{", "return", "false", "\n", "}", "\n\n", "switch", "strings", ".", "ToLower", "(", "string", "(", "b", ")", ")", "{", "case", "\"", "\"", ":", "return", "true", "\n", "}", "\n\n", "for", "len", "(", "b", ")", ">", "0", "{", "r", ",", "size", ":=", "utf8", ".", "DecodeRune", "(", "b", ")", "\n", "if", "!", "(", "(", "r", ">=", "32", "&&", "r", "<=", "47", ")", "||", "(", "r", ">=", "58", "&&", "r", "<=", "64", ")", "||", "(", "r", ">=", "91", "&&", "r", "<=", "96", ")", "||", "(", "r", ">=", "123", "&&", "r", "<=", "126", ")", ")", "{", "// non metadata character included in value", "return", "false", "\n", "}", "\n", "b", "=", "b", "[", "size", ":", "]", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// The BR state that attributes MUST NOT contain metadata such as '.', '-', ' ', // this check implements a structure wide validation for values that indication // that the field is absent, incomplete, or not applicable. // // ASCII range of forbidden metadata characters are 32 - 47, 58 -64, 91 - 96, // 123 - 126, if the value does only contain metadata this value is forbidden. // This check does also detect double characters or any combination of metadata // characters.
[ "The", "BR", "state", "that", "attributes", "MUST", "NOT", "contain", "metadata", "such", "as", ".", "-", "this", "check", "implements", "a", "structure", "wide", "validation", "for", "values", "that", "indication", "that", "the", "field", "is", "absent", "incomplete", "or", "not", "applicable", ".", "ASCII", "range", "of", "forbidden", "metadata", "characters", "are", "32", "-", "47", "58", "-", "64", "91", "-", "96", "123", "-", "126", "if", "the", "value", "does", "only", "contain", "metadata", "this", "value", "is", "forbidden", ".", "This", "check", "does", "also", "detect", "double", "characters", "or", "any", "combination", "of", "metadata", "characters", "." ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/asn1/format.go#L198-L221
12,222
globalsign/certlint
asn1/format.go
isControlCharacter
func isControlCharacter(b []byte) bool { for len(b) > 0 { r, size := utf8.DecodeRune(b) if unicode.IsControl(r) || unicode.Is(unicode.C, r) { return true } b = b[size:] } return false }
go
func isControlCharacter(b []byte) bool { for len(b) > 0 { r, size := utf8.DecodeRune(b) if unicode.IsControl(r) || unicode.Is(unicode.C, r) { return true } b = b[size:] } return false }
[ "func", "isControlCharacter", "(", "b", "[", "]", "byte", ")", "bool", "{", "for", "len", "(", "b", ")", ">", "0", "{", "r", ",", "size", ":=", "utf8", ".", "DecodeRune", "(", "b", ")", "\n", "if", "unicode", ".", "IsControl", "(", "r", ")", "||", "unicode", ".", "Is", "(", "unicode", ".", "C", ",", "r", ")", "{", "return", "true", "\n", "}", "\n", "b", "=", "b", "[", "size", ":", "]", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isControlCharacter checks if Control characters are included in the given bytes
[ "isControlCharacter", "checks", "if", "Control", "characters", "are", "included", "in", "the", "given", "bytes" ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/asn1/format.go#L224-L233
12,223
globalsign/certlint
checks/certificate/keyusage/keyusagestring.go
keyUsageString
func keyUsageString(ku x509.KeyUsage) string { switch ku { case x509.KeyUsageDigitalSignature: return "DigitalSignature" case x509.KeyUsageContentCommitment: return "ContentCommitment" case x509.KeyUsageKeyEncipherment: return "KeyEncipherment" case x509.KeyUsageDataEncipherment: return "DataEncipherment" case x509.KeyUsageKeyAgreement: return "KeyAgreement" case x509.KeyUsageCertSign: return "CertSign" case x509.KeyUsageCRLSign: return "CRLSign" case x509.KeyUsageEncipherOnly: return "EncipherOnly" case x509.KeyUsageDecipherOnly: return "DecipherOnly" } return "Unknown" }
go
func keyUsageString(ku x509.KeyUsage) string { switch ku { case x509.KeyUsageDigitalSignature: return "DigitalSignature" case x509.KeyUsageContentCommitment: return "ContentCommitment" case x509.KeyUsageKeyEncipherment: return "KeyEncipherment" case x509.KeyUsageDataEncipherment: return "DataEncipherment" case x509.KeyUsageKeyAgreement: return "KeyAgreement" case x509.KeyUsageCertSign: return "CertSign" case x509.KeyUsageCRLSign: return "CRLSign" case x509.KeyUsageEncipherOnly: return "EncipherOnly" case x509.KeyUsageDecipherOnly: return "DecipherOnly" } return "Unknown" }
[ "func", "keyUsageString", "(", "ku", "x509", ".", "KeyUsage", ")", "string", "{", "switch", "ku", "{", "case", "x509", ".", "KeyUsageDigitalSignature", ":", "return", "\"", "\"", "\n", "case", "x509", ".", "KeyUsageContentCommitment", ":", "return", "\"", "\"", "\n", "case", "x509", ".", "KeyUsageKeyEncipherment", ":", "return", "\"", "\"", "\n", "case", "x509", ".", "KeyUsageDataEncipherment", ":", "return", "\"", "\"", "\n", "case", "x509", ".", "KeyUsageKeyAgreement", ":", "return", "\"", "\"", "\n", "case", "x509", ".", "KeyUsageCertSign", ":", "return", "\"", "\"", "\n", "case", "x509", ".", "KeyUsageCRLSign", ":", "return", "\"", "\"", "\n", "case", "x509", ".", "KeyUsageEncipherOnly", ":", "return", "\"", "\"", "\n", "case", "x509", ".", "KeyUsageDecipherOnly", ":", "return", "\"", "\"", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// keyUsageString returns the name of the keyusage as string
[ "keyUsageString", "returns", "the", "name", "of", "the", "keyusage", "as", "string" ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/checks/certificate/keyusage/keyusagestring.go#L6-L28
12,224
globalsign/certlint
certdata/type.go
setCertificateType
func (d *Data) setCertificateType() error { // We want to be able to detect 'false' CA certificates, classify as CA // certificate is basic contains and key usage certsign are set. if d.Cert.IsCA && d.Cert.KeyUsage&x509.KeyUsageCertSign != 0 { d.Type = "CA" return nil } // The fallback type is used when a certificate could be any of a range // but further checks need to define the exact type. When these checks fail // the fallback type is used. var fallbackType string // Based on ExtKeyUsage for _, ku := range d.Cert.ExtKeyUsage { switch ku { case x509.ExtKeyUsageServerAuth: // Try to determine certificate type via policy oid d.Type = getType(d.Cert.PolicyIdentifiers) fallbackType = "DV" case x509.ExtKeyUsageClientAuth: fallbackType = "PS" case x509.ExtKeyUsageEmailProtection: d.Type = "PS" case x509.ExtKeyUsageCodeSigning: d.Type = "CS" case x509.ExtKeyUsageTimeStamping: d.Type = "TS" case x509.ExtKeyUsageOCSPSigning: d.Type = "OCSP" } } // If we have no known key usage, try the policy list again if d.Type == "" { d.Type = getType(d.Cert.PolicyIdentifiers) } // When determined by Policy Identifier we can stop if d.Type != "" { return nil } // Based on UnknownExtKeyUsage for _, ku := range d.Cert.UnknownExtKeyUsage { switch { case ku.Equal(asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 21, 19}): // dsEmailReplication d.Type = "PS" return nil case ku.Equal(asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 8, 2, 2}): // IPSEC Protection d.Type = "IPSEC" return nil } } // Check if the e-mailAddress is set in the DN for _, n := range d.Cert.Subject.Names { switch { case n.Type.Equal(asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 1}): // e-mailAddress d.Type = "PS" return nil } } // An @ sing in the common name is often used in PS. if strings.Contains(d.Cert.Subject.CommonName, "@") { d.Type = "PS" return nil } else if strings.Contains(d.Cert.Subject.CommonName, " ") { d.Type = "PS" return nil } // If it's a fqdn, it's a EV, OV or DV if suffix, _ := psl.PublicSuffix(strings.ToLower(d.Cert.Subject.CommonName)); len(suffix) > 0 { if len(d.Cert.Subject.Organization) > 0 { if len(d.Cert.Subject.SerialNumber) > 0 { d.Type = "EV" return nil } d.Type = "OV" return nil } d.Type = "DV" return nil } if len(fallbackType) > 0 { d.Type = fallbackType return nil } if d.Type == "" { return fmt.Errorf("Could not determine certificate type") } return nil }
go
func (d *Data) setCertificateType() error { // We want to be able to detect 'false' CA certificates, classify as CA // certificate is basic contains and key usage certsign are set. if d.Cert.IsCA && d.Cert.KeyUsage&x509.KeyUsageCertSign != 0 { d.Type = "CA" return nil } // The fallback type is used when a certificate could be any of a range // but further checks need to define the exact type. When these checks fail // the fallback type is used. var fallbackType string // Based on ExtKeyUsage for _, ku := range d.Cert.ExtKeyUsage { switch ku { case x509.ExtKeyUsageServerAuth: // Try to determine certificate type via policy oid d.Type = getType(d.Cert.PolicyIdentifiers) fallbackType = "DV" case x509.ExtKeyUsageClientAuth: fallbackType = "PS" case x509.ExtKeyUsageEmailProtection: d.Type = "PS" case x509.ExtKeyUsageCodeSigning: d.Type = "CS" case x509.ExtKeyUsageTimeStamping: d.Type = "TS" case x509.ExtKeyUsageOCSPSigning: d.Type = "OCSP" } } // If we have no known key usage, try the policy list again if d.Type == "" { d.Type = getType(d.Cert.PolicyIdentifiers) } // When determined by Policy Identifier we can stop if d.Type != "" { return nil } // Based on UnknownExtKeyUsage for _, ku := range d.Cert.UnknownExtKeyUsage { switch { case ku.Equal(asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 21, 19}): // dsEmailReplication d.Type = "PS" return nil case ku.Equal(asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 8, 2, 2}): // IPSEC Protection d.Type = "IPSEC" return nil } } // Check if the e-mailAddress is set in the DN for _, n := range d.Cert.Subject.Names { switch { case n.Type.Equal(asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 1}): // e-mailAddress d.Type = "PS" return nil } } // An @ sing in the common name is often used in PS. if strings.Contains(d.Cert.Subject.CommonName, "@") { d.Type = "PS" return nil } else if strings.Contains(d.Cert.Subject.CommonName, " ") { d.Type = "PS" return nil } // If it's a fqdn, it's a EV, OV or DV if suffix, _ := psl.PublicSuffix(strings.ToLower(d.Cert.Subject.CommonName)); len(suffix) > 0 { if len(d.Cert.Subject.Organization) > 0 { if len(d.Cert.Subject.SerialNumber) > 0 { d.Type = "EV" return nil } d.Type = "OV" return nil } d.Type = "DV" return nil } if len(fallbackType) > 0 { d.Type = fallbackType return nil } if d.Type == "" { return fmt.Errorf("Could not determine certificate type") } return nil }
[ "func", "(", "d", "*", "Data", ")", "setCertificateType", "(", ")", "error", "{", "// We want to be able to detect 'false' CA certificates, classify as CA", "// certificate is basic contains and key usage certsign are set.", "if", "d", ".", "Cert", ".", "IsCA", "&&", "d", ".", "Cert", ".", "KeyUsage", "&", "x509", ".", "KeyUsageCertSign", "!=", "0", "{", "d", ".", "Type", "=", "\"", "\"", "\n", "return", "nil", "\n", "}", "\n\n", "// The fallback type is used when a certificate could be any of a range", "// but further checks need to define the exact type. When these checks fail", "// the fallback type is used.", "var", "fallbackType", "string", "\n\n", "// Based on ExtKeyUsage", "for", "_", ",", "ku", ":=", "range", "d", ".", "Cert", ".", "ExtKeyUsage", "{", "switch", "ku", "{", "case", "x509", ".", "ExtKeyUsageServerAuth", ":", "// Try to determine certificate type via policy oid", "d", ".", "Type", "=", "getType", "(", "d", ".", "Cert", ".", "PolicyIdentifiers", ")", "\n", "fallbackType", "=", "\"", "\"", "\n", "case", "x509", ".", "ExtKeyUsageClientAuth", ":", "fallbackType", "=", "\"", "\"", "\n", "case", "x509", ".", "ExtKeyUsageEmailProtection", ":", "d", ".", "Type", "=", "\"", "\"", "\n", "case", "x509", ".", "ExtKeyUsageCodeSigning", ":", "d", ".", "Type", "=", "\"", "\"", "\n", "case", "x509", ".", "ExtKeyUsageTimeStamping", ":", "d", ".", "Type", "=", "\"", "\"", "\n", "case", "x509", ".", "ExtKeyUsageOCSPSigning", ":", "d", ".", "Type", "=", "\"", "\"", "\n", "}", "\n", "}", "\n\n", "// If we have no known key usage, try the policy list again", "if", "d", ".", "Type", "==", "\"", "\"", "{", "d", ".", "Type", "=", "getType", "(", "d", ".", "Cert", ".", "PolicyIdentifiers", ")", "\n", "}", "\n\n", "// When determined by Policy Identifier we can stop", "if", "d", ".", "Type", "!=", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "// Based on UnknownExtKeyUsage", "for", "_", ",", "ku", ":=", "range", "d", ".", "Cert", ".", "UnknownExtKeyUsage", "{", "switch", "{", "case", "ku", ".", "Equal", "(", "asn1", ".", "ObjectIdentifier", "{", "1", ",", "3", ",", "6", ",", "1", ",", "4", ",", "1", ",", "311", ",", "21", ",", "19", "}", ")", ":", "// dsEmailReplication", "d", ".", "Type", "=", "\"", "\"", "\n", "return", "nil", "\n", "case", "ku", ".", "Equal", "(", "asn1", ".", "ObjectIdentifier", "{", "1", ",", "3", ",", "6", ",", "1", ",", "5", ",", "5", ",", "8", ",", "2", ",", "2", "}", ")", ":", "// IPSEC Protection", "d", ".", "Type", "=", "\"", "\"", "\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "// Check if the e-mailAddress is set in the DN", "for", "_", ",", "n", ":=", "range", "d", ".", "Cert", ".", "Subject", ".", "Names", "{", "switch", "{", "case", "n", ".", "Type", ".", "Equal", "(", "asn1", ".", "ObjectIdentifier", "{", "1", ",", "2", ",", "840", ",", "113549", ",", "1", ",", "9", ",", "1", "}", ")", ":", "// e-mailAddress", "d", ".", "Type", "=", "\"", "\"", "\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "// An @ sing in the common name is often used in PS.", "if", "strings", ".", "Contains", "(", "d", ".", "Cert", ".", "Subject", ".", "CommonName", ",", "\"", "\"", ")", "{", "d", ".", "Type", "=", "\"", "\"", "\n", "return", "nil", "\n", "}", "else", "if", "strings", ".", "Contains", "(", "d", ".", "Cert", ".", "Subject", ".", "CommonName", ",", "\"", "\"", ")", "{", "d", ".", "Type", "=", "\"", "\"", "\n", "return", "nil", "\n", "}", "\n\n", "// If it's a fqdn, it's a EV, OV or DV", "if", "suffix", ",", "_", ":=", "psl", ".", "PublicSuffix", "(", "strings", ".", "ToLower", "(", "d", ".", "Cert", ".", "Subject", ".", "CommonName", ")", ")", ";", "len", "(", "suffix", ")", ">", "0", "{", "if", "len", "(", "d", ".", "Cert", ".", "Subject", ".", "Organization", ")", ">", "0", "{", "if", "len", "(", "d", ".", "Cert", ".", "Subject", ".", "SerialNumber", ")", ">", "0", "{", "d", ".", "Type", "=", "\"", "\"", "\n", "return", "nil", "\n", "}", "\n\n", "d", ".", "Type", "=", "\"", "\"", "\n", "return", "nil", "\n", "}", "\n\n", "d", ".", "Type", "=", "\"", "\"", "\n", "return", "nil", "\n", "}", "\n\n", "if", "len", "(", "fallbackType", ")", ">", "0", "{", "d", ".", "Type", "=", "fallbackType", "\n", "return", "nil", "\n", "}", "\n\n", "if", "d", ".", "Type", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// setCertificateType set the base on how we check for other requirements of the // certificate. It's important that we reliably identify the purpose to apply // the right checks for that certificate type.
[ "setCertificateType", "set", "the", "base", "on", "how", "we", "check", "for", "other", "requirements", "of", "the", "certificate", ".", "It", "s", "important", "that", "we", "reliably", "identify", "the", "purpose", "to", "apply", "the", "right", "checks", "for", "that", "certificate", "type", "." ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/certdata/type.go#L15-L115
12,225
globalsign/certlint
checks/filter.go
Check
func (f *Filter) Check(d *certdata.Data) bool { // Is certificate recognised as one of the given types if len(f.Type) > 0 { var inFilter bool for _, t := range f.Type { if d.Type == t { inFilter = true } } if !inFilter { return false } } // Issued before given date if f.IssuedBefore != nil && !d.Cert.NotBefore.Before(*f.IssuedBefore) { return false } // Issued after given date if f.IssuedAfter != nil && !d.Cert.NotBefore.After(*f.IssuedAfter) { return false } // Expires before given date if f.ExpiresBefore != nil && !d.Cert.NotBefore.Before(*f.ExpiresBefore) { return false } // Expires after given date if f.ExpiresAfter != nil && !d.Cert.NotAfter.After(*f.ExpiresAfter) { return false } return true }
go
func (f *Filter) Check(d *certdata.Data) bool { // Is certificate recognised as one of the given types if len(f.Type) > 0 { var inFilter bool for _, t := range f.Type { if d.Type == t { inFilter = true } } if !inFilter { return false } } // Issued before given date if f.IssuedBefore != nil && !d.Cert.NotBefore.Before(*f.IssuedBefore) { return false } // Issued after given date if f.IssuedAfter != nil && !d.Cert.NotBefore.After(*f.IssuedAfter) { return false } // Expires before given date if f.ExpiresBefore != nil && !d.Cert.NotBefore.Before(*f.ExpiresBefore) { return false } // Expires after given date if f.ExpiresAfter != nil && !d.Cert.NotAfter.After(*f.ExpiresAfter) { return false } return true }
[ "func", "(", "f", "*", "Filter", ")", "Check", "(", "d", "*", "certdata", ".", "Data", ")", "bool", "{", "// Is certificate recognised as one of the given types", "if", "len", "(", "f", ".", "Type", ")", ">", "0", "{", "var", "inFilter", "bool", "\n", "for", "_", ",", "t", ":=", "range", "f", ".", "Type", "{", "if", "d", ".", "Type", "==", "t", "{", "inFilter", "=", "true", "\n", "}", "\n", "}", "\n", "if", "!", "inFilter", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "// Issued before given date", "if", "f", ".", "IssuedBefore", "!=", "nil", "&&", "!", "d", ".", "Cert", ".", "NotBefore", ".", "Before", "(", "*", "f", ".", "IssuedBefore", ")", "{", "return", "false", "\n", "}", "\n", "// Issued after given date", "if", "f", ".", "IssuedAfter", "!=", "nil", "&&", "!", "d", ".", "Cert", ".", "NotBefore", ".", "After", "(", "*", "f", ".", "IssuedAfter", ")", "{", "return", "false", "\n", "}", "\n", "// Expires before given date", "if", "f", ".", "ExpiresBefore", "!=", "nil", "&&", "!", "d", ".", "Cert", ".", "NotBefore", ".", "Before", "(", "*", "f", ".", "ExpiresBefore", ")", "{", "return", "false", "\n", "}", "\n", "// Expires after given date", "if", "f", ".", "ExpiresAfter", "!=", "nil", "&&", "!", "d", ".", "Cert", ".", "NotAfter", ".", "After", "(", "*", "f", ".", "ExpiresAfter", ")", "{", "return", "false", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// Check returns true if a certificate complies with the given filter
[ "Check", "returns", "true", "if", "a", "certificate", "complies", "with", "the", "given", "filter" ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/checks/filter.go#L19-L51
12,226
globalsign/certlint
checks/extensions.go
RegisterExtensionCheck
func RegisterExtensionCheck(name string, oid asn1.ObjectIdentifier, filter *Filter, f func(pkix.Extension, *certdata.Data) *errors.Errors) { extMutex.Lock() Extensions = append(Extensions, extensionCheck{name, oid, filter, f}) extMutex.Unlock() }
go
func RegisterExtensionCheck(name string, oid asn1.ObjectIdentifier, filter *Filter, f func(pkix.Extension, *certdata.Data) *errors.Errors) { extMutex.Lock() Extensions = append(Extensions, extensionCheck{name, oid, filter, f}) extMutex.Unlock() }
[ "func", "RegisterExtensionCheck", "(", "name", "string", ",", "oid", "asn1", ".", "ObjectIdentifier", ",", "filter", "*", "Filter", ",", "f", "func", "(", "pkix", ".", "Extension", ",", "*", "certdata", ".", "Data", ")", "*", "errors", ".", "Errors", ")", "{", "extMutex", ".", "Lock", "(", ")", "\n", "Extensions", "=", "append", "(", "Extensions", ",", "extensionCheck", "{", "name", ",", "oid", ",", "filter", ",", "f", "}", ")", "\n", "extMutex", ".", "Unlock", "(", ")", "\n", "}" ]
// RegisterExtensionCheck adds a new check to Extensions
[ "RegisterExtensionCheck", "adds", "a", "new", "check", "to", "Extensions" ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/checks/extensions.go#L28-L32
12,227
globalsign/certlint
checks/extensions.go
Check
func (ex extensions) Check(ext pkix.Extension, d *certdata.Data) *errors.Errors { var e = errors.New(nil) var found bool for _, ec := range ex { if ec.oid.Equal(ext.Id) { found = true if ec.filter != nil && ec.filter.Check(d) { continue } e.Append(ec.f(ext, d)) } } if !found { // Don't report private enterprise extensions as unknown, registered private // extensions have still been checked above. if !strings.HasPrefix(ext.Id.String(), "1.3.6.1.4.1.") { e.Warning("Certificate contains unknown extension (%s)", ext.Id.String()) } } return e }
go
func (ex extensions) Check(ext pkix.Extension, d *certdata.Data) *errors.Errors { var e = errors.New(nil) var found bool for _, ec := range ex { if ec.oid.Equal(ext.Id) { found = true if ec.filter != nil && ec.filter.Check(d) { continue } e.Append(ec.f(ext, d)) } } if !found { // Don't report private enterprise extensions as unknown, registered private // extensions have still been checked above. if !strings.HasPrefix(ext.Id.String(), "1.3.6.1.4.1.") { e.Warning("Certificate contains unknown extension (%s)", ext.Id.String()) } } return e }
[ "func", "(", "ex", "extensions", ")", "Check", "(", "ext", "pkix", ".", "Extension", ",", "d", "*", "certdata", ".", "Data", ")", "*", "errors", ".", "Errors", "{", "var", "e", "=", "errors", ".", "New", "(", "nil", ")", "\n", "var", "found", "bool", "\n\n", "for", "_", ",", "ec", ":=", "range", "ex", "{", "if", "ec", ".", "oid", ".", "Equal", "(", "ext", ".", "Id", ")", "{", "found", "=", "true", "\n", "if", "ec", ".", "filter", "!=", "nil", "&&", "ec", ".", "filter", ".", "Check", "(", "d", ")", "{", "continue", "\n", "}", "\n", "e", ".", "Append", "(", "ec", ".", "f", "(", "ext", ",", "d", ")", ")", "\n", "}", "\n", "}", "\n\n", "if", "!", "found", "{", "// Don't report private enterprise extensions as unknown, registered private", "// extensions have still been checked above.", "if", "!", "strings", ".", "HasPrefix", "(", "ext", ".", "Id", ".", "String", "(", ")", ",", "\"", "\"", ")", "{", "e", ".", "Warning", "(", "\"", "\"", ",", "ext", ".", "Id", ".", "String", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "e", "\n", "}" ]
// Check lookups the registered extension checks and runs all checks with the // same Object Identifier.
[ "Check", "lookups", "the", "registered", "extension", "checks", "and", "runs", "all", "checks", "with", "the", "same", "Object", "Identifier", "." ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/checks/extensions.go#L36-L59
12,228
globalsign/certlint
checks/certificate/publickey/goodkey/goodkey.go
goodKeyECDSA
func (policy *KeyPolicy) goodKeyECDSA(key ecdsa.PublicKey) (err error) { // Check the curve. // // The validity of the curve is an assumption for all following tests. err = policy.goodCurve(key.Curve) if err != nil { return err } // Key validation routine adapted from NIST SP800-56A § 5.6.2.3.2. // <http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar2.pdf> // // Assuming a prime field since a) we are only allowing such curves and b) // crypto/elliptic only supports prime curves. Where this assumption // simplifies the code below, it is explicitly stated and explained. If ever // adapting this code to support non-prime curves, refer to NIST SP800-56A § // 5.6.2.3.2 and adapt this code appropriately. params := key.Params() // SP800-56A § 5.6.2.3.2 Step 1. // Partial check of the public key for an invalid range in the EC group: // Verify that key is not the point at infinity O. // This code assumes that the point at infinity is (0,0), which is the // case for all supported curves. if isPointAtInfinityNISTP(key.X, key.Y) { return fmt.Errorf("Key x, y must not be the point at infinity") } // SP800-56A § 5.6.2.3.2 Step 2. // "Verify that x_Q and y_Q are integers in the interval [0,p-1] in the // case that q is an odd prime p, or that x_Q and y_Q are bit strings // of length m bits in the case that q = 2**m." // // Prove prime field: ASSUMED. // Prove q != 2: ASSUMED. (Curve parameter. No supported curve has q == 2.) // Prime field && q != 2 => q is an odd prime p // Therefore "verify that x, y are in [0, p-1]" satisfies step 2. // // Therefore verify that both x and y of the public key point have the unique // correct representation of an element in the underlying field by verifying // that x and y are integers in [0, p-1]. if key.X.Sign() < 0 || key.Y.Sign() < 0 { return fmt.Errorf("Key x, y must not be negative") } if key.X.Cmp(params.P) >= 0 || key.Y.Cmp(params.P) >= 0 { return fmt.Errorf("Key x, y must not exceed P-1") } // SP800-56A § 5.6.2.3.2 Step 3. // "If q is an odd prime p, verify that (y_Q)**2 === (x_Q)***3 + a*x_Q + b (mod p). // If q = 2**m, verify that (y_Q)**2 + (x_Q)*(y_Q) == (x_Q)**3 + a*(x_Q)*2 + b in // the finite field of size 2**m. // (Ensures that the public key is on the correct elliptic curve.)" // // q is an odd prime p: proven/assumed above. // a = -3 for all supported curves. // // Therefore step 3 is satisfied simply by showing that // y**2 === x**3 - 3*x + B (mod P). // // This proves that the public key is on the correct elliptic curve. // But in practice, this test is provided by crypto/elliptic, so use that. if !key.Curve.IsOnCurve(key.X, key.Y) { return fmt.Errorf("Key point is not on the curve") } // SP800-56A § 5.6.2.3.2 Step 4. // "Verify that n*Q == O. // (Ensures that the public key has the correct order. Along with check 1, // ensures that the public key is in the correct range in the correct EC // subgroup, that is, it is in the correct EC subgroup and is not the // identity element.)" // // Ensure that public key has the correct order: // verify that n*Q = O. // // n*Q = O iff n*Q is the point at infinity (see step 1). ox, oy := key.Curve.ScalarMult(key.X, key.Y, params.N.Bytes()) if !isPointAtInfinityNISTP(ox, oy) { return fmt.Errorf("Public key does not have correct order") } // End of SP800-56A § 5.6.2.3.2 Public Key Validation Routine. // Key is valid. return nil }
go
func (policy *KeyPolicy) goodKeyECDSA(key ecdsa.PublicKey) (err error) { // Check the curve. // // The validity of the curve is an assumption for all following tests. err = policy.goodCurve(key.Curve) if err != nil { return err } // Key validation routine adapted from NIST SP800-56A § 5.6.2.3.2. // <http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar2.pdf> // // Assuming a prime field since a) we are only allowing such curves and b) // crypto/elliptic only supports prime curves. Where this assumption // simplifies the code below, it is explicitly stated and explained. If ever // adapting this code to support non-prime curves, refer to NIST SP800-56A § // 5.6.2.3.2 and adapt this code appropriately. params := key.Params() // SP800-56A § 5.6.2.3.2 Step 1. // Partial check of the public key for an invalid range in the EC group: // Verify that key is not the point at infinity O. // This code assumes that the point at infinity is (0,0), which is the // case for all supported curves. if isPointAtInfinityNISTP(key.X, key.Y) { return fmt.Errorf("Key x, y must not be the point at infinity") } // SP800-56A § 5.6.2.3.2 Step 2. // "Verify that x_Q and y_Q are integers in the interval [0,p-1] in the // case that q is an odd prime p, or that x_Q and y_Q are bit strings // of length m bits in the case that q = 2**m." // // Prove prime field: ASSUMED. // Prove q != 2: ASSUMED. (Curve parameter. No supported curve has q == 2.) // Prime field && q != 2 => q is an odd prime p // Therefore "verify that x, y are in [0, p-1]" satisfies step 2. // // Therefore verify that both x and y of the public key point have the unique // correct representation of an element in the underlying field by verifying // that x and y are integers in [0, p-1]. if key.X.Sign() < 0 || key.Y.Sign() < 0 { return fmt.Errorf("Key x, y must not be negative") } if key.X.Cmp(params.P) >= 0 || key.Y.Cmp(params.P) >= 0 { return fmt.Errorf("Key x, y must not exceed P-1") } // SP800-56A § 5.6.2.3.2 Step 3. // "If q is an odd prime p, verify that (y_Q)**2 === (x_Q)***3 + a*x_Q + b (mod p). // If q = 2**m, verify that (y_Q)**2 + (x_Q)*(y_Q) == (x_Q)**3 + a*(x_Q)*2 + b in // the finite field of size 2**m. // (Ensures that the public key is on the correct elliptic curve.)" // // q is an odd prime p: proven/assumed above. // a = -3 for all supported curves. // // Therefore step 3 is satisfied simply by showing that // y**2 === x**3 - 3*x + B (mod P). // // This proves that the public key is on the correct elliptic curve. // But in practice, this test is provided by crypto/elliptic, so use that. if !key.Curve.IsOnCurve(key.X, key.Y) { return fmt.Errorf("Key point is not on the curve") } // SP800-56A § 5.6.2.3.2 Step 4. // "Verify that n*Q == O. // (Ensures that the public key has the correct order. Along with check 1, // ensures that the public key is in the correct range in the correct EC // subgroup, that is, it is in the correct EC subgroup and is not the // identity element.)" // // Ensure that public key has the correct order: // verify that n*Q = O. // // n*Q = O iff n*Q is the point at infinity (see step 1). ox, oy := key.Curve.ScalarMult(key.X, key.Y, params.N.Bytes()) if !isPointAtInfinityNISTP(ox, oy) { return fmt.Errorf("Public key does not have correct order") } // End of SP800-56A § 5.6.2.3.2 Public Key Validation Routine. // Key is valid. return nil }
[ "func", "(", "policy", "*", "KeyPolicy", ")", "goodKeyECDSA", "(", "key", "ecdsa", ".", "PublicKey", ")", "(", "err", "error", ")", "{", "// Check the curve.", "//", "// The validity of the curve is an assumption for all following tests.", "err", "=", "policy", ".", "goodCurve", "(", "key", ".", "Curve", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Key validation routine adapted from NIST SP800-56A § 5.6.2.3.2.", "// <http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar2.pdf>", "//", "// Assuming a prime field since a) we are only allowing such curves and b)", "// crypto/elliptic only supports prime curves. Where this assumption", "// simplifies the code below, it is explicitly stated and explained. If ever", "// adapting this code to support non-prime curves, refer to NIST SP800-56A §", "// 5.6.2.3.2 and adapt this code appropriately.", "params", ":=", "key", ".", "Params", "(", ")", "\n\n", "// SP800-56A § 5.6.2.3.2 Step 1.", "// Partial check of the public key for an invalid range in the EC group:", "// Verify that key is not the point at infinity O.", "// This code assumes that the point at infinity is (0,0), which is the", "// case for all supported curves.", "if", "isPointAtInfinityNISTP", "(", "key", ".", "X", ",", "key", ".", "Y", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// SP800-56A § 5.6.2.3.2 Step 2.", "// \"Verify that x_Q and y_Q are integers in the interval [0,p-1] in the", "// case that q is an odd prime p, or that x_Q and y_Q are bit strings", "// of length m bits in the case that q = 2**m.\"", "//", "// Prove prime field: ASSUMED.", "// Prove q != 2: ASSUMED. (Curve parameter. No supported curve has q == 2.)", "// Prime field && q != 2 => q is an odd prime p", "// Therefore \"verify that x, y are in [0, p-1]\" satisfies step 2.", "//", "// Therefore verify that both x and y of the public key point have the unique", "// correct representation of an element in the underlying field by verifying", "// that x and y are integers in [0, p-1].", "if", "key", ".", "X", ".", "Sign", "(", ")", "<", "0", "||", "key", ".", "Y", ".", "Sign", "(", ")", "<", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "key", ".", "X", ".", "Cmp", "(", "params", ".", "P", ")", ">=", "0", "||", "key", ".", "Y", ".", "Cmp", "(", "params", ".", "P", ")", ">=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// SP800-56A § 5.6.2.3.2 Step 3.", "// \"If q is an odd prime p, verify that (y_Q)**2 === (x_Q)***3 + a*x_Q + b (mod p).", "// If q = 2**m, verify that (y_Q)**2 + (x_Q)*(y_Q) == (x_Q)**3 + a*(x_Q)*2 + b in", "// the finite field of size 2**m.", "// (Ensures that the public key is on the correct elliptic curve.)\"", "//", "// q is an odd prime p: proven/assumed above.", "// a = -3 for all supported curves.", "//", "// Therefore step 3 is satisfied simply by showing that", "// y**2 === x**3 - 3*x + B (mod P).", "//", "// This proves that the public key is on the correct elliptic curve.", "// But in practice, this test is provided by crypto/elliptic, so use that.", "if", "!", "key", ".", "Curve", ".", "IsOnCurve", "(", "key", ".", "X", ",", "key", ".", "Y", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// SP800-56A § 5.6.2.3.2 Step 4.", "// \"Verify that n*Q == O.", "// (Ensures that the public key has the correct order. Along with check 1,", "// ensures that the public key is in the correct range in the correct EC", "// subgroup, that is, it is in the correct EC subgroup and is not the", "// identity element.)\"", "//", "// Ensure that public key has the correct order:", "// verify that n*Q = O.", "//", "// n*Q = O iff n*Q is the point at infinity (see step 1).", "ox", ",", "oy", ":=", "key", ".", "Curve", ".", "ScalarMult", "(", "key", ".", "X", ",", "key", ".", "Y", ",", "params", ".", "N", ".", "Bytes", "(", ")", ")", "\n", "if", "!", "isPointAtInfinityNISTP", "(", "ox", ",", "oy", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// End of SP800-56A § 5.6.2.3.2 Public Key Validation Routine.", "// Key is valid.", "return", "nil", "\n", "}" ]
// GoodKeyECDSA determines if an ECDSA pubkey meets our requirements
[ "GoodKeyECDSA", "determines", "if", "an", "ECDSA", "pubkey", "meets", "our", "requirements" ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/checks/certificate/publickey/goodkey/goodkey.go#L78-L164
12,229
globalsign/certlint
certlint.go
getCertificate
func getCertificate(file string) []byte { derBytes, err := ioutil.ReadFile(file) if err != nil { fmt.Println(err) return nil } // decode pem block, _ := pem.Decode(derBytes) if block != nil { derBytes = block.Bytes } return derBytes }
go
func getCertificate(file string) []byte { derBytes, err := ioutil.ReadFile(file) if err != nil { fmt.Println(err) return nil } // decode pem block, _ := pem.Decode(derBytes) if block != nil { derBytes = block.Bytes } return derBytes }
[ "func", "getCertificate", "(", "file", "string", ")", "[", "]", "byte", "{", "derBytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Println", "(", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "// decode pem", "block", ",", "_", ":=", "pem", ".", "Decode", "(", "derBytes", ")", "\n", "if", "block", "!=", "nil", "{", "derBytes", "=", "block", ".", "Bytes", "\n", "}", "\n", "return", "derBytes", "\n", "}" ]
// getCertificate reads a single certificate from disk
[ "getCertificate", "reads", "a", "single", "certificate", "from", "disk" ]
0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7
https://github.com/globalsign/certlint/blob/0d1cb4010c341ea8d36a5e49a88e1dca78a21fa7/certlint.go#L447-L459
12,230
mattetti/audio
aiff/chunk.go
Read
func (ch *Chunk) Read(p []byte) (n int, err error) { if ch == nil || ch.R == nil { return 0, errors.New("nil chunk/reader pointer") } n, err = ch.R.Read(p) ch.Pos += n return n, err }
go
func (ch *Chunk) Read(p []byte) (n int, err error) { if ch == nil || ch.R == nil { return 0, errors.New("nil chunk/reader pointer") } n, err = ch.R.Read(p) ch.Pos += n return n, err }
[ "func", "(", "ch", "*", "Chunk", ")", "Read", "(", "p", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "if", "ch", "==", "nil", "||", "ch", ".", "R", "==", "nil", "{", "return", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "n", ",", "err", "=", "ch", ".", "R", ".", "Read", "(", "p", ")", "\n", "ch", ".", "Pos", "+=", "n", "\n", "return", "n", ",", "err", "\n", "}" ]
// Read implements the reader interface
[ "Read", "implements", "the", "reader", "interface" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/aiff/chunk.go#L42-L49
12,231
mattetti/audio
aiff/chunk.go
ReadLE
func (ch *Chunk) ReadLE(dst interface{}) error { if ch == nil || ch.R == nil { return errors.New("nil chunk/reader pointer") } if ch.IsFullyRead() { return io.EOF } ch.Pos += binary.Size(dst) return binary.Read(ch.R, binary.LittleEndian, dst) }
go
func (ch *Chunk) ReadLE(dst interface{}) error { if ch == nil || ch.R == nil { return errors.New("nil chunk/reader pointer") } if ch.IsFullyRead() { return io.EOF } ch.Pos += binary.Size(dst) return binary.Read(ch.R, binary.LittleEndian, dst) }
[ "func", "(", "ch", "*", "Chunk", ")", "ReadLE", "(", "dst", "interface", "{", "}", ")", "error", "{", "if", "ch", "==", "nil", "||", "ch", ".", "R", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "ch", ".", "IsFullyRead", "(", ")", "{", "return", "io", ".", "EOF", "\n", "}", "\n", "ch", ".", "Pos", "+=", "binary", ".", "Size", "(", "dst", ")", "\n", "return", "binary", ".", "Read", "(", "ch", ".", "R", ",", "binary", ".", "LittleEndian", ",", "dst", ")", "\n", "}" ]
// ReadLE reads the Little Endian chunk data into the passed struct
[ "ReadLE", "reads", "the", "Little", "Endian", "chunk", "data", "into", "the", "passed", "struct" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/aiff/chunk.go#L52-L61
12,232
mattetti/audio
aiff/chunk.go
ReadByte
func (ch *Chunk) ReadByte() (byte, error) { if ch.IsFullyRead() { return 0, io.EOF } var r byte err := ch.ReadLE(&r) return r, err }
go
func (ch *Chunk) ReadByte() (byte, error) { if ch.IsFullyRead() { return 0, io.EOF } var r byte err := ch.ReadLE(&r) return r, err }
[ "func", "(", "ch", "*", "Chunk", ")", "ReadByte", "(", ")", "(", "byte", ",", "error", ")", "{", "if", "ch", ".", "IsFullyRead", "(", ")", "{", "return", "0", ",", "io", ".", "EOF", "\n", "}", "\n", "var", "r", "byte", "\n", "err", ":=", "ch", ".", "ReadLE", "(", "&", "r", ")", "\n", "return", "r", ",", "err", "\n", "}" ]
// ReadByte reads and returns a single byte
[ "ReadByte", "reads", "and", "returns", "a", "single", "byte" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/aiff/chunk.go#L73-L80
12,233
mattetti/audio
aiff/chunk.go
IsFullyRead
func (ch *Chunk) IsFullyRead() bool { if ch == nil || ch.R == nil { return true } return ch.Size <= ch.Pos }
go
func (ch *Chunk) IsFullyRead() bool { if ch == nil || ch.R == nil { return true } return ch.Size <= ch.Pos }
[ "func", "(", "ch", "*", "Chunk", ")", "IsFullyRead", "(", ")", "bool", "{", "if", "ch", "==", "nil", "||", "ch", ".", "R", "==", "nil", "{", "return", "true", "\n", "}", "\n", "return", "ch", ".", "Size", "<=", "ch", ".", "Pos", "\n", "}" ]
// IsFullyRead checks if we're finished reading the chunk
[ "IsFullyRead", "checks", "if", "we", "re", "finished", "reading", "the", "chunk" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/aiff/chunk.go#L83-L88
12,234
mattetti/audio
aiff/chunk.go
Jump
func (ch *Chunk) Jump(bytesAhead int) error { var err error var n int64 if bytesAhead > 0 { n, err = io.CopyN(ioutil.Discard, ch.R, int64(bytesAhead)) ch.Pos += int(n) } return err }
go
func (ch *Chunk) Jump(bytesAhead int) error { var err error var n int64 if bytesAhead > 0 { n, err = io.CopyN(ioutil.Discard, ch.R, int64(bytesAhead)) ch.Pos += int(n) } return err }
[ "func", "(", "ch", "*", "Chunk", ")", "Jump", "(", "bytesAhead", "int", ")", "error", "{", "var", "err", "error", "\n", "var", "n", "int64", "\n", "if", "bytesAhead", ">", "0", "{", "n", ",", "err", "=", "io", ".", "CopyN", "(", "ioutil", ".", "Discard", ",", "ch", ".", "R", ",", "int64", "(", "bytesAhead", ")", ")", "\n", "ch", ".", "Pos", "+=", "int", "(", "n", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Jump jumps ahead in the chunk
[ "Jump", "jumps", "ahead", "in", "the", "chunk" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/aiff/chunk.go#L91-L99
12,235
mattetti/audio
mp3/frame.go
Duration
func (f *Frame) Duration() time.Duration { if !f.Header.IsValid() { return 0 } ms := (1000 / float64(f.Header.SampleRate())) * float64(f.Header.Samples()) dur := time.Duration(int(float64(time.Millisecond) * ms)) if dur < 0 { // we have bad data, let's ignore it dur = 0 } return dur }
go
func (f *Frame) Duration() time.Duration { if !f.Header.IsValid() { return 0 } ms := (1000 / float64(f.Header.SampleRate())) * float64(f.Header.Samples()) dur := time.Duration(int(float64(time.Millisecond) * ms)) if dur < 0 { // we have bad data, let's ignore it dur = 0 } return dur }
[ "func", "(", "f", "*", "Frame", ")", "Duration", "(", ")", "time", ".", "Duration", "{", "if", "!", "f", ".", "Header", ".", "IsValid", "(", ")", "{", "return", "0", "\n", "}", "\n", "ms", ":=", "(", "1000", "/", "float64", "(", "f", ".", "Header", ".", "SampleRate", "(", ")", ")", ")", "*", "float64", "(", "f", ".", "Header", ".", "Samples", "(", ")", ")", "\n", "dur", ":=", "time", ".", "Duration", "(", "int", "(", "float64", "(", "time", ".", "Millisecond", ")", "*", "ms", ")", ")", "\n", "if", "dur", "<", "0", "{", "// we have bad data, let's ignore it", "dur", "=", "0", "\n", "}", "\n", "return", "dur", "\n", "}" ]
// Duration calculates the time duration of this frame based on the samplerate and number of samples
[ "Duration", "calculates", "the", "time", "duration", "of", "this", "frame", "based", "on", "the", "samplerate", "and", "number", "of", "samples" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/mp3/frame.go#L37-L48
12,236
mattetti/audio
mp3/frame.go
CRC
func (f *Frame) CRC() uint16 { var crc uint16 if !f.Header.Protection() { return 0 } crcdata := bytes.NewReader(f.buf[4:6]) binary.Read(crcdata, binary.BigEndian, &crc) return crc }
go
func (f *Frame) CRC() uint16 { var crc uint16 if !f.Header.Protection() { return 0 } crcdata := bytes.NewReader(f.buf[4:6]) binary.Read(crcdata, binary.BigEndian, &crc) return crc }
[ "func", "(", "f", "*", "Frame", ")", "CRC", "(", ")", "uint16", "{", "var", "crc", "uint16", "\n", "if", "!", "f", ".", "Header", ".", "Protection", "(", ")", "{", "return", "0", "\n", "}", "\n", "crcdata", ":=", "bytes", ".", "NewReader", "(", "f", ".", "buf", "[", "4", ":", "6", "]", ")", "\n", "binary", ".", "Read", "(", "crcdata", ",", "binary", ".", "BigEndian", ",", "&", "crc", ")", "\n", "return", "crc", "\n", "}" ]
// CRC returns the CRC word stored in this frame
[ "CRC", "returns", "the", "CRC", "word", "stored", "in", "this", "frame" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/mp3/frame.go#L51-L59
12,237
mattetti/audio
mp3/frame.go
SideInfo
func (f *Frame) SideInfo() FrameSideInfo { if f.Header.Protection() { return FrameSideInfo(f.buf[6:]) } else { return FrameSideInfo(f.buf[4:]) } }
go
func (f *Frame) SideInfo() FrameSideInfo { if f.Header.Protection() { return FrameSideInfo(f.buf[6:]) } else { return FrameSideInfo(f.buf[4:]) } }
[ "func", "(", "f", "*", "Frame", ")", "SideInfo", "(", ")", "FrameSideInfo", "{", "if", "f", ".", "Header", ".", "Protection", "(", ")", "{", "return", "FrameSideInfo", "(", "f", ".", "buf", "[", "6", ":", "]", ")", "\n", "}", "else", "{", "return", "FrameSideInfo", "(", "f", ".", "buf", "[", "4", ":", "]", ")", "\n", "}", "\n", "}" ]
// SideInfo returns the side info for this frame
[ "SideInfo", "returns", "the", "side", "info", "for", "this", "frame" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/mp3/frame.go#L62-L68
12,238
mattetti/audio
mp3/frame.go
String
func (f *Frame) String() string { str := "" str += fmt.Sprintf("Header: \n%s", f.Header) str += fmt.Sprintf("CRC: %x\n", f.CRC()) str += fmt.Sprintf("Samples: %v\n", f.Header.Samples()) str += fmt.Sprintf("Size: %v\n", f.Header.Size()) str += fmt.Sprintf("Duration: %v\n", f.Duration()) return str }
go
func (f *Frame) String() string { str := "" str += fmt.Sprintf("Header: \n%s", f.Header) str += fmt.Sprintf("CRC: %x\n", f.CRC()) str += fmt.Sprintf("Samples: %v\n", f.Header.Samples()) str += fmt.Sprintf("Size: %v\n", f.Header.Size()) str += fmt.Sprintf("Duration: %v\n", f.Duration()) return str }
[ "func", "(", "f", "*", "Frame", ")", "String", "(", ")", "string", "{", "str", ":=", "\"", "\"", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "f", ".", "Header", ")", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "f", ".", "CRC", "(", ")", ")", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "f", ".", "Header", ".", "Samples", "(", ")", ")", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "f", ".", "Header", ".", "Size", "(", ")", ")", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "f", ".", "Duration", "(", ")", ")", "\n", "return", "str", "\n", "}" ]
// Frame returns a string describing this frame, header and side info
[ "Frame", "returns", "a", "string", "describing", "this", "frame", "header", "and", "side", "info" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/mp3/frame.go#L71-L79
12,239
mattetti/audio
midi/varint.go
EncodeVarint
func EncodeVarint(x uint32) []byte { if x>>7 == 0 { return []byte{ byte(x), } } if x>>14 == 0 { return []byte{ byte(0x80 | x>>7), byte(127 & x), } } if x>>21 == 0 { return []byte{ byte(0x80 | x>>14), byte(0x80 | x>>7), byte(127 & x), } } return []byte{ byte(0x80 | x>>21), byte(0x80 | x>>14), byte(0x80 | x>>7), byte(127 & x), } }
go
func EncodeVarint(x uint32) []byte { if x>>7 == 0 { return []byte{ byte(x), } } if x>>14 == 0 { return []byte{ byte(0x80 | x>>7), byte(127 & x), } } if x>>21 == 0 { return []byte{ byte(0x80 | x>>14), byte(0x80 | x>>7), byte(127 & x), } } return []byte{ byte(0x80 | x>>21), byte(0x80 | x>>14), byte(0x80 | x>>7), byte(127 & x), } }
[ "func", "EncodeVarint", "(", "x", "uint32", ")", "[", "]", "byte", "{", "if", "x", ">>", "7", "==", "0", "{", "return", "[", "]", "byte", "{", "byte", "(", "x", ")", ",", "}", "\n", "}", "\n\n", "if", "x", ">>", "14", "==", "0", "{", "return", "[", "]", "byte", "{", "byte", "(", "0x80", "|", "x", ">>", "7", ")", ",", "byte", "(", "127", "&", "x", ")", ",", "}", "\n", "}", "\n\n", "if", "x", ">>", "21", "==", "0", "{", "return", "[", "]", "byte", "{", "byte", "(", "0x80", "|", "x", ">>", "14", ")", ",", "byte", "(", "0x80", "|", "x", ">>", "7", ")", ",", "byte", "(", "127", "&", "x", ")", ",", "}", "\n", "}", "\n\n", "return", "[", "]", "byte", "{", "byte", "(", "0x80", "|", "x", ">>", "21", ")", ",", "byte", "(", "0x80", "|", "x", ">>", "14", ")", ",", "byte", "(", "0x80", "|", "x", ">>", "7", ")", ",", "byte", "(", "127", "&", "x", ")", ",", "}", "\n", "}" ]
// EncodeVarint returns the varint encoding of x.
[ "EncodeVarint", "returns", "the", "varint", "encoding", "of", "x", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/varint.go#L4-L32
12,240
mattetti/audio
midi/varint.go
DecodeVarint
func DecodeVarint(buf []byte) (x uint32, n int) { if len(buf) < 1 { return 0, 0 } if buf[0] <= 0x80 { return uint32(buf[0]), 1 } var b byte for n, b = range buf { x = x << 7 x |= uint32(b) & 0x7F if (b & 0x80) == 0 { return x, n } } return x, n }
go
func DecodeVarint(buf []byte) (x uint32, n int) { if len(buf) < 1 { return 0, 0 } if buf[0] <= 0x80 { return uint32(buf[0]), 1 } var b byte for n, b = range buf { x = x << 7 x |= uint32(b) & 0x7F if (b & 0x80) == 0 { return x, n } } return x, n }
[ "func", "DecodeVarint", "(", "buf", "[", "]", "byte", ")", "(", "x", "uint32", ",", "n", "int", ")", "{", "if", "len", "(", "buf", ")", "<", "1", "{", "return", "0", ",", "0", "\n", "}", "\n\n", "if", "buf", "[", "0", "]", "<=", "0x80", "{", "return", "uint32", "(", "buf", "[", "0", "]", ")", ",", "1", "\n", "}", "\n\n", "var", "b", "byte", "\n", "for", "n", ",", "b", "=", "range", "buf", "{", "x", "=", "x", "<<", "7", "\n", "x", "|=", "uint32", "(", "b", ")", "&", "0x7F", "\n", "if", "(", "b", "&", "0x80", ")", "==", "0", "{", "return", "x", ",", "n", "\n", "}", "\n", "}", "\n\n", "return", "x", ",", "n", "\n", "}" ]
// DecodeVarint reads a varint-encoded integer from the slice. // It returns the integer and the number of bytes consumed, or // zero if there is not enough.
[ "DecodeVarint", "reads", "a", "varint", "-", "encoded", "integer", "from", "the", "slice", ".", "It", "returns", "the", "integer", "and", "the", "number", "of", "bytes", "consumed", "or", "zero", "if", "there", "is", "not", "enough", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/varint.go#L37-L56
12,241
mattetti/audio
transforms/quantize.go
Quantize
func Quantize(buf *audio.PCMBuffer, bitDepth int) { if buf == nil { return } max := math.Pow(2, float64(bitDepth)) - 1 buf.SwitchPrimaryType(audio.Float) bufLen := buf.Len() for i := 0; i < bufLen; i++ { buf.Floats[i] = round((buf.Floats[i]+1)*max)/max - 1.0 } }
go
func Quantize(buf *audio.PCMBuffer, bitDepth int) { if buf == nil { return } max := math.Pow(2, float64(bitDepth)) - 1 buf.SwitchPrimaryType(audio.Float) bufLen := buf.Len() for i := 0; i < bufLen; i++ { buf.Floats[i] = round((buf.Floats[i]+1)*max)/max - 1.0 } }
[ "func", "Quantize", "(", "buf", "*", "audio", ".", "PCMBuffer", ",", "bitDepth", "int", ")", "{", "if", "buf", "==", "nil", "{", "return", "\n", "}", "\n", "max", ":=", "math", ".", "Pow", "(", "2", ",", "float64", "(", "bitDepth", ")", ")", "-", "1", "\n\n", "buf", ".", "SwitchPrimaryType", "(", "audio", ".", "Float", ")", "\n", "bufLen", ":=", "buf", ".", "Len", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "bufLen", ";", "i", "++", "{", "buf", ".", "Floats", "[", "i", "]", "=", "round", "(", "(", "buf", ".", "Floats", "[", "i", "]", "+", "1", ")", "*", "max", ")", "/", "max", "-", "1.0", "\n", "}", "\n", "}" ]
// Quantize quantizes the audio signal to match the target bitDepth
[ "Quantize", "quantizes", "the", "audio", "signal", "to", "match", "the", "target", "bitDepth" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/transforms/quantize.go#L10-L21
12,242
mattetti/audio
transforms/decimator.go
Decimate
func Decimate(buf *audio.PCMBuffer, factor int) (err error) { if buf == nil || buf.Format == nil { return audio.ErrInvalidBuffer } if factor < 0 { return errors.New("can't use a negative factor") } // apply a low pass filter at the nyquist frequency to avoid // aliasing. if err := filters.LowPass(buf, float64(buf.Format.SampleRate)/2); err != nil { return err } // drop samples to match the decimation factor newLength := len(buf.Floats) / factor for i := 0; i < newLength; i++ { buf.Floats[i] = buf.Floats[i*factor] } buf.Floats = buf.Floats[:newLength] buf.Format.SampleRate /= factor return nil }
go
func Decimate(buf *audio.PCMBuffer, factor int) (err error) { if buf == nil || buf.Format == nil { return audio.ErrInvalidBuffer } if factor < 0 { return errors.New("can't use a negative factor") } // apply a low pass filter at the nyquist frequency to avoid // aliasing. if err := filters.LowPass(buf, float64(buf.Format.SampleRate)/2); err != nil { return err } // drop samples to match the decimation factor newLength := len(buf.Floats) / factor for i := 0; i < newLength; i++ { buf.Floats[i] = buf.Floats[i*factor] } buf.Floats = buf.Floats[:newLength] buf.Format.SampleRate /= factor return nil }
[ "func", "Decimate", "(", "buf", "*", "audio", ".", "PCMBuffer", ",", "factor", "int", ")", "(", "err", "error", ")", "{", "if", "buf", "==", "nil", "||", "buf", ".", "Format", "==", "nil", "{", "return", "audio", ".", "ErrInvalidBuffer", "\n", "}", "\n\n", "if", "factor", "<", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// apply a low pass filter at the nyquist frequency to avoid", "// aliasing.", "if", "err", ":=", "filters", ".", "LowPass", "(", "buf", ",", "float64", "(", "buf", ".", "Format", ".", "SampleRate", ")", "/", "2", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// drop samples to match the decimation factor", "newLength", ":=", "len", "(", "buf", ".", "Floats", ")", "/", "factor", "\n", "for", "i", ":=", "0", ";", "i", "<", "newLength", ";", "i", "++", "{", "buf", ".", "Floats", "[", "i", "]", "=", "buf", ".", "Floats", "[", "i", "*", "factor", "]", "\n", "}", "\n", "buf", ".", "Floats", "=", "buf", ".", "Floats", "[", ":", "newLength", "]", "\n", "buf", ".", "Format", ".", "SampleRate", "/=", "factor", "\n\n", "return", "nil", "\n", "}" ]
// Decimate drops samples to switch to a lower sample rate. // Factor is the decimation factor, for instance a factor of 2 of a 44100Hz buffer // will convert the buffer in a 22500 buffer.
[ "Decimate", "drops", "samples", "to", "switch", "to", "a", "lower", "sample", "rate", ".", "Factor", "is", "the", "decimation", "factor", "for", "instance", "a", "factor", "of", "2", "of", "a", "44100Hz", "buffer", "will", "convert", "the", "buffer", "in", "a", "22500", "buffer", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/transforms/decimator.go#L13-L37
12,243
mattetti/audio
audio.go
AvgInt
func AvgInt(xs ...int) int { var output int for i := 0; i < len(xs); i++ { output += xs[i] } return output / len(xs) }
go
func AvgInt(xs ...int) int { var output int for i := 0; i < len(xs); i++ { output += xs[i] } return output / len(xs) }
[ "func", "AvgInt", "(", "xs", "...", "int", ")", "int", "{", "var", "output", "int", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "xs", ")", ";", "i", "++", "{", "output", "+=", "xs", "[", "i", "]", "\n", "}", "\n", "return", "output", "/", "len", "(", "xs", ")", "\n", "}" ]
// AvgInt averages the int values passed
[ "AvgInt", "averages", "the", "int", "values", "passed" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/audio.go#L13-L19
12,244
mattetti/audio
audio.go
IeeeFloatToInt
func IeeeFloatToInt(b [10]byte) int { var i uint32 // Negative number if (b[0] & 0x80) == 1 { return 0 } // Less than 1 if b[0] <= 0x3F { return 1 } // Too big if b[0] > 0x40 { return 67108864 } // Still too big if b[0] == 0x40 && b[1] > 0x1C { return 800000000 } i = (uint32(b[2]) << 23) | (uint32(b[3]) << 15) | (uint32(b[4]) << 7) | (uint32(b[5]) >> 1) i >>= (29 - uint32(b[1])) return int(i) }
go
func IeeeFloatToInt(b [10]byte) int { var i uint32 // Negative number if (b[0] & 0x80) == 1 { return 0 } // Less than 1 if b[0] <= 0x3F { return 1 } // Too big if b[0] > 0x40 { return 67108864 } // Still too big if b[0] == 0x40 && b[1] > 0x1C { return 800000000 } i = (uint32(b[2]) << 23) | (uint32(b[3]) << 15) | (uint32(b[4]) << 7) | (uint32(b[5]) >> 1) i >>= (29 - uint32(b[1])) return int(i) }
[ "func", "IeeeFloatToInt", "(", "b", "[", "10", "]", "byte", ")", "int", "{", "var", "i", "uint32", "\n", "// Negative number", "if", "(", "b", "[", "0", "]", "&", "0x80", ")", "==", "1", "{", "return", "0", "\n", "}", "\n\n", "// Less than 1", "if", "b", "[", "0", "]", "<=", "0x3F", "{", "return", "1", "\n", "}", "\n\n", "// Too big", "if", "b", "[", "0", "]", ">", "0x40", "{", "return", "67108864", "\n", "}", "\n\n", "// Still too big", "if", "b", "[", "0", "]", "==", "0x40", "&&", "b", "[", "1", "]", ">", "0x1C", "{", "return", "800000000", "\n", "}", "\n\n", "i", "=", "(", "uint32", "(", "b", "[", "2", "]", ")", "<<", "23", ")", "|", "(", "uint32", "(", "b", "[", "3", "]", ")", "<<", "15", ")", "|", "(", "uint32", "(", "b", "[", "4", "]", ")", "<<", "7", ")", "|", "(", "uint32", "(", "b", "[", "5", "]", ")", ">>", "1", ")", "\n", "i", ">>=", "(", "29", "-", "uint32", "(", "b", "[", "1", "]", ")", ")", "\n\n", "return", "int", "(", "i", ")", "\n", "}" ]
// IeeeFloatToInt converts a 10 byte IEEE float into an int.
[ "IeeeFloatToInt", "converts", "a", "10", "byte", "IEEE", "float", "into", "an", "int", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/audio.go#L39-L65
12,245
mattetti/audio
aiff/decoder.go
Duration
func (d *Decoder) Duration() (time.Duration, error) { if d == nil { return 0, errors.New("can't calculate the duration of a nil pointer") } d.ReadInfo() if err := d.Err(); err != nil { return 0, err } duration := time.Duration(float64(d.NumSampleFrames) / float64(d.SampleRate) * float64(time.Second)) return duration, nil }
go
func (d *Decoder) Duration() (time.Duration, error) { if d == nil { return 0, errors.New("can't calculate the duration of a nil pointer") } d.ReadInfo() if err := d.Err(); err != nil { return 0, err } duration := time.Duration(float64(d.NumSampleFrames) / float64(d.SampleRate) * float64(time.Second)) return duration, nil }
[ "func", "(", "d", "*", "Decoder", ")", "Duration", "(", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "if", "d", "==", "nil", "{", "return", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "d", ".", "ReadInfo", "(", ")", "\n", "if", "err", ":=", "d", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "duration", ":=", "time", ".", "Duration", "(", "float64", "(", "d", ".", "NumSampleFrames", ")", "/", "float64", "(", "d", ".", "SampleRate", ")", "*", "float64", "(", "time", ".", "Second", ")", ")", "\n", "return", "duration", ",", "nil", "\n", "}" ]
// Duration returns the time duration for the current AIFF container
[ "Duration", "returns", "the", "time", "duration", "for", "the", "current", "AIFF", "container" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/aiff/decoder.go#L141-L151
12,246
mattetti/audio
aiff/decoder.go
iDnSize
func (d *Decoder) iDnSize() ([4]byte, uint32, error) { var ID [4]byte var blockSize uint32 if d.err = binary.Read(d.r, binary.BigEndian, &ID); d.err != nil { return ID, blockSize, d.err } if d.err = binary.Read(d.r, binary.BigEndian, &blockSize); d.err != nil { return ID, blockSize, d.err } return ID, blockSize, nil }
go
func (d *Decoder) iDnSize() ([4]byte, uint32, error) { var ID [4]byte var blockSize uint32 if d.err = binary.Read(d.r, binary.BigEndian, &ID); d.err != nil { return ID, blockSize, d.err } if d.err = binary.Read(d.r, binary.BigEndian, &blockSize); d.err != nil { return ID, blockSize, d.err } return ID, blockSize, nil }
[ "func", "(", "d", "*", "Decoder", ")", "iDnSize", "(", ")", "(", "[", "4", "]", "byte", ",", "uint32", ",", "error", ")", "{", "var", "ID", "[", "4", "]", "byte", "\n", "var", "blockSize", "uint32", "\n", "if", "d", ".", "err", "=", "binary", ".", "Read", "(", "d", ".", "r", ",", "binary", ".", "BigEndian", ",", "&", "ID", ")", ";", "d", ".", "err", "!=", "nil", "{", "return", "ID", ",", "blockSize", ",", "d", ".", "err", "\n", "}", "\n", "if", "d", ".", "err", "=", "binary", ".", "Read", "(", "d", ".", "r", ",", "binary", ".", "BigEndian", ",", "&", "blockSize", ")", ";", "d", ".", "err", "!=", "nil", "{", "return", "ID", ",", "blockSize", ",", "d", ".", "err", "\n", "}", "\n", "return", "ID", ",", "blockSize", ",", "nil", "\n", "}" ]
// iDnSize returns the next ID + block size
[ "iDnSize", "returns", "the", "next", "ID", "+", "block", "size" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/aiff/decoder.go#L359-L369
12,247
mattetti/audio
aiff/decoder.go
ReadInfo
func (d *Decoder) ReadInfo() { if d == nil || d.SampleRate > 0 { return } if d.err = d.readHeaders(); d.err != nil { d.err = fmt.Errorf("failed to read header - %v", d.err) return } var ( id [4]byte size uint32 rewindBytes int64 ) for d.err != io.EOF { id, size, d.err = d.iDnSize() if d.err != nil { d.err = fmt.Errorf("error reading chunk header - %v", d.err) break } switch id { case COMMID: d.parseCommChunk(size) // if we found other chunks before the COMM, // we need to rewind the reader so we can properly // read the rest later. if rewindBytes > 0 { d.r.Seek(-(rewindBytes + int64(size)), 1) break } return default: // we haven't read the COMM chunk yet, we need to track location to rewind if d.SampleRate == 0 { rewindBytes += int64(size) } if d.err = d.jumpTo(int(size)); d.err != nil { return } } } }
go
func (d *Decoder) ReadInfo() { if d == nil || d.SampleRate > 0 { return } if d.err = d.readHeaders(); d.err != nil { d.err = fmt.Errorf("failed to read header - %v", d.err) return } var ( id [4]byte size uint32 rewindBytes int64 ) for d.err != io.EOF { id, size, d.err = d.iDnSize() if d.err != nil { d.err = fmt.Errorf("error reading chunk header - %v", d.err) break } switch id { case COMMID: d.parseCommChunk(size) // if we found other chunks before the COMM, // we need to rewind the reader so we can properly // read the rest later. if rewindBytes > 0 { d.r.Seek(-(rewindBytes + int64(size)), 1) break } return default: // we haven't read the COMM chunk yet, we need to track location to rewind if d.SampleRate == 0 { rewindBytes += int64(size) } if d.err = d.jumpTo(int(size)); d.err != nil { return } } } }
[ "func", "(", "d", "*", "Decoder", ")", "ReadInfo", "(", ")", "{", "if", "d", "==", "nil", "||", "d", ".", "SampleRate", ">", "0", "{", "return", "\n", "}", "\n", "if", "d", ".", "err", "=", "d", ".", "readHeaders", "(", ")", ";", "d", ".", "err", "!=", "nil", "{", "d", ".", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "d", ".", "err", ")", "\n", "return", "\n", "}", "\n\n", "var", "(", "id", "[", "4", "]", "byte", "\n", "size", "uint32", "\n", "rewindBytes", "int64", "\n", ")", "\n", "for", "d", ".", "err", "!=", "io", ".", "EOF", "{", "id", ",", "size", ",", "d", ".", "err", "=", "d", ".", "iDnSize", "(", ")", "\n", "if", "d", ".", "err", "!=", "nil", "{", "d", ".", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "d", ".", "err", ")", "\n", "break", "\n", "}", "\n", "switch", "id", "{", "case", "COMMID", ":", "d", ".", "parseCommChunk", "(", "size", ")", "\n", "// if we found other chunks before the COMM,", "// we need to rewind the reader so we can properly", "// read the rest later.", "if", "rewindBytes", ">", "0", "{", "d", ".", "r", ".", "Seek", "(", "-", "(", "rewindBytes", "+", "int64", "(", "size", ")", ")", ",", "1", ")", "\n", "break", "\n", "}", "\n", "return", "\n", "default", ":", "// we haven't read the COMM chunk yet, we need to track location to rewind", "if", "d", ".", "SampleRate", "==", "0", "{", "rewindBytes", "+=", "int64", "(", "size", ")", "\n", "}", "\n", "if", "d", ".", "err", "=", "d", ".", "jumpTo", "(", "int", "(", "size", ")", ")", ";", "d", ".", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// ReadInfo reads the underlying reader until the comm header is parsed. // This method is safe to call multiple times.
[ "ReadInfo", "reads", "the", "underlying", "reader", "until", "the", "comm", "header", "is", "parsed", ".", "This", "method", "is", "safe", "to", "call", "multiple", "times", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/aiff/decoder.go#L405-L446
12,248
mattetti/audio
midi/decoder.go
VarLen
func (d *Decoder) VarLen() (val uint32, readBytes uint32, err error) { buf := []byte{} var lastByte bool var n uint32 for !lastByte { b, err := d.ReadByte() if err != nil { return 0, n, err } buf = append(buf, b) lastByte = (b>>7 == 0x0) n++ } val, nUsed := DecodeVarint(buf) return val, uint32(nUsed), nil }
go
func (d *Decoder) VarLen() (val uint32, readBytes uint32, err error) { buf := []byte{} var lastByte bool var n uint32 for !lastByte { b, err := d.ReadByte() if err != nil { return 0, n, err } buf = append(buf, b) lastByte = (b>>7 == 0x0) n++ } val, nUsed := DecodeVarint(buf) return val, uint32(nUsed), nil }
[ "func", "(", "d", "*", "Decoder", ")", "VarLen", "(", ")", "(", "val", "uint32", ",", "readBytes", "uint32", ",", "err", "error", ")", "{", "buf", ":=", "[", "]", "byte", "{", "}", "\n", "var", "lastByte", "bool", "\n", "var", "n", "uint32", "\n\n", "for", "!", "lastByte", "{", "b", ",", "err", ":=", "d", ".", "ReadByte", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "n", ",", "err", "\n", "}", "\n", "buf", "=", "append", "(", "buf", ",", "b", ")", "\n", "lastByte", "=", "(", "b", ">>", "7", "==", "0x0", ")", "\n", "n", "++", "\n", "}", "\n\n", "val", ",", "nUsed", ":=", "DecodeVarint", "(", "buf", ")", "\n", "return", "val", ",", "uint32", "(", "nUsed", ")", ",", "nil", "\n", "}" ]
// VarLen returns the variable length value at the exact parser location.
[ "VarLen", "returns", "the", "variable", "length", "value", "at", "the", "exact", "parser", "location", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/decoder.go#L208-L225
12,249
mattetti/audio
midi/decoder.go
VarLenTxt
func (d *Decoder) VarLenTxt() (string, uint32, error) { var l uint32 var err error var n uint32 if l, n, err = d.VarLen(); err != nil { return "", n, err } buf := make([]byte, l) err = d.Read(buf) return string(buf), n, err }
go
func (d *Decoder) VarLenTxt() (string, uint32, error) { var l uint32 var err error var n uint32 if l, n, err = d.VarLen(); err != nil { return "", n, err } buf := make([]byte, l) err = d.Read(buf) return string(buf), n, err }
[ "func", "(", "d", "*", "Decoder", ")", "VarLenTxt", "(", ")", "(", "string", ",", "uint32", ",", "error", ")", "{", "var", "l", "uint32", "\n", "var", "err", "error", "\n", "var", "n", "uint32", "\n\n", "if", "l", ",", "n", ",", "err", "=", "d", ".", "VarLen", "(", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "n", ",", "err", "\n", "}", "\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "l", ")", "\n", "err", "=", "d", ".", "Read", "(", "buf", ")", "\n", "return", "string", "(", "buf", ")", ",", "n", ",", "err", "\n", "}" ]
// VarLengthTxt Returns a variable length text string // as well as the amount of bytes read
[ "VarLengthTxt", "Returns", "a", "variable", "length", "text", "string", "as", "well", "as", "the", "amount", "of", "bytes", "read" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/decoder.go#L229-L240
12,250
mattetti/audio
midi/decoder.go
Read
func (d *Decoder) Read(dst interface{}) error { return binary.Read(d.r, binary.BigEndian, dst) }
go
func (d *Decoder) Read(dst interface{}) error { return binary.Read(d.r, binary.BigEndian, dst) }
[ "func", "(", "d", "*", "Decoder", ")", "Read", "(", "dst", "interface", "{", "}", ")", "error", "{", "return", "binary", ".", "Read", "(", "d", ".", "r", ",", "binary", ".", "BigEndian", ",", "dst", ")", "\n", "}" ]
// read reads n bytes from the parser's reader and stores them into the provided dst, // which must be a pointer to a fixed-size value.
[ "read", "reads", "n", "bytes", "from", "the", "parser", "s", "reader", "and", "stores", "them", "into", "the", "provided", "dst", "which", "must", "be", "a", "pointer", "to", "a", "fixed", "-", "size", "value", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/decoder.go#L250-L252
12,251
mattetti/audio
midi/decoder.go
Uint7
func (d *Decoder) Uint7() (uint8, error) { b, err := d.ReadByte() if err != nil { return 0, err } return (b & 0x7f), nil }
go
func (d *Decoder) Uint7() (uint8, error) { b, err := d.ReadByte() if err != nil { return 0, err } return (b & 0x7f), nil }
[ "func", "(", "d", "*", "Decoder", ")", "Uint7", "(", ")", "(", "uint8", ",", "error", ")", "{", "b", ",", "err", ":=", "d", ".", "ReadByte", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "(", "b", "&", "0x7f", ")", ",", "nil", "\n", "}" ]
// Uint7 reads a byte and converts the first 7 bits into an uint8
[ "Uint7", "reads", "a", "byte", "and", "converts", "the", "first", "7", "bits", "into", "an", "uint8" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/decoder.go#L255-L261
12,252
mattetti/audio
midi/decoder.go
Uint24
func (d *Decoder) Uint24() (uint32, error) { bytes := make([]byte, 3) if err := d.Read(bytes); err != nil { return 0, err } var output uint32 output |= uint32(bytes[2]) << 0 output |= uint32(bytes[1]) << 8 output |= uint32(bytes[0]) << 16 return output, nil }
go
func (d *Decoder) Uint24() (uint32, error) { bytes := make([]byte, 3) if err := d.Read(bytes); err != nil { return 0, err } var output uint32 output |= uint32(bytes[2]) << 0 output |= uint32(bytes[1]) << 8 output |= uint32(bytes[0]) << 16 return output, nil }
[ "func", "(", "d", "*", "Decoder", ")", "Uint24", "(", ")", "(", "uint32", ",", "error", ")", "{", "bytes", ":=", "make", "(", "[", "]", "byte", ",", "3", ")", "\n", "if", "err", ":=", "d", ".", "Read", "(", "bytes", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "var", "output", "uint32", "\n", "output", "|=", "uint32", "(", "bytes", "[", "2", "]", ")", "<<", "0", "\n", "output", "|=", "uint32", "(", "bytes", "[", "1", "]", ")", "<<", "8", "\n", "output", "|=", "uint32", "(", "bytes", "[", "0", "]", ")", "<<", "16", "\n\n", "return", "output", ",", "nil", "\n", "}" ]
// Uint24 reads 3 bytes and convert them into a uint32
[ "Uint24", "reads", "3", "bytes", "and", "convert", "them", "into", "a", "uint32" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/decoder.go#L264-L276
12,253
mattetti/audio
riff/parser.go
ParseHeaders
func (c *Parser) ParseHeaders() error { id, size, err := c.IDnSize() if err != nil { return err } c.ID = id if c.ID != RiffID { return fmt.Errorf("%s - %s", c.ID, ErrFmtNotSupported) } c.Size = size if err := binary.Read(c.r, binary.BigEndian, &c.Format); err != nil { return err } return nil }
go
func (c *Parser) ParseHeaders() error { id, size, err := c.IDnSize() if err != nil { return err } c.ID = id if c.ID != RiffID { return fmt.Errorf("%s - %s", c.ID, ErrFmtNotSupported) } c.Size = size if err := binary.Read(c.r, binary.BigEndian, &c.Format); err != nil { return err } return nil }
[ "func", "(", "c", "*", "Parser", ")", "ParseHeaders", "(", ")", "error", "{", "id", ",", "size", ",", "err", ":=", "c", ".", "IDnSize", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ".", "ID", "=", "id", "\n", "if", "c", ".", "ID", "!=", "RiffID", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "c", ".", "ID", ",", "ErrFmtNotSupported", ")", "\n", "}", "\n", "c", ".", "Size", "=", "size", "\n", "if", "err", ":=", "binary", ".", "Read", "(", "c", ".", "r", ",", "binary", ".", "BigEndian", ",", "&", "c", ".", "Format", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ParseHeaders reads the header of the passed container and populat the container with parsed info. // Note that this code advances the container reader.
[ "ParseHeaders", "reads", "the", "header", "of", "the", "passed", "container", "and", "populat", "the", "container", "with", "parsed", "info", ".", "Note", "that", "this", "code", "advances", "the", "container", "reader", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/riff/parser.go#L77-L92
12,254
mattetti/audio
riff/parser.go
NextChunk
func (c *Parser) NextChunk() (*Chunk, error) { if c == nil { return nil, errors.New("can't calculate the duration of a nil pointer") } id, size, err := c.IDnSize() if err != nil { return nil, err } // all RIFF chunks (including WAVE "data" chunks) must be word aligned. // If the data uses an odd number of bytes, a padding byte with a value of zero must be placed at the end of the sample data. // The "data" chunk header's size should not include this byte. if size%2 == 1 { size++ } ch := &Chunk{ ID: id, Size: int(size), R: c.r, } return ch, nil }
go
func (c *Parser) NextChunk() (*Chunk, error) { if c == nil { return nil, errors.New("can't calculate the duration of a nil pointer") } id, size, err := c.IDnSize() if err != nil { return nil, err } // all RIFF chunks (including WAVE "data" chunks) must be word aligned. // If the data uses an odd number of bytes, a padding byte with a value of zero must be placed at the end of the sample data. // The "data" chunk header's size should not include this byte. if size%2 == 1 { size++ } ch := &Chunk{ ID: id, Size: int(size), R: c.r, } return ch, nil }
[ "func", "(", "c", "*", "Parser", ")", "NextChunk", "(", ")", "(", "*", "Chunk", ",", "error", ")", "{", "if", "c", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "id", ",", "size", ",", "err", ":=", "c", ".", "IDnSize", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// all RIFF chunks (including WAVE \"data\" chunks) must be word aligned.", "// If the data uses an odd number of bytes, a padding byte with a value of zero must be placed at the end of the sample data.", "// The \"data\" chunk header's size should not include this byte.", "if", "size", "%", "2", "==", "1", "{", "size", "++", "\n", "}", "\n\n", "ch", ":=", "&", "Chunk", "{", "ID", ":", "id", ",", "Size", ":", "int", "(", "size", ")", ",", "R", ":", "c", ".", "r", ",", "}", "\n", "return", "ch", ",", "nil", "\n", "}" ]
// NextChunk returns a convenient structure to parse the next chunk. // If the container is fully read, io.EOF is returned as an error.
[ "NextChunk", "returns", "a", "convenient", "structure", "to", "parse", "the", "next", "chunk", ".", "If", "the", "container", "is", "fully", "read", "io", ".", "EOF", "is", "returned", "as", "an", "error", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/riff/parser.go#L127-L149
12,255
mattetti/audio
riff/parser.go
IDnSize
func (c *Parser) IDnSize() ([4]byte, uint32, error) { var ID [4]byte var blockSize uint32 if err := binary.Read(c.r, binary.BigEndian, &ID); err != nil { return ID, blockSize, err } if err := binary.Read(c.r, binary.LittleEndian, &blockSize); err != err { return ID, blockSize, err } return ID, blockSize, nil }
go
func (c *Parser) IDnSize() ([4]byte, uint32, error) { var ID [4]byte var blockSize uint32 if err := binary.Read(c.r, binary.BigEndian, &ID); err != nil { return ID, blockSize, err } if err := binary.Read(c.r, binary.LittleEndian, &blockSize); err != err { return ID, blockSize, err } return ID, blockSize, nil }
[ "func", "(", "c", "*", "Parser", ")", "IDnSize", "(", ")", "(", "[", "4", "]", "byte", ",", "uint32", ",", "error", ")", "{", "var", "ID", "[", "4", "]", "byte", "\n", "var", "blockSize", "uint32", "\n", "if", "err", ":=", "binary", ".", "Read", "(", "c", ".", "r", ",", "binary", ".", "BigEndian", ",", "&", "ID", ")", ";", "err", "!=", "nil", "{", "return", "ID", ",", "blockSize", ",", "err", "\n", "}", "\n", "if", "err", ":=", "binary", ".", "Read", "(", "c", ".", "r", ",", "binary", ".", "LittleEndian", ",", "&", "blockSize", ")", ";", "err", "!=", "err", "{", "return", "ID", ",", "blockSize", ",", "err", "\n", "}", "\n", "return", "ID", ",", "blockSize", ",", "nil", "\n", "}" ]
// IDnSize returns the next ID + block size
[ "IDnSize", "returns", "the", "next", "ID", "+", "block", "size" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/riff/parser.go#L152-L162
12,256
mattetti/audio
riff/parser.go
Parse
func (p *Parser) Parse() error { if p == nil { return errors.New("can't calculate the wav duration of a nil pointer") } if p.Size == 0 { id, size, err := p.IDnSize() if err != nil { return err } p.ID = id if p.ID != RiffID { return fmt.Errorf("%s - %s", p.ID, ErrFmtNotSupported) } p.Size = size if err := binary.Read(p.r, binary.BigEndian, &p.Format); err != nil { return err } } var chunk *Chunk var err error for err == nil { chunk, err = p.NextChunk() if err != nil { break } if chunk.ID == FmtID { chunk.DecodeWavHeader(p) } else { if p.Chan != nil { if chunk.Wg == nil { chunk.Wg = p.Wg } chunk.Wg.Add(1) p.Chan <- chunk // the channel has to release otherwise the goroutine is locked chunk.Wg.Wait() } } // BFW: bext chunk described here // https://tech.ebu.ch/docs/tech/tech3285.pdf if !chunk.IsFullyRead() { chunk.Drain() } } if p.Wg != nil { p.Wg.Wait() } if p.Chan != nil { close(p.Chan) } if err == io.EOF { return nil } return err }
go
func (p *Parser) Parse() error { if p == nil { return errors.New("can't calculate the wav duration of a nil pointer") } if p.Size == 0 { id, size, err := p.IDnSize() if err != nil { return err } p.ID = id if p.ID != RiffID { return fmt.Errorf("%s - %s", p.ID, ErrFmtNotSupported) } p.Size = size if err := binary.Read(p.r, binary.BigEndian, &p.Format); err != nil { return err } } var chunk *Chunk var err error for err == nil { chunk, err = p.NextChunk() if err != nil { break } if chunk.ID == FmtID { chunk.DecodeWavHeader(p) } else { if p.Chan != nil { if chunk.Wg == nil { chunk.Wg = p.Wg } chunk.Wg.Add(1) p.Chan <- chunk // the channel has to release otherwise the goroutine is locked chunk.Wg.Wait() } } // BFW: bext chunk described here // https://tech.ebu.ch/docs/tech/tech3285.pdf if !chunk.IsFullyRead() { chunk.Drain() } } if p.Wg != nil { p.Wg.Wait() } if p.Chan != nil { close(p.Chan) } if err == io.EOF { return nil } return err }
[ "func", "(", "p", "*", "Parser", ")", "Parse", "(", ")", "error", "{", "if", "p", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "p", ".", "Size", "==", "0", "{", "id", ",", "size", ",", "err", ":=", "p", ".", "IDnSize", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "p", ".", "ID", "=", "id", "\n", "if", "p", ".", "ID", "!=", "RiffID", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "p", ".", "ID", ",", "ErrFmtNotSupported", ")", "\n", "}", "\n", "p", ".", "Size", "=", "size", "\n", "if", "err", ":=", "binary", ".", "Read", "(", "p", ".", "r", ",", "binary", ".", "BigEndian", ",", "&", "p", ".", "Format", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "var", "chunk", "*", "Chunk", "\n", "var", "err", "error", "\n", "for", "err", "==", "nil", "{", "chunk", ",", "err", "=", "p", ".", "NextChunk", "(", ")", "\n", "if", "err", "!=", "nil", "{", "break", "\n", "}", "\n\n", "if", "chunk", ".", "ID", "==", "FmtID", "{", "chunk", ".", "DecodeWavHeader", "(", "p", ")", "\n", "}", "else", "{", "if", "p", ".", "Chan", "!=", "nil", "{", "if", "chunk", ".", "Wg", "==", "nil", "{", "chunk", ".", "Wg", "=", "p", ".", "Wg", "\n", "}", "\n", "chunk", ".", "Wg", ".", "Add", "(", "1", ")", "\n", "p", ".", "Chan", "<-", "chunk", "\n", "// the channel has to release otherwise the goroutine is locked", "chunk", ".", "Wg", ".", "Wait", "(", ")", "\n", "}", "\n", "}", "\n\n", "// BFW: bext chunk described here", "// https://tech.ebu.ch/docs/tech/tech3285.pdf", "if", "!", "chunk", ".", "IsFullyRead", "(", ")", "{", "chunk", ".", "Drain", "(", ")", "\n", "}", "\n\n", "}", "\n", "if", "p", ".", "Wg", "!=", "nil", "{", "p", ".", "Wg", ".", "Wait", "(", ")", "\n", "}", "\n\n", "if", "p", ".", "Chan", "!=", "nil", "{", "close", "(", "p", ".", "Chan", ")", "\n", "}", "\n\n", "if", "err", "==", "io", ".", "EOF", "{", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Parse parses the content of the file and populate the useful fields. // If the parser has a chan set, chunks are sent to the channel.
[ "Parse", "parses", "the", "content", "of", "the", "file", "and", "populate", "the", "useful", "fields", ".", "If", "the", "parser", "has", "a", "chan", "set", "chunks", "are", "sent", "to", "the", "channel", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/riff/parser.go#L166-L228
12,257
mattetti/audio
riff/parser.go
wavDuration
func (p *Parser) wavDuration() (time.Duration, error) { if p.Size == 0 || p.AvgBytesPerSec == 0 { return 0, fmt.Errorf("can't extract the duration due to the file not properly parsed") } duration := time.Duration((float64(p.Size) / float64(p.AvgBytesPerSec)) * float64(time.Second)) return duration, nil }
go
func (p *Parser) wavDuration() (time.Duration, error) { if p.Size == 0 || p.AvgBytesPerSec == 0 { return 0, fmt.Errorf("can't extract the duration due to the file not properly parsed") } duration := time.Duration((float64(p.Size) / float64(p.AvgBytesPerSec)) * float64(time.Second)) return duration, nil }
[ "func", "(", "p", "*", "Parser", ")", "wavDuration", "(", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "if", "p", ".", "Size", "==", "0", "||", "p", ".", "AvgBytesPerSec", "==", "0", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "duration", ":=", "time", ".", "Duration", "(", "(", "float64", "(", "p", ".", "Size", ")", "/", "float64", "(", "p", ".", "AvgBytesPerSec", ")", ")", "*", "float64", "(", "time", ".", "Second", ")", ")", "\n", "return", "duration", ",", "nil", "\n", "}" ]
// WavDuration returns the time duration of a wav container.
[ "WavDuration", "returns", "the", "time", "duration", "of", "a", "wav", "container", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/riff/parser.go#L231-L237
12,258
mattetti/audio
mp3/decoder.go
Duration
func (d *Decoder) Duration() (time.Duration, error) { if d == nil { return 0, errors.New("can't calculate the duration of a nil pointer") } fr := &Frame{} var frameDuration time.Duration var duration time.Duration var err error for { err = d.Next(fr) if err != nil { // bad headers can be ignored and hopefully skipped if err == ErrInvalidHeader { continue } break } frameDuration = fr.Duration() if frameDuration > 0 { duration += frameDuration } d.NbrFrames++ } if err == io.EOF || err == io.ErrUnexpectedEOF || err == io.ErrShortBuffer { err = nil } return duration, err }
go
func (d *Decoder) Duration() (time.Duration, error) { if d == nil { return 0, errors.New("can't calculate the duration of a nil pointer") } fr := &Frame{} var frameDuration time.Duration var duration time.Duration var err error for { err = d.Next(fr) if err != nil { // bad headers can be ignored and hopefully skipped if err == ErrInvalidHeader { continue } break } frameDuration = fr.Duration() if frameDuration > 0 { duration += frameDuration } d.NbrFrames++ } if err == io.EOF || err == io.ErrUnexpectedEOF || err == io.ErrShortBuffer { err = nil } return duration, err }
[ "func", "(", "d", "*", "Decoder", ")", "Duration", "(", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "if", "d", "==", "nil", "{", "return", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "fr", ":=", "&", "Frame", "{", "}", "\n", "var", "frameDuration", "time", ".", "Duration", "\n", "var", "duration", "time", ".", "Duration", "\n", "var", "err", "error", "\n", "for", "{", "err", "=", "d", ".", "Next", "(", "fr", ")", "\n", "if", "err", "!=", "nil", "{", "// bad headers can be ignored and hopefully skipped", "if", "err", "==", "ErrInvalidHeader", "{", "continue", "\n", "}", "\n", "break", "\n", "}", "\n", "frameDuration", "=", "fr", ".", "Duration", "(", ")", "\n", "if", "frameDuration", ">", "0", "{", "duration", "+=", "frameDuration", "\n", "}", "\n", "d", ".", "NbrFrames", "++", "\n", "}", "\n", "if", "err", "==", "io", ".", "EOF", "||", "err", "==", "io", ".", "ErrUnexpectedEOF", "||", "err", "==", "io", ".", "ErrShortBuffer", "{", "err", "=", "nil", "\n", "}", "\n\n", "return", "duration", ",", "err", "\n", "}" ]
// Duration returns the time duration for the current mp3 file // The entire reader will be consumed, the consumer might want to rewind the reader // if they want to read more from the feed. // Note that this is an estimated duration based on how the frames look. An invalid file might have // a duration.
[ "Duration", "returns", "the", "time", "duration", "for", "the", "current", "mp3", "file", "The", "entire", "reader", "will", "be", "consumed", "the", "consumer", "might", "want", "to", "rewind", "the", "reader", "if", "they", "want", "to", "read", "more", "from", "the", "feed", ".", "Note", "that", "this", "is", "an", "estimated", "duration", "based", "on", "how", "the", "frames", "look", ".", "An", "invalid", "file", "might", "have", "a", "duration", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/mp3/decoder.go#L82-L110
12,259
mattetti/audio
mp3/decoder.go
Next
func (d *Decoder) Next(f *Frame) error { if f == nil { return fmt.Errorf("can't decode to a nil Frame") } var n int f.SkippedBytes = 0 f.Counter++ hLen := 4 if f.buf == nil { f.buf = make([]byte, hLen) } else { f.buf = f.buf[:hLen] } _, err := io.ReadAtLeast(d.r, f.buf, hLen) if err != nil { return err } // ID3v1 tag at the beggining if bytes.Compare(f.buf[:3], id3v1.HeaderTagID) == 0 { // the ID3v1 tag is always 128 bytes long, we already read 4 bytes // so we need to read the rest. buf := make([]byte, 124) // TODO: parse the actual header if _, err := io.ReadAtLeast(d.r, buf, 124); err != nil { return ErrInvalidHeader } buf = append(f.buf, buf...) // that wasn't a frame f = &Frame{} return nil } // ID3v2 tag if bytes.Compare(f.buf[:3], id3v2.HeaderTagID) == 0 { d.ID3v2tag = &id3v2.Tag{} // we already read 4 bytes, an id3v2 tag header is of size 10, read the rest // and append it to what we already have. buf := make([]byte, 6) n, err := d.r.Read(buf) if err != nil || n != 6 { return ErrInvalidHeader } buf = append(f.buf, buf...) th := id3v2.TagHeader{} copy(th[:], buf) if err = d.ID3v2tag.ReadHeader(th); err != nil { return err } // TODO: parse the actual tag // Skip the tag for now bytesToSkip := int64(d.ID3v2tag.Header.Size) var cn int64 if cn, err = io.CopyN(ioutil.Discard, d.r, bytesToSkip); cn != bytesToSkip { return ErrInvalidHeader } f = &Frame{} return err } f.Header = FrameHeader(f.buf) if !f.Header.IsValid() { f.Header, n, err = d.skipToNextFrame() if err != nil { return err } f.SkippedBytes = n } dataSize := f.Header.Size() if dataSize > 4 { // substract the 4 bytes we already read dataSize -= 4 f.buf = append(f.buf, make([]byte, dataSize)...) _, err = io.ReadAtLeast(d.r, f.buf[4:], int(dataSize)) } return err }
go
func (d *Decoder) Next(f *Frame) error { if f == nil { return fmt.Errorf("can't decode to a nil Frame") } var n int f.SkippedBytes = 0 f.Counter++ hLen := 4 if f.buf == nil { f.buf = make([]byte, hLen) } else { f.buf = f.buf[:hLen] } _, err := io.ReadAtLeast(d.r, f.buf, hLen) if err != nil { return err } // ID3v1 tag at the beggining if bytes.Compare(f.buf[:3], id3v1.HeaderTagID) == 0 { // the ID3v1 tag is always 128 bytes long, we already read 4 bytes // so we need to read the rest. buf := make([]byte, 124) // TODO: parse the actual header if _, err := io.ReadAtLeast(d.r, buf, 124); err != nil { return ErrInvalidHeader } buf = append(f.buf, buf...) // that wasn't a frame f = &Frame{} return nil } // ID3v2 tag if bytes.Compare(f.buf[:3], id3v2.HeaderTagID) == 0 { d.ID3v2tag = &id3v2.Tag{} // we already read 4 bytes, an id3v2 tag header is of size 10, read the rest // and append it to what we already have. buf := make([]byte, 6) n, err := d.r.Read(buf) if err != nil || n != 6 { return ErrInvalidHeader } buf = append(f.buf, buf...) th := id3v2.TagHeader{} copy(th[:], buf) if err = d.ID3v2tag.ReadHeader(th); err != nil { return err } // TODO: parse the actual tag // Skip the tag for now bytesToSkip := int64(d.ID3v2tag.Header.Size) var cn int64 if cn, err = io.CopyN(ioutil.Discard, d.r, bytesToSkip); cn != bytesToSkip { return ErrInvalidHeader } f = &Frame{} return err } f.Header = FrameHeader(f.buf) if !f.Header.IsValid() { f.Header, n, err = d.skipToNextFrame() if err != nil { return err } f.SkippedBytes = n } dataSize := f.Header.Size() if dataSize > 4 { // substract the 4 bytes we already read dataSize -= 4 f.buf = append(f.buf, make([]byte, dataSize)...) _, err = io.ReadAtLeast(d.r, f.buf[4:], int(dataSize)) } return err }
[ "func", "(", "d", "*", "Decoder", ")", "Next", "(", "f", "*", "Frame", ")", "error", "{", "if", "f", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "n", "int", "\n", "f", ".", "SkippedBytes", "=", "0", "\n", "f", ".", "Counter", "++", "\n\n", "hLen", ":=", "4", "\n", "if", "f", ".", "buf", "==", "nil", "{", "f", ".", "buf", "=", "make", "(", "[", "]", "byte", ",", "hLen", ")", "\n", "}", "else", "{", "f", ".", "buf", "=", "f", ".", "buf", "[", ":", "hLen", "]", "\n", "}", "\n\n", "_", ",", "err", ":=", "io", ".", "ReadAtLeast", "(", "d", ".", "r", ",", "f", ".", "buf", ",", "hLen", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// ID3v1 tag at the beggining", "if", "bytes", ".", "Compare", "(", "f", ".", "buf", "[", ":", "3", "]", ",", "id3v1", ".", "HeaderTagID", ")", "==", "0", "{", "// the ID3v1 tag is always 128 bytes long, we already read 4 bytes", "// so we need to read the rest.", "buf", ":=", "make", "(", "[", "]", "byte", ",", "124", ")", "\n", "// TODO: parse the actual header", "if", "_", ",", "err", ":=", "io", ".", "ReadAtLeast", "(", "d", ".", "r", ",", "buf", ",", "124", ")", ";", "err", "!=", "nil", "{", "return", "ErrInvalidHeader", "\n", "}", "\n", "buf", "=", "append", "(", "f", ".", "buf", ",", "buf", "...", ")", "\n", "// that wasn't a frame", "f", "=", "&", "Frame", "{", "}", "\n", "return", "nil", "\n", "}", "\n\n", "// ID3v2 tag", "if", "bytes", ".", "Compare", "(", "f", ".", "buf", "[", ":", "3", "]", ",", "id3v2", ".", "HeaderTagID", ")", "==", "0", "{", "d", ".", "ID3v2tag", "=", "&", "id3v2", ".", "Tag", "{", "}", "\n", "// we already read 4 bytes, an id3v2 tag header is of size 10, read the rest", "// and append it to what we already have.", "buf", ":=", "make", "(", "[", "]", "byte", ",", "6", ")", "\n", "n", ",", "err", ":=", "d", ".", "r", ".", "Read", "(", "buf", ")", "\n", "if", "err", "!=", "nil", "||", "n", "!=", "6", "{", "return", "ErrInvalidHeader", "\n", "}", "\n", "buf", "=", "append", "(", "f", ".", "buf", ",", "buf", "...", ")", "\n\n", "th", ":=", "id3v2", ".", "TagHeader", "{", "}", "\n", "copy", "(", "th", "[", ":", "]", ",", "buf", ")", "\n", "if", "err", "=", "d", ".", "ID3v2tag", ".", "ReadHeader", "(", "th", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// TODO: parse the actual tag", "// Skip the tag for now", "bytesToSkip", ":=", "int64", "(", "d", ".", "ID3v2tag", ".", "Header", ".", "Size", ")", "\n", "var", "cn", "int64", "\n", "if", "cn", ",", "err", "=", "io", ".", "CopyN", "(", "ioutil", ".", "Discard", ",", "d", ".", "r", ",", "bytesToSkip", ")", ";", "cn", "!=", "bytesToSkip", "{", "return", "ErrInvalidHeader", "\n", "}", "\n", "f", "=", "&", "Frame", "{", "}", "\n", "return", "err", "\n", "}", "\n\n", "f", ".", "Header", "=", "FrameHeader", "(", "f", ".", "buf", ")", "\n", "if", "!", "f", ".", "Header", ".", "IsValid", "(", ")", "{", "f", ".", "Header", ",", "n", ",", "err", "=", "d", ".", "skipToNextFrame", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "f", ".", "SkippedBytes", "=", "n", "\n", "}", "\n\n", "dataSize", ":=", "f", ".", "Header", ".", "Size", "(", ")", "\n", "if", "dataSize", ">", "4", "{", "// substract the 4 bytes we already read", "dataSize", "-=", "4", "\n", "f", ".", "buf", "=", "append", "(", "f", ".", "buf", ",", "make", "(", "[", "]", "byte", ",", "dataSize", ")", "...", ")", "\n", "_", ",", "err", "=", "io", ".", "ReadAtLeast", "(", "d", ".", "r", ",", "f", ".", "buf", "[", "4", ":", "]", ",", "int", "(", "dataSize", ")", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Next decodes the next frame into the provided frame structure.
[ "Next", "decodes", "the", "next", "frame", "into", "the", "provided", "frame", "structure", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/mp3/decoder.go#L113-L194
12,260
mattetti/audio
mp3/decoder.go
skipToNextFrame
func (d *Decoder) skipToNextFrame() (fh FrameHeader, readN int, err error) { if d == nil { return nil, readN, errors.New("nil decoder") } buf := make([]byte, 1) lookAheadBuf := make([]byte, 1) var n int for { n, err = d.r.Read(buf) readN += n if err != nil { return nil, readN, err } readN++ if buf[0] == 0xFF { if _, err := d.r.Read(lookAheadBuf); err != nil { return nil, readN, err } readN++ if lookAheadBuf[0]&0xE0 == 0xE0 { buf = []byte{0xff, lookAheadBuf[0], 0, 0} n, err := d.r.Read(buf[2:]) if err != nil { return nil, readN + n, err } if n != 2 { return nil, readN + n, io.ErrUnexpectedEOF } readN += 2 } return buf, readN, err } } }
go
func (d *Decoder) skipToNextFrame() (fh FrameHeader, readN int, err error) { if d == nil { return nil, readN, errors.New("nil decoder") } buf := make([]byte, 1) lookAheadBuf := make([]byte, 1) var n int for { n, err = d.r.Read(buf) readN += n if err != nil { return nil, readN, err } readN++ if buf[0] == 0xFF { if _, err := d.r.Read(lookAheadBuf); err != nil { return nil, readN, err } readN++ if lookAheadBuf[0]&0xE0 == 0xE0 { buf = []byte{0xff, lookAheadBuf[0], 0, 0} n, err := d.r.Read(buf[2:]) if err != nil { return nil, readN + n, err } if n != 2 { return nil, readN + n, io.ErrUnexpectedEOF } readN += 2 } return buf, readN, err } } }
[ "func", "(", "d", "*", "Decoder", ")", "skipToNextFrame", "(", ")", "(", "fh", "FrameHeader", ",", "readN", "int", ",", "err", "error", ")", "{", "if", "d", "==", "nil", "{", "return", "nil", ",", "readN", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "1", ")", "\n", "lookAheadBuf", ":=", "make", "(", "[", "]", "byte", ",", "1", ")", "\n", "var", "n", "int", "\n", "for", "{", "n", ",", "err", "=", "d", ".", "r", ".", "Read", "(", "buf", ")", "\n", "readN", "+=", "n", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "readN", ",", "err", "\n", "}", "\n", "readN", "++", "\n", "if", "buf", "[", "0", "]", "==", "0xFF", "{", "if", "_", ",", "err", ":=", "d", ".", "r", ".", "Read", "(", "lookAheadBuf", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "readN", ",", "err", "\n", "}", "\n", "readN", "++", "\n", "if", "lookAheadBuf", "[", "0", "]", "&", "0xE0", "==", "0xE0", "{", "buf", "=", "[", "]", "byte", "{", "0xff", ",", "lookAheadBuf", "[", "0", "]", ",", "0", ",", "0", "}", "\n", "n", ",", "err", ":=", "d", ".", "r", ".", "Read", "(", "buf", "[", "2", ":", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "readN", "+", "n", ",", "err", "\n", "}", "\n", "if", "n", "!=", "2", "{", "return", "nil", ",", "readN", "+", "n", ",", "io", ".", "ErrUnexpectedEOF", "\n", "}", "\n", "readN", "+=", "2", "\n", "}", "\n", "return", "buf", ",", "readN", ",", "err", "\n", "}", "\n", "}", "\n", "}" ]
// skipToSyncWord reads until it finds a frame header
[ "skipToSyncWord", "reads", "until", "it", "finds", "a", "frame", "header" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/mp3/decoder.go#L197-L230
12,261
mattetti/audio
midi/encoder.go
Write
func (e *Encoder) Write() error { if e == nil { return errors.New("Can't write a nil encoder") } e.writeHeaders() for _, t := range e.Tracks { if err := e.encodeTrack(t); err != nil { return err } } // go back and update body size in header return nil }
go
func (e *Encoder) Write() error { if e == nil { return errors.New("Can't write a nil encoder") } e.writeHeaders() for _, t := range e.Tracks { if err := e.encodeTrack(t); err != nil { return err } } // go back and update body size in header return nil }
[ "func", "(", "e", "*", "Encoder", ")", "Write", "(", ")", "error", "{", "if", "e", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "e", ".", "writeHeaders", "(", ")", "\n", "for", "_", ",", "t", ":=", "range", "e", ".", "Tracks", "{", "if", "err", ":=", "e", ".", "encodeTrack", "(", "t", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "// go back and update body size in header", "return", "nil", "\n", "}" ]
// Write writes the binary representation to the writer
[ "Write", "writes", "the", "binary", "representation", "to", "the", "writer" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/encoder.go#L69-L81
12,262
mattetti/audio
caf/decoder.go
ReadInfo
func (d *Decoder) ReadInfo() error { if d == nil || d.SampleRate > 0 { return nil } if d.err = d.readHeaders(); d.err != nil { d.err = fmt.Errorf("failed to read header - %v", d.err) return d.err } var chk *chunk.Reader var err error for err == nil { chk, err = d.NextChunk() if err != nil { break } switch chk.ID { case AudioDataChunkID: d.AudioDataSize = int64(chk.Size) // TODO: // editCount uint32 // The modification status of the data section. You should initially set this field to 0, and should increment it each time the audio data in the file is modified. // the rest of the data is the actual audio data. case InfoStringsChunkID: strChunk := &stringsChunk{stringID: map[string]string{}} if err = chk.ReadBE(&strChunk.numEntries); err != nil { return fmt.Errorf("failed to read the info strings chunk data - %v", err) } if strChunk.numEntries > 0 { for i := uint32(0); i < strChunk.numEntries; i++ { // read key(max 32 bytes) + data (max 1024) both null delimited. // TODO: this is terrible for performance reasons. Read the entire chunk in memory for that. key := []byte{} var b byte msg := []byte{} var msgB byte for j := 0; j < 32; j++ { b, err = chk.ReadByte() if err != nil { break } // end of key? if b == 0x0 { for k := 0; k < 1024; k++ { msgB, err = chk.ReadByte() if err != nil { break } // message terminated if msgB == 0x0 { break } msg = append(msg, msgB) } break } key = append(key, b) } if len(key) > 0 { strChunk.stringID[string(key)] = string(msg) } } for k, v := range strChunk.stringID { fmt.Printf("%s -> %s\n", k, v) } } // kuki // The Magic Cookie chunk contains supplementary (“magic cookie”) data required by certain audio data formats, such as MPEG-4 AAC, for decoding of the audio data. If the audio data format contained in a CAF file requires magic cookie data, the file must have this chunk. // https://developer.apple.com/library/content/documentation/MusicAudio/Reference/CAFSpec/CAF_spec/CAF_spec.html#//apple_ref/doc/uid/TP40001862-CH210-BCGFCCFA // strg // The optional Strings chunk contains any number of textual // strings, along with an index for accessing them. These strings serve // as labels for other chunks, such as Marker or Region chunks. // free // The optional Free chunk is for reserving space, or providing // padding, in a CAF file. The contents of the Free chunk data section // have no significance and should be ignored. // info // You can use the optional Information chunk to contain any number // of human-readable text strings. Each string is accessed through a // standard or application-defined key. You should consider information // in this chunk to be secondary when the same information appears in // other chunks. For example, both the Information chunk and the MIDI // chunk (MIDI Chunk) may specify key signature and tempo. In that case, // the MIDI chunk values overrides the values in the Information chunk. // uuid // // You can define your own chunk type to extend the CAF file // specification. For this purpose, this specification includes the // User-Defined chunk type, which you can use to provide a unique // universal identifier for your custom chunk. When parsing a CAF file, // you should ignore any chunk with a UUID that you do not recognize. // ovvw // // You can use the optional Overview chunk to hold sample descriptions // that you can use to draw a graphical view of the audio data in a CAF // file. A CAF file can include multiple Overview chunks to represent // the audio at multiple graphical resolutions. // peak // // You can use the optional Peak chunk to describe the peak amplitude // present in each channel of a CAF file and to indicate in which frame // the peak occurs for each channel. } chk.Done() } if d.err == nil && d.err != nil { d.err = err } return d.Err() }
go
func (d *Decoder) ReadInfo() error { if d == nil || d.SampleRate > 0 { return nil } if d.err = d.readHeaders(); d.err != nil { d.err = fmt.Errorf("failed to read header - %v", d.err) return d.err } var chk *chunk.Reader var err error for err == nil { chk, err = d.NextChunk() if err != nil { break } switch chk.ID { case AudioDataChunkID: d.AudioDataSize = int64(chk.Size) // TODO: // editCount uint32 // The modification status of the data section. You should initially set this field to 0, and should increment it each time the audio data in the file is modified. // the rest of the data is the actual audio data. case InfoStringsChunkID: strChunk := &stringsChunk{stringID: map[string]string{}} if err = chk.ReadBE(&strChunk.numEntries); err != nil { return fmt.Errorf("failed to read the info strings chunk data - %v", err) } if strChunk.numEntries > 0 { for i := uint32(0); i < strChunk.numEntries; i++ { // read key(max 32 bytes) + data (max 1024) both null delimited. // TODO: this is terrible for performance reasons. Read the entire chunk in memory for that. key := []byte{} var b byte msg := []byte{} var msgB byte for j := 0; j < 32; j++ { b, err = chk.ReadByte() if err != nil { break } // end of key? if b == 0x0 { for k := 0; k < 1024; k++ { msgB, err = chk.ReadByte() if err != nil { break } // message terminated if msgB == 0x0 { break } msg = append(msg, msgB) } break } key = append(key, b) } if len(key) > 0 { strChunk.stringID[string(key)] = string(msg) } } for k, v := range strChunk.stringID { fmt.Printf("%s -> %s\n", k, v) } } // kuki // The Magic Cookie chunk contains supplementary (“magic cookie”) data required by certain audio data formats, such as MPEG-4 AAC, for decoding of the audio data. If the audio data format contained in a CAF file requires magic cookie data, the file must have this chunk. // https://developer.apple.com/library/content/documentation/MusicAudio/Reference/CAFSpec/CAF_spec/CAF_spec.html#//apple_ref/doc/uid/TP40001862-CH210-BCGFCCFA // strg // The optional Strings chunk contains any number of textual // strings, along with an index for accessing them. These strings serve // as labels for other chunks, such as Marker or Region chunks. // free // The optional Free chunk is for reserving space, or providing // padding, in a CAF file. The contents of the Free chunk data section // have no significance and should be ignored. // info // You can use the optional Information chunk to contain any number // of human-readable text strings. Each string is accessed through a // standard or application-defined key. You should consider information // in this chunk to be secondary when the same information appears in // other chunks. For example, both the Information chunk and the MIDI // chunk (MIDI Chunk) may specify key signature and tempo. In that case, // the MIDI chunk values overrides the values in the Information chunk. // uuid // // You can define your own chunk type to extend the CAF file // specification. For this purpose, this specification includes the // User-Defined chunk type, which you can use to provide a unique // universal identifier for your custom chunk. When parsing a CAF file, // you should ignore any chunk with a UUID that you do not recognize. // ovvw // // You can use the optional Overview chunk to hold sample descriptions // that you can use to draw a graphical view of the audio data in a CAF // file. A CAF file can include multiple Overview chunks to represent // the audio at multiple graphical resolutions. // peak // // You can use the optional Peak chunk to describe the peak amplitude // present in each channel of a CAF file and to indicate in which frame // the peak occurs for each channel. } chk.Done() } if d.err == nil && d.err != nil { d.err = err } return d.Err() }
[ "func", "(", "d", "*", "Decoder", ")", "ReadInfo", "(", ")", "error", "{", "if", "d", "==", "nil", "||", "d", ".", "SampleRate", ">", "0", "{", "return", "nil", "\n", "}", "\n", "if", "d", ".", "err", "=", "d", ".", "readHeaders", "(", ")", ";", "d", ".", "err", "!=", "nil", "{", "d", ".", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "d", ".", "err", ")", "\n", "return", "d", ".", "err", "\n", "}", "\n\n", "var", "chk", "*", "chunk", ".", "Reader", "\n", "var", "err", "error", "\n", "for", "err", "==", "nil", "{", "chk", ",", "err", "=", "d", ".", "NextChunk", "(", ")", "\n", "if", "err", "!=", "nil", "{", "break", "\n", "}", "\n", "switch", "chk", ".", "ID", "{", "case", "AudioDataChunkID", ":", "d", ".", "AudioDataSize", "=", "int64", "(", "chk", ".", "Size", ")", "\n", "// TODO:", "// editCount uint32", "// The modification status of the data section. You should initially set this field to 0, and should increment it each time the audio data in the file is modified.", "// the rest of the data is the actual audio data.", "case", "InfoStringsChunkID", ":", "strChunk", ":=", "&", "stringsChunk", "{", "stringID", ":", "map", "[", "string", "]", "string", "{", "}", "}", "\n", "if", "err", "=", "chk", ".", "ReadBE", "(", "&", "strChunk", ".", "numEntries", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "strChunk", ".", "numEntries", ">", "0", "{", "for", "i", ":=", "uint32", "(", "0", ")", ";", "i", "<", "strChunk", ".", "numEntries", ";", "i", "++", "{", "// read key(max 32 bytes) + data (max 1024) both null delimited.", "// TODO: this is terrible for performance reasons. Read the entire chunk in memory for that.", "key", ":=", "[", "]", "byte", "{", "}", "\n", "var", "b", "byte", "\n", "msg", ":=", "[", "]", "byte", "{", "}", "\n", "var", "msgB", "byte", "\n", "for", "j", ":=", "0", ";", "j", "<", "32", ";", "j", "++", "{", "b", ",", "err", "=", "chk", ".", "ReadByte", "(", ")", "\n", "if", "err", "!=", "nil", "{", "break", "\n", "}", "\n", "// end of key?", "if", "b", "==", "0x0", "{", "for", "k", ":=", "0", ";", "k", "<", "1024", ";", "k", "++", "{", "msgB", ",", "err", "=", "chk", ".", "ReadByte", "(", ")", "\n", "if", "err", "!=", "nil", "{", "break", "\n", "}", "\n", "// message terminated", "if", "msgB", "==", "0x0", "{", "break", "\n", "}", "\n", "msg", "=", "append", "(", "msg", ",", "msgB", ")", "\n", "}", "\n", "break", "\n", "}", "\n", "key", "=", "append", "(", "key", ",", "b", ")", "\n", "}", "\n", "if", "len", "(", "key", ")", ">", "0", "{", "strChunk", ".", "stringID", "[", "string", "(", "key", ")", "]", "=", "string", "(", "msg", ")", "\n", "}", "\n", "}", "\n\n", "for", "k", ",", "v", ":=", "range", "strChunk", ".", "stringID", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "k", ",", "v", ")", "\n", "}", "\n", "}", "\n\n", "// kuki", "// The Magic Cookie chunk contains supplementary (“magic cookie”) data required by certain audio data formats, such as MPEG-4 AAC, for decoding of the audio data. If the audio data format contained in a CAF file requires magic cookie data, the file must have this chunk.", "// https://developer.apple.com/library/content/documentation/MusicAudio/Reference/CAFSpec/CAF_spec/CAF_spec.html#//apple_ref/doc/uid/TP40001862-CH210-BCGFCCFA", "// strg", "// The optional Strings chunk contains any number of textual", "// strings, along with an index for accessing them. These strings serve", "// as labels for other chunks, such as Marker or Region chunks.", "// free", "// The optional Free chunk is for reserving space, or providing", "// padding, in a CAF file. The contents of the Free chunk data section", "// have no significance and should be ignored.", "// info", "// You can use the optional Information chunk to contain any number", "// of human-readable text strings. Each string is accessed through a", "// standard or application-defined key. You should consider information", "// in this chunk to be secondary when the same information appears in", "// other chunks. For example, both the Information chunk and the MIDI", "// chunk (MIDI Chunk) may specify key signature and tempo. In that case,", "// the MIDI chunk values overrides the values in the Information chunk.", "// uuid", "//", "// You can define your own chunk type to extend the CAF file", "// specification. For this purpose, this specification includes the", "// User-Defined chunk type, which you can use to provide a unique", "// universal identifier for your custom chunk. When parsing a CAF file,", "// you should ignore any chunk with a UUID that you do not recognize.", "// ovvw", "//", "// You can use the optional Overview chunk to hold sample descriptions", "// that you can use to draw a graphical view of the audio data in a CAF", "// file. A CAF file can include multiple Overview chunks to represent", "// the audio at multiple graphical resolutions.", "// peak", "//", "// You can use the optional Peak chunk to describe the peak amplitude", "// present in each channel of a CAF file and to indicate in which frame", "// the peak occurs for each channel.", "}", "\n", "chk", ".", "Done", "(", ")", "\n", "}", "\n\n", "if", "d", ".", "err", "==", "nil", "&&", "d", ".", "err", "!=", "nil", "{", "d", ".", "err", "=", "err", "\n", "}", "\n", "return", "d", ".", "Err", "(", ")", "\n", "}" ]
// ReadInfo reads the underlying reader finds the data it needs. // This method is safe to call multiple times.
[ "ReadInfo", "reads", "the", "underlying", "reader", "finds", "the", "data", "it", "needs", ".", "This", "method", "is", "safe", "to", "call", "multiple", "times", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/caf/decoder.go#L98-L217
12,263
mattetti/audio
caf/decoder.go
parseDescChunk
func (d *Decoder) parseDescChunk() error { if err := d.Read(&d.SampleRate); err != nil { return err } if err := d.Read(&d.FormatID); err != nil { return err } if err := d.Read(&d.FormatFlags); err != nil { return err } if err := d.Read(&d.BytesPerPacket); err != nil { return err } if err := d.Read(&d.FramesPerPacket); err != nil { return err } if err := d.Read(&d.ChannelsPerFrame); err != nil { return err } if err := d.Read(&d.BitsPerChannel); err != nil { return err } return nil }
go
func (d *Decoder) parseDescChunk() error { if err := d.Read(&d.SampleRate); err != nil { return err } if err := d.Read(&d.FormatID); err != nil { return err } if err := d.Read(&d.FormatFlags); err != nil { return err } if err := d.Read(&d.BytesPerPacket); err != nil { return err } if err := d.Read(&d.FramesPerPacket); err != nil { return err } if err := d.Read(&d.ChannelsPerFrame); err != nil { return err } if err := d.Read(&d.BitsPerChannel); err != nil { return err } return nil }
[ "func", "(", "d", "*", "Decoder", ")", "parseDescChunk", "(", ")", "error", "{", "if", "err", ":=", "d", ".", "Read", "(", "&", "d", ".", "SampleRate", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "d", ".", "Read", "(", "&", "d", ".", "FormatID", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "d", ".", "Read", "(", "&", "d", ".", "FormatFlags", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "d", ".", "Read", "(", "&", "d", ".", "BytesPerPacket", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "d", ".", "Read", "(", "&", "d", ".", "FramesPerPacket", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "d", ".", "Read", "(", "&", "d", ".", "ChannelsPerFrame", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "d", ".", "Read", "(", "&", "d", ".", "BitsPerChannel", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// parseDescChunk parses the first chunk called description chunk.
[ "parseDescChunk", "parses", "the", "first", "chunk", "called", "description", "chunk", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/caf/decoder.go#L286-L310
12,264
mattetti/audio
transforms/presenters/gnuplot.go
GnuplotBin
func GnuplotBin(buf *audio.PCMBuffer, path string) error { if buf == nil || buf.Format == nil { return audio.ErrInvalidBuffer } out, err := os.Create(path) if err != nil { return err } defer out.Close() for _, s := range buf.AsFloat32s() { if err = binary.Write(out, binary.BigEndian, s); err != nil { break } } return err }
go
func GnuplotBin(buf *audio.PCMBuffer, path string) error { if buf == nil || buf.Format == nil { return audio.ErrInvalidBuffer } out, err := os.Create(path) if err != nil { return err } defer out.Close() for _, s := range buf.AsFloat32s() { if err = binary.Write(out, binary.BigEndian, s); err != nil { break } } return err }
[ "func", "GnuplotBin", "(", "buf", "*", "audio", ".", "PCMBuffer", ",", "path", "string", ")", "error", "{", "if", "buf", "==", "nil", "||", "buf", ".", "Format", "==", "nil", "{", "return", "audio", ".", "ErrInvalidBuffer", "\n", "}", "\n", "out", ",", "err", ":=", "os", ".", "Create", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "out", ".", "Close", "(", ")", "\n", "for", "_", ",", "s", ":=", "range", "buf", ".", "AsFloat32s", "(", ")", "{", "if", "err", "=", "binary", ".", "Write", "(", "out", ",", "binary", ".", "BigEndian", ",", "s", ")", ";", "err", "!=", "nil", "{", "break", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// GnuplotBin exports the buffer content as a binary gnuplot file.
[ "GnuplotBin", "exports", "the", "buffer", "content", "as", "a", "binary", "gnuplot", "file", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/transforms/presenters/gnuplot.go#L12-L27
12,265
mattetti/audio
decoder/decoder.go
FileFormat
func FileFormat(path string) (Format, error) { if !fileExists(path) { return "", ErrInvalidPath } f, err := os.Open(path) if err != nil { return "", err } defer f.Close() var triedWav bool var triedAif bool ext := strings.ToLower(filepath.Ext(path)) switch ext { case ".wav", ".wave": triedWav = true d := wav.NewDecoder(f) if d.IsValidFile() { return Wav, nil } case ".aif", ".aiff": triedAif = true d := aiff.NewDecoder(f) if d.IsValidFile() { return Aif, nil } } // extension doesn't match, let's try again f.Seek(0, 0) if !triedWav { wd := wav.NewDecoder(f) if wd.IsValidFile() { return Wav, nil } f.Seek(0, 0) } if !triedAif { ad := aiff.NewDecoder(f) if ad.IsValidFile() { return Aif, nil } } return Unknown, nil }
go
func FileFormat(path string) (Format, error) { if !fileExists(path) { return "", ErrInvalidPath } f, err := os.Open(path) if err != nil { return "", err } defer f.Close() var triedWav bool var triedAif bool ext := strings.ToLower(filepath.Ext(path)) switch ext { case ".wav", ".wave": triedWav = true d := wav.NewDecoder(f) if d.IsValidFile() { return Wav, nil } case ".aif", ".aiff": triedAif = true d := aiff.NewDecoder(f) if d.IsValidFile() { return Aif, nil } } // extension doesn't match, let's try again f.Seek(0, 0) if !triedWav { wd := wav.NewDecoder(f) if wd.IsValidFile() { return Wav, nil } f.Seek(0, 0) } if !triedAif { ad := aiff.NewDecoder(f) if ad.IsValidFile() { return Aif, nil } } return Unknown, nil }
[ "func", "FileFormat", "(", "path", "string", ")", "(", "Format", ",", "error", ")", "{", "if", "!", "fileExists", "(", "path", ")", "{", "return", "\"", "\"", ",", "ErrInvalidPath", "\n", "}", "\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "var", "triedWav", "bool", "\n", "var", "triedAif", "bool", "\n\n", "ext", ":=", "strings", ".", "ToLower", "(", "filepath", ".", "Ext", "(", "path", ")", ")", "\n", "switch", "ext", "{", "case", "\"", "\"", ",", "\"", "\"", ":", "triedWav", "=", "true", "\n", "d", ":=", "wav", ".", "NewDecoder", "(", "f", ")", "\n", "if", "d", ".", "IsValidFile", "(", ")", "{", "return", "Wav", ",", "nil", "\n", "}", "\n", "case", "\"", "\"", ",", "\"", "\"", ":", "triedAif", "=", "true", "\n", "d", ":=", "aiff", ".", "NewDecoder", "(", "f", ")", "\n", "if", "d", ".", "IsValidFile", "(", ")", "{", "return", "Aif", ",", "nil", "\n", "}", "\n", "}", "\n", "// extension doesn't match, let's try again", "f", ".", "Seek", "(", "0", ",", "0", ")", "\n", "if", "!", "triedWav", "{", "wd", ":=", "wav", ".", "NewDecoder", "(", "f", ")", "\n", "if", "wd", ".", "IsValidFile", "(", ")", "{", "return", "Wav", ",", "nil", "\n", "}", "\n", "f", ".", "Seek", "(", "0", ",", "0", ")", "\n", "}", "\n", "if", "!", "triedAif", "{", "ad", ":=", "aiff", ".", "NewDecoder", "(", "f", ")", "\n", "if", "ad", ".", "IsValidFile", "(", ")", "{", "return", "Aif", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "Unknown", ",", "nil", "\n", "}" ]
// FileFormat returns the known format of the passed path.
[ "FileFormat", "returns", "the", "known", "format", "of", "the", "passed", "path", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/decoder/decoder.go#L38-L81
12,266
mattetti/audio
riff/riff.go
New
func New(r io.Reader) *Parser { return &Parser{r: r, Wg: &sync.WaitGroup{}} }
go
func New(r io.Reader) *Parser { return &Parser{r: r, Wg: &sync.WaitGroup{}} }
[ "func", "New", "(", "r", "io", ".", "Reader", ")", "*", "Parser", "{", "return", "&", "Parser", "{", "r", ":", "r", ",", "Wg", ":", "&", "sync", ".", "WaitGroup", "{", "}", "}", "\n", "}" ]
// New creates a parser wrapper for a reader. // Note that the reader doesn't get rewinded as the container is processed.
[ "New", "creates", "a", "parser", "wrapper", "for", "a", "reader", ".", "Note", "that", "the", "reader", "doesn", "t", "get", "rewinded", "as", "the", "container", "is", "processed", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/riff/riff.go#L30-L32
12,267
mattetti/audio
riff/riff.go
Duration
func Duration(r io.Reader) (time.Duration, error) { c := New(r) if err := c.ParseHeaders(); err != nil { return 0, err } return c.Duration() }
go
func Duration(r io.Reader) (time.Duration, error) { c := New(r) if err := c.ParseHeaders(); err != nil { return 0, err } return c.Duration() }
[ "func", "Duration", "(", "r", "io", ".", "Reader", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "c", ":=", "New", "(", "r", ")", "\n", "if", "err", ":=", "c", ".", "ParseHeaders", "(", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "c", ".", "Duration", "(", ")", "\n", "}" ]
// Duration returns the time duration of the passed reader if the sub format is supported.
[ "Duration", "returns", "the", "time", "duration", "of", "the", "passed", "reader", "if", "the", "sub", "format", "is", "supported", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/riff/riff.go#L35-L41
12,268
mattetti/audio
mp3/id3v2/tag_header.go
ReadVersion
func (th TagHeader) ReadVersion() Version { return Version{ Major: uint8(th[3]), Revision: uint8(th[4]), } }
go
func (th TagHeader) ReadVersion() Version { return Version{ Major: uint8(th[3]), Revision: uint8(th[4]), } }
[ "func", "(", "th", "TagHeader", ")", "ReadVersion", "(", ")", "Version", "{", "return", "Version", "{", "Major", ":", "uint8", "(", "th", "[", "3", "]", ")", ",", "Revision", ":", "uint8", "(", "th", "[", "4", "]", ")", ",", "}", "\n", "}" ]
// ReadVersion extracts the version information.
[ "ReadVersion", "extracts", "the", "version", "information", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/mp3/id3v2/tag_header.go#L14-L19
12,269
mattetti/audio
mp3/id3v2/tag_header.go
ReadFlags
func (th TagHeader) ReadFlags() Flags { flags := Flags{} flags.Unsynchronisation = (th[5] & (1 << 0)) != 0 // 3.1.a flags.ExtendedHeader = (th[5] & (1 << 1)) != 0 // 3.1.b flags.ExperimentalIndicator = (th[5] & (1 << 2)) != 0 // 3.1.c flags.FooterPresent = (th[5] & (1 << 3)) != 0 // 3.1.d return flags }
go
func (th TagHeader) ReadFlags() Flags { flags := Flags{} flags.Unsynchronisation = (th[5] & (1 << 0)) != 0 // 3.1.a flags.ExtendedHeader = (th[5] & (1 << 1)) != 0 // 3.1.b flags.ExperimentalIndicator = (th[5] & (1 << 2)) != 0 // 3.1.c flags.FooterPresent = (th[5] & (1 << 3)) != 0 // 3.1.d return flags }
[ "func", "(", "th", "TagHeader", ")", "ReadFlags", "(", ")", "Flags", "{", "flags", ":=", "Flags", "{", "}", "\n", "flags", ".", "Unsynchronisation", "=", "(", "th", "[", "5", "]", "&", "(", "1", "<<", "0", ")", ")", "!=", "0", "// 3.1.a", "\n", "flags", ".", "ExtendedHeader", "=", "(", "th", "[", "5", "]", "&", "(", "1", "<<", "1", ")", ")", "!=", "0", "// 3.1.b", "\n", "flags", ".", "ExperimentalIndicator", "=", "(", "th", "[", "5", "]", "&", "(", "1", "<<", "2", ")", ")", "!=", "0", "// 3.1.c", "\n", "flags", ".", "FooterPresent", "=", "(", "th", "[", "5", "]", "&", "(", "1", "<<", "3", ")", ")", "!=", "0", "// 3.1.d", "\n\n", "return", "flags", "\n", "}" ]
// ReadFlags reads the header flags
[ "ReadFlags", "reads", "the", "header", "flags" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/mp3/id3v2/tag_header.go#L22-L30
12,270
mattetti/audio
dsp/filters/fir.go
LowPass
func (f *FIR) LowPass(input []float64) ([]float64, error) { return f.Convolve(input, f.Sinc.LowPassCoefs()) }
go
func (f *FIR) LowPass(input []float64) ([]float64, error) { return f.Convolve(input, f.Sinc.LowPassCoefs()) }
[ "func", "(", "f", "*", "FIR", ")", "LowPass", "(", "input", "[", "]", "float64", ")", "(", "[", "]", "float64", ",", "error", ")", "{", "return", "f", ".", "Convolve", "(", "input", ",", "f", ".", "Sinc", ".", "LowPassCoefs", "(", ")", ")", "\n", "}" ]
// LowPass applies a low pass filter using the FIR
[ "LowPass", "applies", "a", "low", "pass", "filter", "using", "the", "FIR" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/dsp/filters/fir.go#L12-L14
12,271
mattetti/audio
dsp/filters/fir.go
Convolve
func (f *FIR) Convolve(input, kernels []float64) ([]float64, error) { if f == nil { return nil, nil } if !(len(input) > len(kernels)) { return nil, fmt.Errorf("provided data set is not greater than the filter weights") } output := make([]float64, len(input)) for i := 0; i < len(kernels); i++ { var sum float64 for j := 0; j < i; j++ { sum += (input[j] * kernels[len(kernels)-(1+i-j)]) } output[i] = sum } for i := len(kernels); i < len(input); i++ { var sum float64 for j := 0; j < len(kernels); j++ { sum += (input[i-j] * kernels[j]) } output[i] = sum } return output, nil }
go
func (f *FIR) Convolve(input, kernels []float64) ([]float64, error) { if f == nil { return nil, nil } if !(len(input) > len(kernels)) { return nil, fmt.Errorf("provided data set is not greater than the filter weights") } output := make([]float64, len(input)) for i := 0; i < len(kernels); i++ { var sum float64 for j := 0; j < i; j++ { sum += (input[j] * kernels[len(kernels)-(1+i-j)]) } output[i] = sum } for i := len(kernels); i < len(input); i++ { var sum float64 for j := 0; j < len(kernels); j++ { sum += (input[i-j] * kernels[j]) } output[i] = sum } return output, nil }
[ "func", "(", "f", "*", "FIR", ")", "Convolve", "(", "input", ",", "kernels", "[", "]", "float64", ")", "(", "[", "]", "float64", ",", "error", ")", "{", "if", "f", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "if", "!", "(", "len", "(", "input", ")", ">", "len", "(", "kernels", ")", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "output", ":=", "make", "(", "[", "]", "float64", ",", "len", "(", "input", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "kernels", ")", ";", "i", "++", "{", "var", "sum", "float64", "\n\n", "for", "j", ":=", "0", ";", "j", "<", "i", ";", "j", "++", "{", "sum", "+=", "(", "input", "[", "j", "]", "*", "kernels", "[", "len", "(", "kernels", ")", "-", "(", "1", "+", "i", "-", "j", ")", "]", ")", "\n", "}", "\n", "output", "[", "i", "]", "=", "sum", "\n", "}", "\n\n", "for", "i", ":=", "len", "(", "kernels", ")", ";", "i", "<", "len", "(", "input", ")", ";", "i", "++", "{", "var", "sum", "float64", "\n", "for", "j", ":=", "0", ";", "j", "<", "len", "(", "kernels", ")", ";", "j", "++", "{", "sum", "+=", "(", "input", "[", "i", "-", "j", "]", "*", "kernels", "[", "j", "]", ")", "\n", "}", "\n", "output", "[", "i", "]", "=", "sum", "\n", "}", "\n\n", "return", "output", ",", "nil", "\n", "}" ]
// Convolve "mixes" two signals together // kernels is the imput that is not part of our signal, it might be shorter // than the origin signal.
[ "Convolve", "mixes", "two", "signals", "together", "kernels", "is", "the", "imput", "that", "is", "not", "part", "of", "our", "signal", "it", "might", "be", "shorter", "than", "the", "origin", "signal", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/dsp/filters/fir.go#L23-L50
12,272
mattetti/audio
dsp/analysis/min_max.go
MinMaxFloat
func MinMaxFloat(buf *audio.PCMBuffer) (min, max float64) { if buf == nil || buf.Len() == 0 { return 0, 0 } buf.SwitchPrimaryType(audio.Float) min = buf.Floats[0] for _, v := range buf.Floats { if v > max { max = v } else if v < min { min = v } } return min, max }
go
func MinMaxFloat(buf *audio.PCMBuffer) (min, max float64) { if buf == nil || buf.Len() == 0 { return 0, 0 } buf.SwitchPrimaryType(audio.Float) min = buf.Floats[0] for _, v := range buf.Floats { if v > max { max = v } else if v < min { min = v } } return min, max }
[ "func", "MinMaxFloat", "(", "buf", "*", "audio", ".", "PCMBuffer", ")", "(", "min", ",", "max", "float64", ")", "{", "if", "buf", "==", "nil", "||", "buf", ".", "Len", "(", ")", "==", "0", "{", "return", "0", ",", "0", "\n", "}", "\n", "buf", ".", "SwitchPrimaryType", "(", "audio", ".", "Float", ")", "\n", "min", "=", "buf", ".", "Floats", "[", "0", "]", "\n\n", "for", "_", ",", "v", ":=", "range", "buf", ".", "Floats", "{", "if", "v", ">", "max", "{", "max", "=", "v", "\n", "}", "else", "if", "v", "<", "min", "{", "min", "=", "v", "\n", "}", "\n", "}", "\n\n", "return", "min", ",", "max", "\n", "}" ]
// MinMaxFloat returns the smallest and biggest samples in the buffer
[ "MinMaxFloat", "returns", "the", "smallest", "and", "biggest", "samples", "in", "the", "buffer" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/dsp/analysis/min_max.go#L6-L22
12,273
mattetti/audio
transforms/mono.go
MonoDownmix
func MonoDownmix(buf *audio.PCMBuffer) error { if buf == nil || buf.Format == nil { return audio.ErrInvalidBuffer } nChans := buf.Format.NumChannels if nChans < 2 { return nil } nChansF := float64(nChans) frameCount := buf.Size() newData := make([]float64, frameCount) buf.SwitchPrimaryType(audio.Float) for i := 0; i < frameCount; i++ { newData[i] = 0 for j := 0; j < nChans; j++ { newData[i] += buf.Floats[i*nChans+j] } newData[i] /= nChansF } buf.Floats = newData buf.Format.NumChannels = 1 return nil }
go
func MonoDownmix(buf *audio.PCMBuffer) error { if buf == nil || buf.Format == nil { return audio.ErrInvalidBuffer } nChans := buf.Format.NumChannels if nChans < 2 { return nil } nChansF := float64(nChans) frameCount := buf.Size() newData := make([]float64, frameCount) buf.SwitchPrimaryType(audio.Float) for i := 0; i < frameCount; i++ { newData[i] = 0 for j := 0; j < nChans; j++ { newData[i] += buf.Floats[i*nChans+j] } newData[i] /= nChansF } buf.Floats = newData buf.Format.NumChannels = 1 return nil }
[ "func", "MonoDownmix", "(", "buf", "*", "audio", ".", "PCMBuffer", ")", "error", "{", "if", "buf", "==", "nil", "||", "buf", ".", "Format", "==", "nil", "{", "return", "audio", ".", "ErrInvalidBuffer", "\n", "}", "\n", "nChans", ":=", "buf", ".", "Format", ".", "NumChannels", "\n", "if", "nChans", "<", "2", "{", "return", "nil", "\n", "}", "\n", "nChansF", ":=", "float64", "(", "nChans", ")", "\n\n", "frameCount", ":=", "buf", ".", "Size", "(", ")", "\n", "newData", ":=", "make", "(", "[", "]", "float64", ",", "frameCount", ")", "\n", "buf", ".", "SwitchPrimaryType", "(", "audio", ".", "Float", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "frameCount", ";", "i", "++", "{", "newData", "[", "i", "]", "=", "0", "\n", "for", "j", ":=", "0", ";", "j", "<", "nChans", ";", "j", "++", "{", "newData", "[", "i", "]", "+=", "buf", ".", "Floats", "[", "i", "*", "nChans", "+", "j", "]", "\n", "}", "\n", "newData", "[", "i", "]", "/=", "nChansF", "\n", "}", "\n", "buf", ".", "Floats", "=", "newData", "\n", "buf", ".", "Format", ".", "NumChannels", "=", "1", "\n\n", "return", "nil", "\n", "}" ]
// MonoDownmix converts the buffer to a mono buffer // by downmixing the channels together.
[ "MonoDownmix", "converts", "the", "buffer", "to", "a", "mono", "buffer", "by", "downmixing", "the", "channels", "together", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/transforms/mono.go#L7-L31
12,274
mattetti/audio
transforms/normalize.go
NormalizeMax
func NormalizeMax(buf *audio.PCMBuffer) { if buf == nil { return } buf.SwitchPrimaryType(audio.Float) max := 0.0 for i := 0; i < buf.Len(); i++ { if math.Abs(buf.Floats[i]) > max { max = math.Abs(buf.Floats[i]) } } if max != 0.0 { for i := 0; i < buf.Len(); i++ { buf.Floats[i] /= max } } }
go
func NormalizeMax(buf *audio.PCMBuffer) { if buf == nil { return } buf.SwitchPrimaryType(audio.Float) max := 0.0 for i := 0; i < buf.Len(); i++ { if math.Abs(buf.Floats[i]) > max { max = math.Abs(buf.Floats[i]) } } if max != 0.0 { for i := 0; i < buf.Len(); i++ { buf.Floats[i] /= max } } }
[ "func", "NormalizeMax", "(", "buf", "*", "audio", ".", "PCMBuffer", ")", "{", "if", "buf", "==", "nil", "{", "return", "\n", "}", "\n", "buf", ".", "SwitchPrimaryType", "(", "audio", ".", "Float", ")", "\n", "max", ":=", "0.0", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "buf", ".", "Len", "(", ")", ";", "i", "++", "{", "if", "math", ".", "Abs", "(", "buf", ".", "Floats", "[", "i", "]", ")", ">", "max", "{", "max", "=", "math", ".", "Abs", "(", "buf", ".", "Floats", "[", "i", "]", ")", "\n", "}", "\n", "}", "\n\n", "if", "max", "!=", "0.0", "{", "for", "i", ":=", "0", ";", "i", "<", "buf", ".", "Len", "(", ")", ";", "i", "++", "{", "buf", ".", "Floats", "[", "i", "]", "/=", "max", "\n", "}", "\n", "}", "\n", "}" ]
// NormalizeMax sets the max value to 1 and normalize the rest of the data.
[ "NormalizeMax", "sets", "the", "max", "value", "to", "1", "and", "normalize", "the", "rest", "of", "the", "data", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/transforms/normalize.go#L10-L28
12,275
mattetti/audio
transforms/pcm_scale.go
PCMScale
func PCMScale(buf *audio.PCMBuffer) error { if buf == nil || buf.Format == nil { return audio.ErrInvalidBuffer } buf.SwitchPrimaryType(audio.Float) factor := float64(audio.IntMaxSignedValue(buf.Format.BitDepth)) for i := 0; i < buf.Len(); i++ { buf.Floats[i] *= factor } return nil }
go
func PCMScale(buf *audio.PCMBuffer) error { if buf == nil || buf.Format == nil { return audio.ErrInvalidBuffer } buf.SwitchPrimaryType(audio.Float) factor := float64(audio.IntMaxSignedValue(buf.Format.BitDepth)) for i := 0; i < buf.Len(); i++ { buf.Floats[i] *= factor } return nil }
[ "func", "PCMScale", "(", "buf", "*", "audio", ".", "PCMBuffer", ")", "error", "{", "if", "buf", "==", "nil", "||", "buf", ".", "Format", "==", "nil", "{", "return", "audio", ".", "ErrInvalidBuffer", "\n", "}", "\n", "buf", ".", "SwitchPrimaryType", "(", "audio", ".", "Float", ")", "\n", "factor", ":=", "float64", "(", "audio", ".", "IntMaxSignedValue", "(", "buf", ".", "Format", ".", "BitDepth", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "buf", ".", "Len", "(", ")", ";", "i", "++", "{", "buf", ".", "Floats", "[", "i", "]", "*=", "factor", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// PCMScale converts a buffer with audio content from -1 to 1 into // the PCM scale based on the buffer's bitdepth.
[ "PCMScale", "converts", "a", "buffer", "with", "audio", "content", "from", "-", "1", "to", "1", "into", "the", "PCM", "scale", "based", "on", "the", "buffer", "s", "bitdepth", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/transforms/pcm_scale.go#L7-L18
12,276
mattetti/audio
generator/generator.go
Sine
func Sine(x32 float64) float64 { x := float64(x32) y := SineB*x + SineC*x*(math.Abs(x)) y = SineP*(y*(math.Abs(y))-y) + y return float64(y) }
go
func Sine(x32 float64) float64 { x := float64(x32) y := SineB*x + SineC*x*(math.Abs(x)) y = SineP*(y*(math.Abs(y))-y) + y return float64(y) }
[ "func", "Sine", "(", "x32", "float64", ")", "float64", "{", "x", ":=", "float64", "(", "x32", ")", "\n", "y", ":=", "SineB", "*", "x", "+", "SineC", "*", "x", "*", "(", "math", ".", "Abs", "(", "x", ")", ")", "\n", "y", "=", "SineP", "*", "(", "y", "*", "(", "math", ".", "Abs", "(", "y", ")", ")", "-", "y", ")", "+", "y", "\n", "return", "float64", "(", "y", ")", "\n", "}" ]
// Sine takes an input value from -Pi to Pi // and returns a value between -1 and 1
[ "Sine", "takes", "an", "input", "value", "from", "-", "Pi", "to", "Pi", "and", "returns", "a", "value", "between", "-", "1", "and", "1" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/generator/generator.go#L28-L33
12,277
mattetti/audio
pcm_buffer.go
NewPCMIntBuffer
func NewPCMIntBuffer(data []int, format *Format) *PCMBuffer { return &PCMBuffer{ Format: format, DataType: Integer, Ints: data, } }
go
func NewPCMIntBuffer(data []int, format *Format) *PCMBuffer { return &PCMBuffer{ Format: format, DataType: Integer, Ints: data, } }
[ "func", "NewPCMIntBuffer", "(", "data", "[", "]", "int", ",", "format", "*", "Format", ")", "*", "PCMBuffer", "{", "return", "&", "PCMBuffer", "{", "Format", ":", "format", ",", "DataType", ":", "Integer", ",", "Ints", ":", "data", ",", "}", "\n", "}" ]
// NewPCMIntBuffer returns a new PCM buffer backed by the passed integer samples
[ "NewPCMIntBuffer", "returns", "a", "new", "PCM", "buffer", "backed", "by", "the", "passed", "integer", "samples" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/pcm_buffer.go#L61-L67
12,278
mattetti/audio
pcm_buffer.go
NewPCMFloatBuffer
func NewPCMFloatBuffer(data []float64, format *Format) *PCMBuffer { return &PCMBuffer{ Format: format, DataType: Float, Floats: data, } }
go
func NewPCMFloatBuffer(data []float64, format *Format) *PCMBuffer { return &PCMBuffer{ Format: format, DataType: Float, Floats: data, } }
[ "func", "NewPCMFloatBuffer", "(", "data", "[", "]", "float64", ",", "format", "*", "Format", ")", "*", "PCMBuffer", "{", "return", "&", "PCMBuffer", "{", "Format", ":", "format", ",", "DataType", ":", "Float", ",", "Floats", ":", "data", ",", "}", "\n", "}" ]
// NewPCMFloatBuffer returns a new PCM buffer backed by the passed float samples
[ "NewPCMFloatBuffer", "returns", "a", "new", "PCM", "buffer", "backed", "by", "the", "passed", "float", "samples" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/pcm_buffer.go#L70-L76
12,279
mattetti/audio
pcm_buffer.go
NewPCMByteBuffer
func NewPCMByteBuffer(data []byte, format *Format) *PCMBuffer { return &PCMBuffer{ Format: format, DataType: Byte, Bytes: data, } }
go
func NewPCMByteBuffer(data []byte, format *Format) *PCMBuffer { return &PCMBuffer{ Format: format, DataType: Byte, Bytes: data, } }
[ "func", "NewPCMByteBuffer", "(", "data", "[", "]", "byte", ",", "format", "*", "Format", ")", "*", "PCMBuffer", "{", "return", "&", "PCMBuffer", "{", "Format", ":", "format", ",", "DataType", ":", "Byte", ",", "Bytes", ":", "data", ",", "}", "\n", "}" ]
// NewPCMByteBuffer returns a new PCM buffer backed by the passed float samples
[ "NewPCMByteBuffer", "returns", "a", "new", "PCM", "buffer", "backed", "by", "the", "passed", "float", "samples" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/pcm_buffer.go#L79-L85
12,280
mattetti/audio
pcm_buffer.go
Size
func (b *PCMBuffer) Size() (numFrames int) { if b == nil || b.Format == nil { return 0 } numChannels := b.Format.NumChannels if numChannels == 0 { numChannels = 1 } switch b.DataType { case Integer: numFrames = len(b.Ints) / numChannels case Float: numFrames = len(b.Floats) / numChannels case Byte: sampleSize := int((b.Format.BitDepth-1)/8 + 1) numFrames = (len(b.Bytes) / sampleSize) / numChannels } return numFrames }
go
func (b *PCMBuffer) Size() (numFrames int) { if b == nil || b.Format == nil { return 0 } numChannels := b.Format.NumChannels if numChannels == 0 { numChannels = 1 } switch b.DataType { case Integer: numFrames = len(b.Ints) / numChannels case Float: numFrames = len(b.Floats) / numChannels case Byte: sampleSize := int((b.Format.BitDepth-1)/8 + 1) numFrames = (len(b.Bytes) / sampleSize) / numChannels } return numFrames }
[ "func", "(", "b", "*", "PCMBuffer", ")", "Size", "(", ")", "(", "numFrames", "int", ")", "{", "if", "b", "==", "nil", "||", "b", ".", "Format", "==", "nil", "{", "return", "0", "\n", "}", "\n", "numChannels", ":=", "b", ".", "Format", ".", "NumChannels", "\n", "if", "numChannels", "==", "0", "{", "numChannels", "=", "1", "\n", "}", "\n", "switch", "b", ".", "DataType", "{", "case", "Integer", ":", "numFrames", "=", "len", "(", "b", ".", "Ints", ")", "/", "numChannels", "\n", "case", "Float", ":", "numFrames", "=", "len", "(", "b", ".", "Floats", ")", "/", "numChannels", "\n", "case", "Byte", ":", "sampleSize", ":=", "int", "(", "(", "b", ".", "Format", ".", "BitDepth", "-", "1", ")", "/", "8", "+", "1", ")", "\n", "numFrames", "=", "(", "len", "(", "b", ".", "Bytes", ")", "/", "sampleSize", ")", "/", "numChannels", "\n", "}", "\n", "return", "numFrames", "\n", "}" ]
// Size returns the number of frames contained in the buffer.
[ "Size", "returns", "the", "number", "of", "frames", "contained", "in", "the", "buffer", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/pcm_buffer.go#L106-L124
12,281
mattetti/audio
pcm_buffer.go
AsInt16s
func (b *PCMBuffer) AsInt16s() (out []int16) { if b == nil { return nil } switch b.DataType { case Integer, Float: out = make([]int16, len(b.Ints)) for i := 0; i < len(b.Ints); i++ { out[i] = int16(b.Ints[i]) } case Byte: // if the format isn't defined, we can't read the byte data if b.Format == nil || b.Format.Endianness == nil || b.Format.BitDepth == 0 { return out } bytesPerSample := int((b.Format.BitDepth-1)/8 + 1) buf := bytes.NewBuffer(b.Bytes) out := make([]int16, len(b.Bytes)/bytesPerSample) binary.Read(buf, b.Format.Endianness, &out) } return out }
go
func (b *PCMBuffer) AsInt16s() (out []int16) { if b == nil { return nil } switch b.DataType { case Integer, Float: out = make([]int16, len(b.Ints)) for i := 0; i < len(b.Ints); i++ { out[i] = int16(b.Ints[i]) } case Byte: // if the format isn't defined, we can't read the byte data if b.Format == nil || b.Format.Endianness == nil || b.Format.BitDepth == 0 { return out } bytesPerSample := int((b.Format.BitDepth-1)/8 + 1) buf := bytes.NewBuffer(b.Bytes) out := make([]int16, len(b.Bytes)/bytesPerSample) binary.Read(buf, b.Format.Endianness, &out) } return out }
[ "func", "(", "b", "*", "PCMBuffer", ")", "AsInt16s", "(", ")", "(", "out", "[", "]", "int16", ")", "{", "if", "b", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "switch", "b", ".", "DataType", "{", "case", "Integer", ",", "Float", ":", "out", "=", "make", "(", "[", "]", "int16", ",", "len", "(", "b", ".", "Ints", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "b", ".", "Ints", ")", ";", "i", "++", "{", "out", "[", "i", "]", "=", "int16", "(", "b", ".", "Ints", "[", "i", "]", ")", "\n", "}", "\n", "case", "Byte", ":", "// if the format isn't defined, we can't read the byte data", "if", "b", ".", "Format", "==", "nil", "||", "b", ".", "Format", ".", "Endianness", "==", "nil", "||", "b", ".", "Format", ".", "BitDepth", "==", "0", "{", "return", "out", "\n", "}", "\n", "bytesPerSample", ":=", "int", "(", "(", "b", ".", "Format", ".", "BitDepth", "-", "1", ")", "/", "8", "+", "1", ")", "\n", "buf", ":=", "bytes", ".", "NewBuffer", "(", "b", ".", "Bytes", ")", "\n", "out", ":=", "make", "(", "[", "]", "int16", ",", "len", "(", "b", ".", "Bytes", ")", "/", "bytesPerSample", ")", "\n", "binary", ".", "Read", "(", "buf", ",", "b", ".", "Format", ".", "Endianness", ",", "&", "out", ")", "\n", "}", "\n", "return", "out", "\n", "}" ]
// AsInt16s returns the buffer samples as int16 sample values.
[ "AsInt16s", "returns", "the", "buffer", "samples", "as", "int16", "sample", "values", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/pcm_buffer.go#L154-L175
12,282
mattetti/audio
generator/osc.go
NewOsc
func NewOsc(shape WaveType, hz float64, fs int) *Osc { return &Osc{Shape: shape, Amplitude: 1, Freq: hz, Fs: fs, phaseAngleIncr: ((hz * TwoPi) / float64(fs))} }
go
func NewOsc(shape WaveType, hz float64, fs int) *Osc { return &Osc{Shape: shape, Amplitude: 1, Freq: hz, Fs: fs, phaseAngleIncr: ((hz * TwoPi) / float64(fs))} }
[ "func", "NewOsc", "(", "shape", "WaveType", ",", "hz", "float64", ",", "fs", "int", ")", "*", "Osc", "{", "return", "&", "Osc", "{", "Shape", ":", "shape", ",", "Amplitude", ":", "1", ",", "Freq", ":", "hz", ",", "Fs", ":", "fs", ",", "phaseAngleIncr", ":", "(", "(", "hz", "*", "TwoPi", ")", "/", "float64", "(", "fs", ")", ")", "}", "\n", "}" ]
// NewOsc returns a new oscillator, note that if you change the phase offset of the returned osc, // you also need to set the CurrentPhaseAngle
[ "NewOsc", "returns", "a", "new", "oscillator", "note", "that", "if", "you", "change", "the", "phase", "offset", "of", "the", "returned", "osc", "you", "also", "need", "to", "set", "the", "CurrentPhaseAngle" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/generator/osc.go#L31-L33
12,283
mattetti/audio
generator/osc.go
Reset
func (o *Osc) Reset() { o.phaseAngleIncr = ((o.Freq * TwoPi) / float64(o.Fs)) o.currentSample = 0 }
go
func (o *Osc) Reset() { o.phaseAngleIncr = ((o.Freq * TwoPi) / float64(o.Fs)) o.currentSample = 0 }
[ "func", "(", "o", "*", "Osc", ")", "Reset", "(", ")", "{", "o", ".", "phaseAngleIncr", "=", "(", "(", "o", ".", "Freq", "*", "TwoPi", ")", "/", "float64", "(", "o", ".", "Fs", ")", ")", "\n", "o", ".", "currentSample", "=", "0", "\n", "}" ]
// Reset sets the oscillator back to its starting state
[ "Reset", "sets", "the", "oscillator", "back", "to", "its", "starting", "state" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/generator/osc.go#L36-L39
12,284
mattetti/audio
generator/osc.go
SetFreq
func (o *Osc) SetFreq(hz float64) { if o.Freq != hz { o.Freq = hz o.phaseAngleIncr = ((hz * TwoPi) / float64(o.Fs)) } }
go
func (o *Osc) SetFreq(hz float64) { if o.Freq != hz { o.Freq = hz o.phaseAngleIncr = ((hz * TwoPi) / float64(o.Fs)) } }
[ "func", "(", "o", "*", "Osc", ")", "SetFreq", "(", "hz", "float64", ")", "{", "if", "o", ".", "Freq", "!=", "hz", "{", "o", ".", "Freq", "=", "hz", "\n", "o", ".", "phaseAngleIncr", "=", "(", "(", "hz", "*", "TwoPi", ")", "/", "float64", "(", "o", ".", "Fs", ")", ")", "\n", "}", "\n", "}" ]
// SetFreq updates the oscillator frequency
[ "SetFreq", "updates", "the", "oscillator", "frequency" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/generator/osc.go#L42-L47
12,285
mattetti/audio
generator/osc.go
SetAttackInMs
func (o *Osc) SetAttackInMs(ms int) { if o == nil { return } if ms <= 0 { o.attackInSamples = 0 return } o.attackInSamples = int(float32(o.Fs) / (1000.0 / float32(ms))) }
go
func (o *Osc) SetAttackInMs(ms int) { if o == nil { return } if ms <= 0 { o.attackInSamples = 0 return } o.attackInSamples = int(float32(o.Fs) / (1000.0 / float32(ms))) }
[ "func", "(", "o", "*", "Osc", ")", "SetAttackInMs", "(", "ms", "int", ")", "{", "if", "o", "==", "nil", "{", "return", "\n", "}", "\n", "if", "ms", "<=", "0", "{", "o", ".", "attackInSamples", "=", "0", "\n", "return", "\n", "}", "\n", "o", ".", "attackInSamples", "=", "int", "(", "float32", "(", "o", ".", "Fs", ")", "/", "(", "1000.0", "/", "float32", "(", "ms", ")", ")", ")", "\n", "}" ]
// SetAttackInMs sets the duration for the oscillator to be at full amplitude // after it starts.
[ "SetAttackInMs", "sets", "the", "duration", "for", "the", "oscillator", "to", "be", "at", "full", "amplitude", "after", "it", "starts", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/generator/osc.go#L51-L60
12,286
mattetti/audio
generator/osc.go
Signal
func (o *Osc) Signal(length int) []float64 { output := make([]float64, length) for i := 0; i < length; i++ { output[i] = o.Sample() } return output }
go
func (o *Osc) Signal(length int) []float64 { output := make([]float64, length) for i := 0; i < length; i++ { output[i] = o.Sample() } return output }
[ "func", "(", "o", "*", "Osc", ")", "Signal", "(", "length", "int", ")", "[", "]", "float64", "{", "output", ":=", "make", "(", "[", "]", "float64", ",", "length", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "length", ";", "i", "++", "{", "output", "[", "i", "]", "=", "o", ".", "Sample", "(", ")", "\n", "}", "\n", "return", "output", "\n", "}" ]
// Signal uses the osc to generate a discreet signal
[ "Signal", "uses", "the", "osc", "to", "generate", "a", "discreet", "signal" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/generator/osc.go#L63-L69
12,287
mattetti/audio
generator/osc.go
Fill
func (o *Osc) Fill(buf *audio.PCMBuffer) error { if o == nil { return nil } len := buf.Len() for i := 0; i < len; i++ { switch buf.DataType { case audio.Integer: buf.Ints[i] = int(o.Sample()) case audio.Float: buf.Floats[i] = o.Sample() case audio.Byte: // TODO: check the format bitdepth and endianess and convert return errors.New("bytes buffer not yet supported") } } return nil }
go
func (o *Osc) Fill(buf *audio.PCMBuffer) error { if o == nil { return nil } len := buf.Len() for i := 0; i < len; i++ { switch buf.DataType { case audio.Integer: buf.Ints[i] = int(o.Sample()) case audio.Float: buf.Floats[i] = o.Sample() case audio.Byte: // TODO: check the format bitdepth and endianess and convert return errors.New("bytes buffer not yet supported") } } return nil }
[ "func", "(", "o", "*", "Osc", ")", "Fill", "(", "buf", "*", "audio", ".", "PCMBuffer", ")", "error", "{", "if", "o", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "len", ":=", "buf", ".", "Len", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", ";", "i", "++", "{", "switch", "buf", ".", "DataType", "{", "case", "audio", ".", "Integer", ":", "buf", ".", "Ints", "[", "i", "]", "=", "int", "(", "o", ".", "Sample", "(", ")", ")", "\n", "case", "audio", ".", "Float", ":", "buf", ".", "Floats", "[", "i", "]", "=", "o", ".", "Sample", "(", ")", "\n", "case", "audio", ".", "Byte", ":", "// TODO: check the format bitdepth and endianess and convert", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Fill fills up the pass PCMBuffer with the output of the oscillator.
[ "Fill", "fills", "up", "the", "pass", "PCMBuffer", "with", "the", "output", "of", "the", "oscillator", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/generator/osc.go#L72-L89
12,288
mattetti/audio
generator/osc.go
Sample
func (o *Osc) Sample() (output float64) { if o == nil { return } o.currentSample++ if o.CurrentPhaseAngle < -math.Pi { o.CurrentPhaseAngle += TwoPi } else if o.CurrentPhaseAngle > math.Pi { o.CurrentPhaseAngle -= TwoPi } var amp float64 if o.attackInSamples > o.currentSample { // linear fade in amp = float64(o.currentSample) * (o.Amplitude / float64(o.attackInSamples)) } else { amp = o.Amplitude } switch o.Shape { case WaveSine: output = amp*Sine(o.CurrentPhaseAngle) + o.DcOffset case WaveTriangle: output = amp*Triangle(o.CurrentPhaseAngle) + o.DcOffset case WaveSaw: output = amp*Sawtooth(o.CurrentPhaseAngle) + o.DcOffset case WaveSqr: fmt.Println(o.CurrentPhaseAngle) output = amp*Square(o.CurrentPhaseAngle) + o.DcOffset } o.CurrentPhaseAngle += o.phaseAngleIncr return output }
go
func (o *Osc) Sample() (output float64) { if o == nil { return } o.currentSample++ if o.CurrentPhaseAngle < -math.Pi { o.CurrentPhaseAngle += TwoPi } else if o.CurrentPhaseAngle > math.Pi { o.CurrentPhaseAngle -= TwoPi } var amp float64 if o.attackInSamples > o.currentSample { // linear fade in amp = float64(o.currentSample) * (o.Amplitude / float64(o.attackInSamples)) } else { amp = o.Amplitude } switch o.Shape { case WaveSine: output = amp*Sine(o.CurrentPhaseAngle) + o.DcOffset case WaveTriangle: output = amp*Triangle(o.CurrentPhaseAngle) + o.DcOffset case WaveSaw: output = amp*Sawtooth(o.CurrentPhaseAngle) + o.DcOffset case WaveSqr: fmt.Println(o.CurrentPhaseAngle) output = amp*Square(o.CurrentPhaseAngle) + o.DcOffset } o.CurrentPhaseAngle += o.phaseAngleIncr return output }
[ "func", "(", "o", "*", "Osc", ")", "Sample", "(", ")", "(", "output", "float64", ")", "{", "if", "o", "==", "nil", "{", "return", "\n", "}", "\n", "o", ".", "currentSample", "++", "\n", "if", "o", ".", "CurrentPhaseAngle", "<", "-", "math", ".", "Pi", "{", "o", ".", "CurrentPhaseAngle", "+=", "TwoPi", "\n", "}", "else", "if", "o", ".", "CurrentPhaseAngle", ">", "math", ".", "Pi", "{", "o", ".", "CurrentPhaseAngle", "-=", "TwoPi", "\n", "}", "\n\n", "var", "amp", "float64", "\n", "if", "o", ".", "attackInSamples", ">", "o", ".", "currentSample", "{", "// linear fade in", "amp", "=", "float64", "(", "o", ".", "currentSample", ")", "*", "(", "o", ".", "Amplitude", "/", "float64", "(", "o", ".", "attackInSamples", ")", ")", "\n", "}", "else", "{", "amp", "=", "o", ".", "Amplitude", "\n", "}", "\n\n", "switch", "o", ".", "Shape", "{", "case", "WaveSine", ":", "output", "=", "amp", "*", "Sine", "(", "o", ".", "CurrentPhaseAngle", ")", "+", "o", ".", "DcOffset", "\n", "case", "WaveTriangle", ":", "output", "=", "amp", "*", "Triangle", "(", "o", ".", "CurrentPhaseAngle", ")", "+", "o", ".", "DcOffset", "\n", "case", "WaveSaw", ":", "output", "=", "amp", "*", "Sawtooth", "(", "o", ".", "CurrentPhaseAngle", ")", "+", "o", ".", "DcOffset", "\n", "case", "WaveSqr", ":", "fmt", ".", "Println", "(", "o", ".", "CurrentPhaseAngle", ")", "\n", "output", "=", "amp", "*", "Square", "(", "o", ".", "CurrentPhaseAngle", ")", "+", "o", ".", "DcOffset", "\n", "}", "\n\n", "o", ".", "CurrentPhaseAngle", "+=", "o", ".", "phaseAngleIncr", "\n", "return", "output", "\n", "}" ]
// Sample returns the next sample generated by the oscillator
[ "Sample", "returns", "the", "next", "sample", "generated", "by", "the", "oscillator" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/generator/osc.go#L92-L125
12,289
mattetti/audio
riff/chunk.go
Done
func (ch *Chunk) Done() { if !ch.IsFullyRead() { ch.Drain() } if ch.Wg != nil { ch.Wg.Done() } }
go
func (ch *Chunk) Done() { if !ch.IsFullyRead() { ch.Drain() } if ch.Wg != nil { ch.Wg.Done() } }
[ "func", "(", "ch", "*", "Chunk", ")", "Done", "(", ")", "{", "if", "!", "ch", ".", "IsFullyRead", "(", ")", "{", "ch", ".", "Drain", "(", ")", "\n", "}", "\n", "if", "ch", ".", "Wg", "!=", "nil", "{", "ch", ".", "Wg", ".", "Done", "(", ")", "\n", "}", "\n", "}" ]
// Done signals the parent parser that we are done reading the chunk // if the chunk isn't fully read, this code will do so before signaling.
[ "Done", "signals", "the", "parent", "parser", "that", "we", "are", "done", "reading", "the", "chunk", "if", "the", "chunk", "isn", "t", "fully", "read", "this", "code", "will", "do", "so", "before", "signaling", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/riff/chunk.go#L61-L68
12,290
mattetti/audio
riff/chunk.go
ReadBE
func (ch *Chunk) ReadBE(dst interface{}) error { if ch.IsFullyRead() { return io.EOF } ch.Pos += binary.Size(dst) return binary.Read(ch.R, binary.LittleEndian, dst) }
go
func (ch *Chunk) ReadBE(dst interface{}) error { if ch.IsFullyRead() { return io.EOF } ch.Pos += binary.Size(dst) return binary.Read(ch.R, binary.LittleEndian, dst) }
[ "func", "(", "ch", "*", "Chunk", ")", "ReadBE", "(", "dst", "interface", "{", "}", ")", "error", "{", "if", "ch", ".", "IsFullyRead", "(", ")", "{", "return", "io", ".", "EOF", "\n", "}", "\n", "ch", ".", "Pos", "+=", "binary", ".", "Size", "(", "dst", ")", "\n", "return", "binary", ".", "Read", "(", "ch", ".", "R", ",", "binary", ".", "LittleEndian", ",", "dst", ")", "\n", "}" ]
// ReadBE reads the Big Endian chunk data into the passed struct
[ "ReadBE", "reads", "the", "Big", "Endian", "chunk", "data", "into", "the", "passed", "struct" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/riff/chunk.go#L101-L107
12,291
mattetti/audio
riff/chunk.go
Drain
func (ch *Chunk) Drain() { bytesAhead := ch.Size - ch.Pos for bytesAhead > 0 { readSize := int64(bytesAhead) if _, err := io.CopyN(ioutil.Discard, ch.R, readSize); err != nil { return } bytesAhead -= int(readSize) } }
go
func (ch *Chunk) Drain() { bytesAhead := ch.Size - ch.Pos for bytesAhead > 0 { readSize := int64(bytesAhead) if _, err := io.CopyN(ioutil.Discard, ch.R, readSize); err != nil { return } bytesAhead -= int(readSize) } }
[ "func", "(", "ch", "*", "Chunk", ")", "Drain", "(", ")", "{", "bytesAhead", ":=", "ch", ".", "Size", "-", "ch", ".", "Pos", "\n", "for", "bytesAhead", ">", "0", "{", "readSize", ":=", "int64", "(", "bytesAhead", ")", "\n\n", "if", "_", ",", "err", ":=", "io", ".", "CopyN", "(", "ioutil", ".", "Discard", ",", "ch", ".", "R", ",", "readSize", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "bytesAhead", "-=", "int", "(", "readSize", ")", "\n", "}", "\n", "}" ]
// Drain discards the rest of the chunk
[ "Drain", "discards", "the", "rest", "of", "the", "chunk" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/riff/chunk.go#L120-L130
12,292
mattetti/audio
dsp/analysis/dft.go
NewDFT
func NewDFT(sr int, x []float64) *DFT { return &DFT{ SampleRate: sr, Coefs: fft.FFTReal(x), } }
go
func NewDFT(sr int, x []float64) *DFT { return &DFT{ SampleRate: sr, Coefs: fft.FFTReal(x), } }
[ "func", "NewDFT", "(", "sr", "int", ",", "x", "[", "]", "float64", ")", "*", "DFT", "{", "return", "&", "DFT", "{", "SampleRate", ":", "sr", ",", "Coefs", ":", "fft", ".", "FFTReal", "(", "x", ")", ",", "}", "\n", "}" ]
// NewDFT returns the FFT result wrapped in a DFT struct
[ "NewDFT", "returns", "the", "FFT", "result", "wrapped", "in", "a", "DFT", "struct" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/dsp/analysis/dft.go#L24-L29
12,293
mattetti/audio
dsp/analysis/dft.go
IFFT
func (d *DFT) IFFT() []float64 { sndDataCmplx := fft.IFFT(d.Coefs) sndData := make([]float64, len(sndDataCmplx)) for i, cpx := range sndDataCmplx { sndData[i] = cmplx.Abs(cpx) } return sndData }
go
func (d *DFT) IFFT() []float64 { sndDataCmplx := fft.IFFT(d.Coefs) sndData := make([]float64, len(sndDataCmplx)) for i, cpx := range sndDataCmplx { sndData[i] = cmplx.Abs(cpx) } return sndData }
[ "func", "(", "d", "*", "DFT", ")", "IFFT", "(", ")", "[", "]", "float64", "{", "sndDataCmplx", ":=", "fft", ".", "IFFT", "(", "d", ".", "Coefs", ")", "\n", "sndData", ":=", "make", "(", "[", "]", "float64", ",", "len", "(", "sndDataCmplx", ")", ")", "\n", "for", "i", ",", "cpx", ":=", "range", "sndDataCmplx", "{", "sndData", "[", "i", "]", "=", "cmplx", ".", "Abs", "(", "cpx", ")", "\n", "}", "\n", "return", "sndData", "\n", "}" ]
// IFFT runs an inverse fast fourrier transform and returns the float values
[ "IFFT", "runs", "an", "inverse", "fast", "fourrier", "transform", "and", "returns", "the", "float", "values" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/dsp/analysis/dft.go#L32-L39
12,294
mattetti/audio
transforms/resample.go
Resample
func Resample(buf *audio.PCMBuffer, fs float64) error { if buf == nil || buf.Format == nil { return audio.ErrInvalidBuffer } if buf.Format.SampleRate == int(fs) { return nil } buf.SwitchPrimaryType(audio.Float) // downsample if fs < float64(buf.Format.SampleRate) { factor := float64(buf.Format.SampleRate) / fs // apply a low pass filter at the nyquist frequency to avoid // aliasing. if err := filters.LowPass(buf, float64(buf.Format.SampleRate)/2); err != nil { return err } // drop samples to match the decimation factor newLength := int(math.Floor(float64(len(buf.Floats)) / factor)) var targetI int for i := 0; i < newLength; i++ { targetI = int(math.Floor(float64(i) * factor)) buf.Floats[i] = buf.Floats[targetI] } buf.Floats = buf.Floats[:newLength] buf.Format.SampleRate = int(fs) return nil } // oversample // Note: oversampling reduces the amplitude factor := fs / float64(buf.Format.SampleRate) newLength := int(math.Ceil(float64(len(buf.Floats)) * factor)) newFloats := make([]float64, newLength) padding := int( math.Ceil( float64(newLength) / float64(len(buf.Floats)))) var idx int for i := 0; i < len(buf.Floats); i++ { idx = i * padding if idx >= len(newFloats) { break } newFloats[idx] = buf.Floats[i] } buf.Floats = newFloats buf.Format.SampleRate = int(fs) return nil }
go
func Resample(buf *audio.PCMBuffer, fs float64) error { if buf == nil || buf.Format == nil { return audio.ErrInvalidBuffer } if buf.Format.SampleRate == int(fs) { return nil } buf.SwitchPrimaryType(audio.Float) // downsample if fs < float64(buf.Format.SampleRate) { factor := float64(buf.Format.SampleRate) / fs // apply a low pass filter at the nyquist frequency to avoid // aliasing. if err := filters.LowPass(buf, float64(buf.Format.SampleRate)/2); err != nil { return err } // drop samples to match the decimation factor newLength := int(math.Floor(float64(len(buf.Floats)) / factor)) var targetI int for i := 0; i < newLength; i++ { targetI = int(math.Floor(float64(i) * factor)) buf.Floats[i] = buf.Floats[targetI] } buf.Floats = buf.Floats[:newLength] buf.Format.SampleRate = int(fs) return nil } // oversample // Note: oversampling reduces the amplitude factor := fs / float64(buf.Format.SampleRate) newLength := int(math.Ceil(float64(len(buf.Floats)) * factor)) newFloats := make([]float64, newLength) padding := int( math.Ceil( float64(newLength) / float64(len(buf.Floats)))) var idx int for i := 0; i < len(buf.Floats); i++ { idx = i * padding if idx >= len(newFloats) { break } newFloats[idx] = buf.Floats[i] } buf.Floats = newFloats buf.Format.SampleRate = int(fs) return nil }
[ "func", "Resample", "(", "buf", "*", "audio", ".", "PCMBuffer", ",", "fs", "float64", ")", "error", "{", "if", "buf", "==", "nil", "||", "buf", ".", "Format", "==", "nil", "{", "return", "audio", ".", "ErrInvalidBuffer", "\n", "}", "\n", "if", "buf", ".", "Format", ".", "SampleRate", "==", "int", "(", "fs", ")", "{", "return", "nil", "\n", "}", "\n", "buf", ".", "SwitchPrimaryType", "(", "audio", ".", "Float", ")", "\n\n", "// downsample", "if", "fs", "<", "float64", "(", "buf", ".", "Format", ".", "SampleRate", ")", "{", "factor", ":=", "float64", "(", "buf", ".", "Format", ".", "SampleRate", ")", "/", "fs", "\n\n", "// apply a low pass filter at the nyquist frequency to avoid", "// aliasing.", "if", "err", ":=", "filters", ".", "LowPass", "(", "buf", ",", "float64", "(", "buf", ".", "Format", ".", "SampleRate", ")", "/", "2", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// drop samples to match the decimation factor", "newLength", ":=", "int", "(", "math", ".", "Floor", "(", "float64", "(", "len", "(", "buf", ".", "Floats", ")", ")", "/", "factor", ")", ")", "\n", "var", "targetI", "int", "\n", "for", "i", ":=", "0", ";", "i", "<", "newLength", ";", "i", "++", "{", "targetI", "=", "int", "(", "math", ".", "Floor", "(", "float64", "(", "i", ")", "*", "factor", ")", ")", "\n", "buf", ".", "Floats", "[", "i", "]", "=", "buf", ".", "Floats", "[", "targetI", "]", "\n", "}", "\n", "buf", ".", "Floats", "=", "buf", ".", "Floats", "[", ":", "newLength", "]", "\n", "buf", ".", "Format", ".", "SampleRate", "=", "int", "(", "fs", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// oversample", "// Note: oversampling reduces the amplitude", "factor", ":=", "fs", "/", "float64", "(", "buf", ".", "Format", ".", "SampleRate", ")", "\n", "newLength", ":=", "int", "(", "math", ".", "Ceil", "(", "float64", "(", "len", "(", "buf", ".", "Floats", ")", ")", "*", "factor", ")", ")", "\n", "newFloats", ":=", "make", "(", "[", "]", "float64", ",", "newLength", ")", "\n", "padding", ":=", "int", "(", "math", ".", "Ceil", "(", "float64", "(", "newLength", ")", "/", "float64", "(", "len", "(", "buf", ".", "Floats", ")", ")", ")", ")", "\n", "var", "idx", "int", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "buf", ".", "Floats", ")", ";", "i", "++", "{", "idx", "=", "i", "*", "padding", "\n", "if", "idx", ">=", "len", "(", "newFloats", ")", "{", "break", "\n", "}", "\n", "newFloats", "[", "idx", "]", "=", "buf", ".", "Floats", "[", "i", "]", "\n", "}", "\n", "buf", ".", "Floats", "=", "newFloats", "\n", "buf", ".", "Format", ".", "SampleRate", "=", "int", "(", "fs", ")", "\n", "return", "nil", "\n", "}" ]
// Resample down or up samples the buffer. Note that the amplitude // will be affected by upsampling.
[ "Resample", "down", "or", "up", "samples", "the", "buffer", ".", "Note", "that", "the", "amplitude", "will", "be", "affected", "by", "upsampling", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/transforms/resample.go#L12-L63
12,295
mattetti/audio
midi/note.go
KeyInt
func KeyInt(n string, octave int) int { key := notesToInt[strings.ToUpper(n)] // octave starts at -2 but first note is at 0 return key + (octave+2)*12 }
go
func KeyInt(n string, octave int) int { key := notesToInt[strings.ToUpper(n)] // octave starts at -2 but first note is at 0 return key + (octave+2)*12 }
[ "func", "KeyInt", "(", "n", "string", ",", "octave", "int", ")", "int", "{", "key", ":=", "notesToInt", "[", "strings", ".", "ToUpper", "(", "n", ")", "]", "\n", "// octave starts at -2 but first note is at 0", "return", "key", "+", "(", "octave", "+", "2", ")", "*", "12", "\n", "}" ]
// KeyInt converts an A-G note notation to a midi note number value.
[ "KeyInt", "converts", "an", "A", "-", "G", "note", "notation", "to", "a", "midi", "note", "number", "value", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/note.go#L40-L44
12,296
mattetti/audio
midi/note.go
NoteToFreq
func NoteToFreq(note int) float64 { return audio.RootA * math.Pow(2, (float64(note)-69.0)/12.0) }
go
func NoteToFreq(note int) float64 { return audio.RootA * math.Pow(2, (float64(note)-69.0)/12.0) }
[ "func", "NoteToFreq", "(", "note", "int", ")", "float64", "{", "return", "audio", ".", "RootA", "*", "math", ".", "Pow", "(", "2", ",", "(", "float64", "(", "note", ")", "-", "69.0", ")", "/", "12.0", ")", "\n", "}" ]
// NoteToFreq returns the frequency of the passed midi note.
[ "NoteToFreq", "returns", "the", "frequency", "of", "the", "passed", "midi", "note", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/note.go#L53-L55
12,297
mattetti/audio
midi/note.go
NoteToName
func NoteToName(note int) string { key := Notes[note%12] octave := ((note / 12) | 0) - 2 // The MIDI scale starts at octave = -2 return key + strconv.Itoa(octave) }
go
func NoteToName(note int) string { key := Notes[note%12] octave := ((note / 12) | 0) - 2 // The MIDI scale starts at octave = -2 return key + strconv.Itoa(octave) }
[ "func", "NoteToName", "(", "note", "int", ")", "string", "{", "key", ":=", "Notes", "[", "note", "%", "12", "]", "\n", "octave", ":=", "(", "(", "note", "/", "12", ")", "|", "0", ")", "-", "2", "// The MIDI scale starts at octave = -2", "\n", "return", "key", "+", "strconv", ".", "Itoa", "(", "octave", ")", "\n", "}" ]
// NoteToName converts a midi note value into its English name
[ "NoteToName", "converts", "a", "midi", "note", "value", "into", "its", "English", "name" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/note.go#L58-L62
12,298
mattetti/audio
midi/note.go
FreqToNote
func FreqToNote(freq float64) int { pitch := 12.0*(math.Log(freq/(440/2.0))/math.Log(2.0)) + 57.0 return int(pitch + 0.00001) }
go
func FreqToNote(freq float64) int { pitch := 12.0*(math.Log(freq/(440/2.0))/math.Log(2.0)) + 57.0 return int(pitch + 0.00001) }
[ "func", "FreqToNote", "(", "freq", "float64", ")", "int", "{", "pitch", ":=", "12.0", "*", "(", "math", ".", "Log", "(", "freq", "/", "(", "440", "/", "2.0", ")", ")", "/", "math", ".", "Log", "(", "2.0", ")", ")", "+", "57.0", "\n", "return", "int", "(", "pitch", "+", "0.00001", ")", "\n", "}" ]
// FreqToNote reports the associated midi node for a given frequency.
[ "FreqToNote", "reports", "the", "associated", "midi", "node", "for", "a", "given", "frequency", "." ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/note.go#L65-L68
12,299
mattetti/audio
midi/track.go
Tempo
func (t *Track) Tempo() int { if t == nil { return 0 } tempoEvType := MetaByteMap["Tempo"] for _, ev := range t.Events { if ev.Cmd == tempoEvType { return int(ev.Bpm) } } return 0 }
go
func (t *Track) Tempo() int { if t == nil { return 0 } tempoEvType := MetaByteMap["Tempo"] for _, ev := range t.Events { if ev.Cmd == tempoEvType { return int(ev.Bpm) } } return 0 }
[ "func", "(", "t", "*", "Track", ")", "Tempo", "(", ")", "int", "{", "if", "t", "==", "nil", "{", "return", "0", "\n", "}", "\n", "tempoEvType", ":=", "MetaByteMap", "[", "\"", "\"", "]", "\n", "for", "_", ",", "ev", ":=", "range", "t", ".", "Events", "{", "if", "ev", ".", "Cmd", "==", "tempoEvType", "{", "return", "int", "(", "ev", ".", "Bpm", ")", "\n", "}", "\n", "}", "\n", "return", "0", "\n", "}" ]
// Tempo returns the tempo of the track if set, 0 otherwise
[ "Tempo", "returns", "the", "tempo", "of", "the", "track", "if", "set", "0", "otherwise" ]
c6aebeb78429d88ff11f1468dac519ead57e7196
https://github.com/mattetti/audio/blob/c6aebeb78429d88ff11f1468dac519ead57e7196/midi/track.go#L29-L40