forked from OpenAyame/ayame
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler_upload.go
299 lines (257 loc) · 8.04 KB
/
handler_upload.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"time"
)
// Set of media files for service
type MediaSet struct {
SrcDir string `json:"src_dir,omitempty"`
DstDir string `json:"dst_dir,omitempty"`
SrcBase string `json:"src_base,omitempty"`
DstBase string `json:"dst_base,omitempty"`
SrcName string `json:"src_name,omitempty"`
DstName string `json:"dst_name,omitempty"`
DstDesc string `json:"dst_desc,omitempty"`
DstFiles []string `json:"dst_files,omitempty"`
}
// Stringer for MediaSet
func (m *MediaSet) String() string {
return fmt.Sprintf("MediaSet> SrcDir=%s, DstDir=%s, SrcName=%s, DstName=%s, DstDesc=%s",
m.SrcDir, m.DstDir, m.SrcName, m.DstName, m.DstDesc)
}
// Convert JSON output for the struct
func (m *MediaSet) JSONString() string {
jbyte, _ := json.Marshal(m)
return string(jbyte)
}
// Convert JSON Indent output for the struct
func (m *MediaSet) JSONIndentString() string {
jbyte, _ := json.MarshalIndent(m, "", " ")
return string(jbyte)
}
// Send struct as the response in JSON
func (m *MediaSet) SendJSON(w http.ResponseWriter) {
jbyte, _ := json.Marshal(m)
w.Header().Set("Content-Type", "application/json")
w.Write(jbyte)
}
// --------------------------------------------------------------------------------------
// Handler for Uploading and Transcoding
func uploadHandler(hub *Hub, w http.ResponseWriter, r *http.Request) {
log.Println(r.URL.Path, r.RemoteAddr, r.Method, r.Header.Get("Content-Type"))
defer log.Printf("uploadHandler exit")
// parse our multipart form, 10 << 20 specifies a maximum upload of 10 MB files.
err := r.ParseMultipartForm(10 << 20)
if err != nil {
log.Println("ParseMultipartForm error:", err)
return
}
file, handler, err := r.FormFile("uploadFile")
if err != nil {
log.Println("FormFile error:", err)
return
}
defer file.Close()
// log.Println(handler)
basename := time.Now().Format("D20060102T150405")
// create a temp file within our upload directory that follows a particular naming pattern
tempFile, err := ioutil.TempFile("asset/upload", "COBOT-"+basename+"-R*"+filepath.Ext(handler.Filename))
if err != nil {
log.Println("TempFile error:", err)
return
}
defer tempFile.Close()
// read all of the contents of our uploaded file into a byte array
fileBytes, err := ioutil.ReadAll(file)
if err != nil {
log.Println("ReadAll error:", err)
return
}
// write this byte array to our temporary file
n, err := tempFile.Write(fileBytes)
if int64(n) < handler.Size || err != nil {
log.Println("Write error:", err, n)
return
}
// return that we have successfully uploaded our file!
fmt.Fprintf(w, "Successfully uploaded the file and being processed it.\n")
log.Printf("%s => %s", handler.Filename, tempFile.Name())
// prepare a media set for the upload file
mset := &MediaSet{}
mset.SrcDir = "asset/upload/"
mset.SrcBase = ""
mset.SrcName = filepath.Base(tempFile.Name())
mset.DstDir = "asset/record/"
mset.DstBase = basename + "/" // time.Now().Format("D20060102T150405/")
mset.DstName = "COBOT-" + basename + "-U" + getUUIDString()
mset.DstDesc = "ffmpeg (libx264/aac) mp4/mpv/jpg/vtt"
log.Println("MediaSet>\n", mset.JSONIndentString())
// do post media processing in background
go postMediaProcessing(mset)
}
// Postprocessing for the video file uploaded
func postMediaProcessing(mset *MediaSet) (err error) {
defer log.Printf("postMediaProcessing Done")
err = getMediaInfo(mset)
if err != nil {
log.Println("getMediaInfo error:", err)
return
}
// log.Println("getMediaInfo:", "Done")
err = makeMediaSet(mset)
if err != nil {
log.Println("makeMediaSet error:", err)
return
}
// log.Println("makeMediaSet:", "Done")
// remove the upload file after sucessful record
err = os.Remove(mset.SrcDir + mset.SrcName)
if err != nil {
log.Println("Remove error:", err)
return
}
return
}
// Make a set of media files for a video
func getMediaInfo(mset *MediaSet) (err error) {
// check mediainfo command if it is executable
_, err = exec.LookPath("mediainfo")
if err != nil {
log.Fatal(err)
}
// log.Println("mediainfo:", path)
// Get meta information for the media file
var stdout, stderr bytes.Buffer
cmd := exec.Command("mediainfo", mset.SrcDir+mset.SrcName)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err = cmd.Run()
if err != nil {
log.Fatalln(err, string(stderr.Bytes()))
}
outStr, errStr := string(stdout.Bytes()), string(stderr.Bytes())
log.Println(outStr, errStr)
return
}
// Make a set of media files for a video
func makeMediaSet(mset *MediaSet) (err error) {
_, err = exec.LookPath("ffmpeg")
if err != nil {
log.Printf("LookPath error: %s", err)
return
}
// log.Println("ffmpeg:", path)
// generate related files for the input video
os.MkdirAll(mset.DstDir+mset.DstBase, os.ModePerm)
inPart := mset.SrcDir + mset.SrcName
outPart := mset.DstDir + mset.DstBase + mset.DstName
log.Println(inPart, "=>", outPart)
cmdStr := fmt.Sprintf("ffmpeg -loglevel error -stats -y")
cmdStr += fmt.Sprintf(" -i %s", inPart)
// if you want to use libfdk_aac, check its support in ffmpeg -codecs / -encoders
mp4Opt := `-vcodec libx264 -vf "scale=1280:720" -acodec aac -movflags faststart -f mp4`
mp4Part := changePathExtention(outPart, ".mp4")
cmdStr += fmt.Sprintf(" %s %s", mp4Opt, mp4Part)
// consider use middle(480:270) if the size(320:180) is small
mpvOpt := `-vcodec libx264 -r 10 -vf "scale=480:270" -an -movflags faststart -f mp4`
mpvPart := changePathExtention(outPart, ".mpv")
cmdStr += fmt.Sprintf(" %s %s", mpvOpt, mpvPart)
jpgOpt := `-ss 00:00:01.000 -frames:v 1 -vf "scale=640:360"`
jpgPart := changePathExtention(outPart, ".jpg")
cmdStr += fmt.Sprintf(" %s %s", jpgOpt, jpgPart)
// gifOpt := `-r 10 -vf "scale=320:180" -loop 0`
// gifPart := changePathExtention(outPart, ".gif")
// cmdStr += fmt.Sprintf("%s %s", gifOpt, gifPart)
// webpOpt := `-r 10 -vf "scale=320:180" -loop 0`
// webpPart := changePathExtention(outPart, ".webp")
// cmdStr += fmt.Sprintf(" %s %s", webpOpt, webpPart)
// webmOpt := `-r 10 -vf "scale=320:180" -an`
// webmPart := changePathExtention(outPart, ".webm")
// cmdStr += fmt.Sprintf(" %s %s", webmOpt, webmPart)
log.Println(cmdStr)
cmd := exec.Command("sh", "-c", cmdStr)
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("CombinedOutput error: %s", err)
return
}
log.Println(string(out))
vttPart := changePathExtention(outPart, ".vtt")
err = makeSubtitleFile(vttPart)
if err != nil {
log.Printf("makeSubtitleFile err: %s", err)
return
}
err = recordMediaSetFiles(mset)
if err != nil {
log.Printf("recordMediaSetFiles err: %s", err)
return
}
log.Println("MediaSet>\n", mset.JSONIndentString())
return
}
// Change extension of the filename with another one
func changePathExtention(fpath, fext string) (str string) {
ext := filepath.Ext(fpath)
str = fpath[0:len(fpath)-len(ext)] + fext
return
}
// Send a web page to the http client
func sendFilePage(w http.ResponseWriter, filename string) (err error) {
page, err := ioutil.ReadFile(filename)
if err != nil {
log.Printf("ReadFile(%s) error: %s", filename, err)
return
}
fmt.Fprintf(w, string(page))
return
}
const sampleTitle = `WEBVTT - Sample text for testing
NOTE
This is comment part. It is not displayed on screen.
00:00:01.000 --> 00:00:05.000 line:-3
<b>This is sample subtitle text.</b>
HTML style tag can be used.
`
func makeSubtitleFile(fname string) (err error) {
f, err := os.Create(fname)
if err != nil {
log.Printf("Create error: %s", err)
return
}
defer f.Close()
n, err := f.WriteString(sampleTitle)
if n < len(sampleTitle) || err != nil {
log.Printf("WriteString error: %s, %d", err, n)
return
}
f.Sync()
return
}
func recordMediaSetFiles(mset *MediaSet) (err error) {
d, err := os.Open(mset.DstDir + mset.DstBase)
if err != nil {
log.Printf("Open error: %s", err)
return
}
defer d.Close()
files, err := d.Readdir(-1)
if err != nil {
log.Printf("Readdir error: %s", err)
return
}
for _, f := range files {
if f.Mode().IsRegular() && f.Size() > 0 {
mset.DstFiles = append(mset.DstFiles, f.Name())
}
}
return
}