From 1b3e03b7d0a3bd9a2932871b867eb51d2899625a Mon Sep 17 00:00:00 2001 From: ChienNM3 Date: Wed, 24 Jan 2024 20:58:33 +0700 Subject: [PATCH] Try to improve download speed --- handler/handler_video_player.go | 9 ++++++++- torrent/manager_state.go | 21 +++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 torrent/manager_state.go diff --git a/handler/handler_video_player.go b/handler/handler_video_player.go index 5915e21..6a8bfac 100644 --- a/handler/handler_video_player.go +++ b/handler/handler_video_player.go @@ -22,6 +22,12 @@ func (h *Handler) Watch(w http.ResponseWriter, r *http.Request, infoHash, fileNa return } + // This step is for speed up the download! + if err := h.torrentManager.CancelOthers(infoHash); err != nil { + handleError(w, r, "Cancel others", err, http.StatusBadRequest) + return + } + _ = ui.VideoPlayer(torrentInfo, fileName).Render(r.Context(), w) } @@ -33,9 +39,10 @@ func (h *Handler) Stream(w http.ResponseWriter, r *http.Request, infoHash, fileN } // TODO: Maybe implement more effective file reader to seed up the download + file.Download() reader := file.NewReader() reader.SetResponsive() - reader.SetReadahead(file.Length() / 100) // Read ahead 1% of the file + //reader.SetReadahead(file.Length() / 100) // Read ahead 1% of the file mime, err := mimetype.DetectReader(reader) if err != nil { diff --git a/torrent/manager_state.go b/torrent/manager_state.go new file mode 100644 index 0000000..80a8309 --- /dev/null +++ b/torrent/manager_state.go @@ -0,0 +1,21 @@ +package torrent + +import ( + "fmt" +) + +// CancelOthers cancels all pieces of all torrents except the one with the given info hash. +func (m *Manager) CancelOthers(infoHash string) error { + infoHashHex, err := infoHashFromHexString(infoHash) + if err != nil { + return fmt.Errorf("parse infohash: %w", err) + } + + for _, tor := range m.client.Torrents() { + if tor.InfoHash() != infoHashHex { + tor.CancelPieces(0, tor.NumPieces()) + } + } + + return nil +}