-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathplayingbar.go
419 lines (355 loc) · 9.51 KB
/
playingbar.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
// Copyright (C) 2020 Raziman
package main
import (
"bytes"
"errors"
"fmt"
"image"
"strconv"
"strings"
"sync/atomic"
"syscall"
"time"
"unsafe"
"github.com/disintegration/imaging"
"github.com/rivo/tview"
"github.com/tramhao/id3v2"
"github.com/ztrue/tracerr"
ugo "gitlab.com/diamondburned/ueberzug-go"
"github.com/issadarkthing/gomu/lyric"
"github.com/issadarkthing/gomu/player"
)
// PlayingBar shows song name, progress and lyric
type PlayingBar struct {
*tview.Frame
full int32
update chan struct{}
progress int32
skip bool
text *tview.TextView
hasTag bool
tag *id3v2.Tag
subtitle *lyric.Lyric
subtitles []*lyric.Lyric
albumPhoto *ugo.Image
albumPhotoSource image.Image
colrowPixel int32
}
func (p *PlayingBar) help() []string {
return []string{}
}
// Playing bar shows progress of the song and the title of the song
func newPlayingBar() *PlayingBar {
textView := tview.NewTextView().SetTextAlign(tview.AlignCenter)
textView.SetBackgroundColor(gomu.colors.background)
textView.SetDynamicColors(true)
frame := tview.NewFrame(textView).SetBorders(1, 1, 1, 1, 1, 1)
frame.SetBorder(true).SetTitle(" Now Playing ")
frame.SetBackgroundColor(gomu.colors.background)
p := &PlayingBar{
Frame: frame,
text: textView,
update: make(chan struct{}),
}
return p
}
// Start processing progress bar
func (p *PlayingBar) run() error {
for {
// stop progressing if song ends or skipped
progress := p.getProgress()
full := p.getFull()
if progress > full || p.skip {
p.skip = false
p.setProgress(0)
break
}
if gomu.player.IsPaused() {
time.Sleep(1 * time.Second)
continue
}
// p.progress = int(gomu.player.GetPosition().Seconds())
p.setProgress(int(gomu.player.GetPosition().Seconds()))
start, err := time.ParseDuration(strconv.Itoa(progress) + "s")
if err != nil {
return tracerr.Wrap(err)
}
end, err := time.ParseDuration(strconv.Itoa(full) + "s")
if err != nil {
return tracerr.Wrap(err)
}
var width, colrowPixel int
gomu.app.QueueUpdate(func() {
_, _, width, _ = p.GetInnerRect()
cols, rows, windowWidth, windowHeight := getConsoleSize()
rowPixel := windowHeight / rows
colPixel := windowWidth / cols
colrowPixel = rowPixel + colPixel
})
progressBar := progresStr(progress, full, width/2, "█", "━")
if p.getColRowPixel() != colrowPixel {
p.updatePhoto()
p.setColRowPixel(colrowPixel)
}
// our progress bar
var lyricText string
if p.subtitle != nil {
lyricText, err = p.subtitle.GetText(progress)
if err != nil {
return tracerr.Wrap(err)
}
}
gomu.app.QueueUpdateDraw(func() {
p.text.SetText(fmt.Sprintf("%s ┃%s┫ %s\n\n[%s]%v[-]",
fmtDuration(start),
progressBar,
fmtDuration(end),
gomu.colors.subtitle,
lyricText,
))
})
<-time.After(time.Second)
}
return nil
}
// Updates song title
func (p *PlayingBar) setSongTitle(title string) {
p.Clear()
titleColor := gomu.colors.title
p.AddText(title, true, tview.AlignCenter, titleColor)
}
// Resets progress bar, ready for execution
func (p *PlayingBar) newProgress(currentSong *player.AudioFile, full int) {
p.setFull(full)
p.setProgress(0)
p.hasTag = false
p.tag = nil
p.subtitles = nil
p.subtitle = nil
if p.albumPhoto != nil {
p.albumPhoto.Clear()
p.albumPhoto.Destroy()
p.albumPhoto = nil
}
err := p.loadLyrics(currentSong.Path())
if err != nil {
errorPopup(err)
return
}
langLyricFromConfig := gomu.anko.GetString("General.lang_lyric")
if langLyricFromConfig == "" {
langLyricFromConfig = "en"
}
if p.hasTag && p.subtitles != nil {
// First we check if the lyric language preferred is presented
for _, v := range p.subtitles {
if strings.Contains(langLyricFromConfig, v.LangExt) {
p.subtitle = v
break
}
}
// Secondly we check if english lyric is available
if p.subtitle == nil {
for _, v := range p.subtitles {
if v.LangExt == "en" {
p.subtitle = v
break
}
}
}
// Finally we display the first lyric
if p.subtitle == nil {
p.subtitle = p.subtitles[0]
}
}
p.setSongTitle(currentSong.Name())
}
// Sets default title and progress bar
func (p *PlayingBar) setDefault() {
p.setSongTitle("---------:---------")
_, _, width, _ := p.GetInnerRect()
text := fmt.Sprintf(
"%s ┣%s┫ %s", "00:00", strings.Repeat("━", width/2), "00:00",
)
p.text.SetText(text)
if p.albumPhoto != nil {
p.albumPhoto.Clear()
}
}
// Skips the current playing song
func (p *PlayingBar) stop() {
p.skip = true
}
// When switch lyrics, we reload the lyrics from mp3 to reflect changes
func (p *PlayingBar) switchLyrics() {
err := p.loadLyrics(gomu.player.GetCurrentSong().Path())
if err != nil {
errorPopup(err)
return
}
// no subtitle just ignore
if len(p.subtitles) == 0 {
defaultTimedPopup(" Warning ", "No embed lyric found")
p.subtitle = nil
return
}
// only 1 subtitle, prompt to the user and select this one
if len(p.subtitles) == 1 {
p.subtitle = p.subtitles[0]
defaultTimedPopup(" Warning ", p.subtitle.LangExt+" lyric is the only lyric available")
return
}
// more than 1 subtitle, cycle through them and select next
var langIndex int
for i, v := range p.subtitles {
if p.subtitle.LangExt == v.LangExt {
langIndex = i + 1
break
}
}
if langIndex >= len(p.subtitles) {
langIndex = 0
}
p.subtitle = p.subtitles[langIndex]
defaultTimedPopup(" Success ", p.subtitle.LangExt+" lyric switched successfully.")
}
func (p *PlayingBar) delayLyric(lyricDelay int) (err error) {
if p.subtitle != nil {
p.subtitle.Offset -= int32(lyricDelay)
err = embedLyric(gomu.player.GetCurrentSong().Path(), p.subtitle, false)
if err != nil {
return tracerr.Wrap(err)
}
err = p.loadLyrics(gomu.player.GetCurrentSong().Path())
if err != nil {
return tracerr.Wrap(err)
}
for _, v := range p.subtitles {
if strings.Contains(v.LangExt, p.subtitle.LangExt) {
p.subtitle = v
break
}
}
}
return nil
}
func (p *PlayingBar) loadLyrics(currentSongPath string) error {
p.subtitles = nil
var tag *id3v2.Tag
var err error
tag, err = id3v2.Open(currentSongPath, id3v2.Options{Parse: true})
if err != nil {
return tracerr.Wrap(err)
}
defer tag.Close()
if tag == nil {
return nil
}
p.hasTag = true
p.tag = tag
if p.albumPhoto != nil {
p.albumPhoto.Clear()
p.albumPhoto.Destroy()
p.albumPhoto = nil
}
syltFrames := tag.GetFrames(tag.CommonID("Synchronised lyrics/text"))
usltFrames := tag.GetFrames(tag.CommonID("Unsynchronised lyrics/text transcription"))
for _, f := range syltFrames {
sylf, ok := f.(id3v2.SynchronisedLyricsFrame)
if !ok {
return fmt.Errorf("sylt error")
}
for _, u := range usltFrames {
uslf, ok := u.(id3v2.UnsynchronisedLyricsFrame)
if !ok {
return errors.New("USLT error")
}
if sylf.ContentDescriptor == uslf.ContentDescriptor {
var lyric lyric.Lyric
err := lyric.NewFromLRC(uslf.Lyrics)
if err != nil {
return tracerr.Wrap(err)
}
lyric.SyncedCaptions = sylf.SynchronizedTexts
lyric.LangExt = sylf.ContentDescriptor
p.subtitles = append(p.subtitles, &lyric)
}
}
}
pictures := tag.GetFrames(tag.CommonID("Attached picture"))
for _, f := range pictures {
pic, ok := f.(id3v2.PictureFrame)
if !ok {
return errors.New("picture frame error")
}
// Do something with picture frame.
imgTmp, err := imaging.Decode(bytes.NewReader(pic.Picture))
if err != nil {
return tracerr.Wrap(err)
}
p.albumPhotoSource = imgTmp
p.setColRowPixel(0)
}
return nil
}
func (p *PlayingBar) getProgress() int {
return int(atomic.LoadInt32(&p.progress))
}
func (p *PlayingBar) setProgress(progress int) {
atomic.StoreInt32(&p.progress, int32(progress))
}
func (p *PlayingBar) getFull() int {
return int(atomic.LoadInt32(&p.full))
}
func (p *PlayingBar) setFull(full int) {
atomic.StoreInt32(&p.full, int32(full))
}
func (p *PlayingBar) getColRowPixel() int {
return int(atomic.LoadInt32(&p.colrowPixel))
}
func (p *PlayingBar) setColRowPixel(colrowPixel int) {
atomic.StoreInt32(&p.colrowPixel, int32(colrowPixel))
}
func getConsoleSize() (int, int, int, int) {
var sz struct {
rows uint16
cols uint16
xpixels uint16
ypixels uint16
}
_, _, _ = syscall.Syscall(syscall.SYS_IOCTL,
uintptr(syscall.Stdout), uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&sz)))
return int(sz.cols), int(sz.rows), int(sz.xpixels), int(sz.ypixels)
}
// updatePhoto finish two tasks: 1. resize photo based on room left for photo
// 2. register photo in the correct position
func (p *PlayingBar) updatePhoto() {
// Put the whole block in goroutine, in order not to block the whole apps
// also to avoid data race by adding QueueUpdateDraw
go gomu.app.QueueUpdateDraw(func() {
if p.albumPhotoSource == nil {
return
}
if p.albumPhoto != nil {
p.albumPhoto.Clear()
p.albumPhoto.Destroy()
p.albumPhoto = nil
}
x, y, width, height := gomu.queue.GetInnerRect()
cols, rows, windowWidth, windowHeight := getConsoleSize()
colPixel := windowWidth / cols
rowPixel := windowHeight / rows
imageWidth := width * colPixel / 3
// resize the photo according to space left for x and y axis
dstImage := imaging.Resize(p.albumPhotoSource, imageWidth, 0, imaging.Lanczos)
var err error
positionX := x*colPixel + width*colPixel - dstImage.Rect.Dx()
positionY := y*rowPixel + height*rowPixel - dstImage.Rect.Dy()
// register new image
p.albumPhoto, err = ugo.NewImage(dstImage, positionX, positionY)
if err != nil {
errorPopup(err)
}
p.albumPhoto.Show()
})
}