Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Doesn't stream content to the file. #152

Open
AYehia0 opened this issue Jan 11, 2023 · 2 comments
Open

Doesn't stream content to the file. #152

AYehia0 opened this issue Jan 11, 2023 · 2 comments
Labels

Comments

@AYehia0
Copy link

AYehia0 commented Jan 11, 2023

Hello, excuse my question I am still a beginner in go 馃槃
I am trying to stream the segments of the m3u8 into one file by appending to the file created, but unfortunately it's doesn't and returns empty file.

// extract the urls of the individual segment and then steam/download.
func downloadSeg(wg *sync.WaitGroup, segment *m.MediaSegment, file *os.File, dlbar *bar.ProgressBar) {
	defer wg.Done()
	resp, err := http.Get(segment.URI)

	log.Println("Error : ", resp.StatusCode)
	if err != nil {
		log.Println("Error : ", err)
		return
	}

	defer resp.Body.Close()

	// append to the file
	_, err = io.Copy(io.MultiWriter(file, dlbar), resp.Body)

	if err != nil {
		log.Println("Error : ", err)
		return
	}

}

// using the goroutine to download each segment concurrently and wait till all finished
func downloadM3u8(m3u8Url string, filepath string) error {
	resp, err := http.Get(m3u8Url)

	if err != nil {
		return err
	}
	defer resp.Body.Close()

	pl, listType, err := m.DecodeFrom(resp.Body, true)
	if err != nil {
		return err
	}
	dlbar := bar.DefaultBytes(resp.ContentLength, "Downloading")
	// create a file to add content to
	// file, _ := os.OpenFile(filepath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
	file, _ := os.Create(filepath)

	// the go routine now
	var wg sync.WaitGroup
	switch listType {
	case m.MEDIA:
		mediapl := pl.(*m.MediaPlaylist)
		for _, segment := range mediapl.Segments {
			if segment == nil {
				continue
			}
			wg.Add(1)
			go downloadSeg(&wg, segment, file, dlbar)
		}
	default:
		return errors.New("Unsupported type!")
	}

	return nil
}

I call downloadM3u8(track.Url, path) after that.

@AYehia0
Copy link
Author

AYehia0 commented Jan 11, 2023

for some reasons removing the go keyword before the downloadSeg solves the problem, IDK why lol.

@WheeskyJack
Copy link

I think you missed calling wg.Wait() in the end. hence , program is exiting even before all go routines are done. adding wg.Wait() before return nil, will help I guess.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants