Skip to content

Commit 4bdb8dd

Browse files
GiteaBotwxiaoguang
andauthored
Detect ogg mime-type as audio or video (#26494) (#26505)
Backport #26494 by @wxiaoguang "ogg" is just a "container" format for audio and video. Golang's `DetectContentType` only reports "application/ogg" for potential ogg files. Actually it could do more "guess" to see whether it is a audio file or a video file. Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
1 parent 24d6aac commit 4bdb8dd

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

modules/typesniffer/typesniffer.go

+12-1
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ func (ct SniffedType) IsRepresentableAsText() bool {
7171
return ct.IsText() || ct.IsSvgImage()
7272
}
7373

74-
// IsBrowsableType returns whether a non-text type can be displayed in a browser
74+
// IsBrowsableBinaryType returns whether a non-text type can be displayed in a browser
7575
func (ct SniffedType) IsBrowsableBinaryType() bool {
7676
return ct.IsImage() || ct.IsSvgImage() || ct.IsPDF() || ct.IsVideo() || ct.IsAudio()
7777
}
@@ -116,6 +116,17 @@ func DetectContentType(data []byte) SniffedType {
116116
}
117117
}
118118

119+
if ct == "application/ogg" {
120+
dataHead := data
121+
if len(dataHead) > 256 {
122+
dataHead = dataHead[:256] // only need to do a quick check for the file header
123+
}
124+
if bytes.Contains(dataHead, []byte("theora")) || bytes.Contains(dataHead, []byte("dirac")) {
125+
ct = "video/ogg" // ogg is only used for some video formats, and it's not popular
126+
} else {
127+
ct = "audio/ogg" // for most cases, it is used as an audio container
128+
}
129+
}
119130
return SniffedType{ct}
120131
}
121132

modules/typesniffer/typesniffer_test.go

+13
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package typesniffer
66
import (
77
"bytes"
88
"encoding/base64"
9+
"encoding/hex"
910
"strings"
1011
"testing"
1112

@@ -121,3 +122,15 @@ func TestDetectContentTypeFromReader(t *testing.T) {
121122
assert.NoError(t, err)
122123
assert.True(t, st.IsAudio())
123124
}
125+
126+
func TestDetectContentTypeOgg(t *testing.T) {
127+
oggAudio, _ := hex.DecodeString("4f67675300020000000000000000352f0000000000007dc39163011e01766f72626973000000000244ac0000000000000071020000000000b8014f6767530000")
128+
st, err := DetectContentTypeFromReader(bytes.NewReader(oggAudio))
129+
assert.NoError(t, err)
130+
assert.True(t, st.IsAudio())
131+
132+
oggVideo, _ := hex.DecodeString("4f676753000200000000000000007d9747ef000000009b59daf3012a807468656f7261030201001e00110001e000010e00020000001e00000001000001000001")
133+
st, err = DetectContentTypeFromReader(bytes.NewReader(oggVideo))
134+
assert.NoError(t, err)
135+
assert.True(t, st.IsVideo())
136+
}

0 commit comments

Comments
 (0)