Skip to content
This repository was archived by the owner on Oct 6, 2024. It is now read-only.

Commit 751caf7

Browse files
author
Nyah Check
committed
Add fixes to decoder logic
Bug exists in decoding raw video stream
1 parent d50d915 commit 751caf7

File tree

2 files changed

+47
-55
lines changed

2 files changed

+47
-55
lines changed

download.go

Lines changed: 46 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"bufio"
55
"errors"
66
"fmt"
7-
"io"
87
"io/ioutil"
98
"log"
109
"net/http"
@@ -53,63 +52,24 @@ func fixExtension(str string) string {
5352
if strings.Contains(str, "mp3") {
5453
str = ".mp3"
5554
} else {
56-
format = ".flv"
55+
str = ".flv"
5756
}
5857

5958
return str
6059
}
6160

62-
// decodeStream accept Values and decodes them individually
63-
// decodeStream returns the final RawVideoStream object
64-
func decodeStream(values url.Values, streams *RawVideoStream, rawstream []stream) error {
65-
streams.Author = values["author"][0]
66-
streams.Title = values["title"][0]
67-
streamMap, ok := values["url_encoded_fmt_stream_map"]
68-
if !ok {
69-
return errors.New("Error reading encoded stream map")
70-
}
71-
72-
// read and decode streams
73-
streamsList := strings.Split(string(streamMap[0]), ",")
74-
for streamPos, streamRaw := range streamsList {
75-
streamQry, err := url.ParseQuery(streamRaw)
76-
if err != nil {
77-
logrus.Infof("Error occured during stream decoding %d: %s\n", streamPos, err)
78-
continue
79-
}
80-
var sig string
81-
if _, exist := streamQry["sig"]; exist {
82-
sig = streamQry["sig"][0]
83-
}
84-
85-
rawstream = append(rawstream, stream{
86-
"quality": streamQry["quality"][0],
87-
"type": streamQry["type"][0],
88-
"url": streamQry["url"][0],
89-
"sig": sig,
90-
"title": values["title"][0],
91-
"author": values["author"][0],
92-
})
93-
logrus.Infof("Stream found: quality '%s', format '%s'", streamQry["quality"][0], streamQry["type"][0])
94-
}
95-
96-
streams.URLEncodedFmtStreamMap = rawstream
97-
return nil
98-
}
99-
10061
// encodeAudioStream consumes a raw data stream and
10162
// encodeAudioStream encodes the data stream in mp3
10263
func encodeAudioStream(file, path, surl string, bitrate uint) error {
103-
resp, err := downloadVideoStream(surl)
64+
data, err := downloadVideoStream(surl)
10465
if err != nil {
10566
log.Printf("Http.Get\nerror: %s\nURL: %s\n", err, surl)
10667
return err
10768
}
108-
defer resp.Body.Close()
10969

11070
tmp, _ := os.OpenFile("_temp_", os.O_CREATE, 0755)
11171
defer tmp.Close()
112-
if _, err := io.Copy(tmp, resp.Body); err != nil {
72+
if _, err := tmp.Write(data); err != nil {
11373
logrus.Errorf("Failed to read response body: %v", err)
11474
return err
11575
}
@@ -121,7 +81,7 @@ func encodeAudioStream(file, path, surl string, bitrate uint) error {
12181
return err
12282
}
12383

124-
outputDirectory := currentDirectory.HomeDir + "Downloads" + path
84+
outputDirectory := currentDirectory.HomeDir + "/Downloads/" + path
12585
outputFile := filepath.Join(outputDirectory, file)
12686
if err := os.MkdirAll(filepath.Dir(outputFile), 0775); err != nil {
12787
logrus.Errorf("Unable to create output directory: %v", err)
@@ -149,12 +109,11 @@ func encodeAudioStream(file, path, surl string, bitrate uint) error {
149109
// encodeVideoStream consumes video data stream and
150110
// encodeVideoStream encodes the video in flv
151111
func encodeVideoStream(file, path, surl string) error {
152-
resp, err := downloadVideoStream(surl)
112+
data, err := downloadVideoStream(surl)
153113
if err != nil {
154114
log.Printf("Http.Get\nerror: %s\nURL: %s\n", err, surl)
155115
return err
156116
}
157-
defer resp.Body.Close()
158117

159118
// Create output file
160119
currentDirectory, err := user.Current()
@@ -163,7 +122,7 @@ func encodeVideoStream(file, path, surl string) error {
163122
return err
164123
}
165124

166-
outputDirectory := currentDirectory.HomeDir + "Downloads" + path
125+
outputDirectory := currentDirectory.HomeDir + "/Downloads/" + path
167126
outputFile := filepath.Join(outputDirectory, file)
168127
if err := os.MkdirAll(filepath.Dir(outputFile), 0775); err != nil {
169128
logrus.Errorf("Unable to create output directory: %v", err)
@@ -177,7 +136,7 @@ func encodeVideoStream(file, path, surl string) error {
177136
defer fp.Close()
178137

179138
//saving downloaded file.
180-
if _, err = io.Copy(fp, resp.Body); err != nil {
139+
if _, err = fp.Write(data); err != nil {
181140
logrus.Errorf("Unable to encode video stream: %s `->` %v", surl, err)
182141
return err
183142
}
@@ -186,7 +145,7 @@ func encodeVideoStream(file, path, surl string) error {
186145

187146
// downloadVideoStream downloads video streams from youtube
188147
// downloadVideoStream returns the *http.Reponse body
189-
func downloadVideoStream(url string) (*http.Response, error) {
148+
func downloadVideoStream(url string) ([]byte, error) {
190149
resp, err := http.Get(url)
191150
if err != nil {
192151
logrus.Errorf("Unable to fetch Data stream from URL(%s)\n: %v", url, err)
@@ -199,7 +158,9 @@ func downloadVideoStream(url string) (*http.Response, error) {
199158
return nil, errors.New("Non 200 status code received")
200159
}
201160

202-
return resp, nil
161+
output, _ := ioutil.ReadAll(resp.Body)
162+
163+
return output, nil
203164
}
204165

205166
// getVideoId extracts the video id string from youtube url
@@ -221,6 +182,38 @@ func getVideoId(url string) (string, error) {
221182
}
222183
}
223184

185+
// decodeStream accept Values and decodes them individually
186+
// decodeStream returns the final RawVideoStream object
187+
func decodeStream(values url.Values, streams *RawVideoStream, rawstream []stream) error {
188+
streams.Author = values.Get("author")
189+
streams.Title = values.Get("title")
190+
streamMap := values.Get("url_encoded_fmt_stream_map")
191+
192+
// read and decode streams
193+
streamsList := strings.Split(string(streamMap), ",")
194+
for streamPos, streamRaw := range streamsList {
195+
streamQry, err := url.ParseQuery(streamRaw)
196+
if err != nil {
197+
logrus.Infof("Error occured during stream decoding %d: %s\n", streamPos, err)
198+
continue
199+
}
200+
var sig string
201+
sig = streamQry.Get("sig")
202+
rawstream = append(rawstream, stream{
203+
"quality": streamQry.Get("quality"),
204+
"type": streamQry.Get("type"),
205+
"url": streamQry.Get("url"),
206+
"sig": sig,
207+
"title": values.Get("title"),
208+
"author": values.Get("author"),
209+
})
210+
logrus.Infof("Stream found: quality '%s', format '%s'", streamQry.Get("quality"), streamQry.Get("type"))
211+
}
212+
213+
streams.URLEncodedFmtStreamMap = rawstream
214+
return nil
215+
}
216+
224217
// decodeVideoStream processes downloaded video stream and
225218
// decodeVideoStream calls helper functions and writes the
226219
// output in the required format
@@ -232,13 +225,12 @@ func decodeVideoStream(videoId, path, format string, bitrate uint) error {
232225
rawVideo.VideoId = videoId
233226
rawVideo.VideoInfo = streamApiUrl + videoId
234227

235-
videoStream, err := downloadVideoStream(rawVideo.VideoInfo)
228+
data, err := downloadVideoStream(rawVideo.VideoInfo)
236229
if err != nil {
237230
logrus.Errorf("Unable to get video stream: %v", err)
238231
return err
239232
}
240233

241-
data, _ := ioutil.ReadAll(videoStream.Body)
242234
parsedResp, err := url.ParseQuery(string(data))
243235
if err != nil {
244236
logrus.Errorf("Error parsing video byte stream: %v", err)
@@ -261,10 +253,10 @@ func decodeVideoStream(videoId, path, format string, bitrate uint) error {
261253
return errors.New("Unable to decode raw video streams")
262254
}
263255

264-
file := removeWhiteSpace(rawVideo.Title + fixExtension(format))
256+
file := removeWhiteSpace(rawVideo.Title) + fixExtension(format)
265257
surl := decStreams[0]["url"] + "&signature" + decStreams[0]["sig"]
266-
logrus.Infof("Downloading data to file: %s", file)
267258

259+
logrus.Infof("Downloading data to file: %s", file)
268260
if strings.Contains(file, "mp3") {
269261
if err := encodeAudioStream(file, path, surl, bitrate); err != nil {
270262
logrus.Errorf("Unable to encode %s: %v", format, err)

main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
4242
func init() {
4343
// parse flags
4444
flag.StringVar(&ids, "id", "", "video url or video id; separate multiple ids with a comma.")
45-
flag.StringVar(&format, "format", "", "download file format(mp3 or flv)")
45+
flag.StringVar(&format, "format", "flv", "download file format(mp3 or flv)")
4646
flag.StringVar(&path, "path", ".", "download file path")
4747
flag.BoolVar(&version, "version", false, "print version number")
4848
flag.UintVar(&bitrate, "bitrate", 192, "audio bitrate")

0 commit comments

Comments
 (0)