10 "github.com/anacrolix/log"
11 "github.com/anacrolix/missinggo/v2"
14 // Accesses Torrent data via a Client. Reads block until the data is available. Seeks and readahead
15 // also drive Client behaviour.
16 type Reader interface {
18 missinggo.ReadContexter
19 // Configure the number of bytes ahead of a read that should also be prioritized in preparation
22 // Don't wait for pieces to complete and be verified. Read calls return as soon as they can when
23 // the underlying chunks become available.
27 // Piece range by piece index, [begin, end).
28 type pieceRange struct {
34 // Adjust the read/seek window to handle Readers locked to File extents and the like.
37 // Function to dynamically calculate readahead. If nil, readahead is static.
38 readaheadFunc func() int64
40 // Required when modifying pos and readahead.
44 // Position that reads have continued contiguously from.
45 contiguousReadStartPos int64
46 // The cached piece range this reader wants downloaded. The zero value corresponds to nothing.
47 // We cache this so that changes can be detected, and bubbled up to the Torrent only as
51 // Reads have been initiated since the last seek. This is used to prevent readaheads occurring
52 // after a seek or with a new reader at the starting position.
57 var _ io.ReadSeekCloser = (*reader)(nil)
59 func (r *reader) SetResponsive() {
61 r.t.cl.event.Broadcast()
64 // Disable responsive mode. TODO: Remove?
65 func (r *reader) SetNonResponsive() {
67 r.t.cl.event.Broadcast()
70 func (r *reader) SetReadahead(readahead int64) {
72 r.readahead = readahead
78 // How many bytes are available to read. Max is the most we could require.
79 func (r *reader) available(off, max int64) (ret int64) {
82 req, ok := r.t.offsetRequest(off)
86 if !r.responsive && !r.t.pieceComplete(pieceIndex(req.Index)) {
89 if !r.t.haveChunk(req) {
92 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
97 // Ensure that ret hasn't exceeded our original max.
104 // Calculates the pieces this reader wants downloaded, ignoring the cached value at r.pieces.
105 func (r *reader) piecesUncached() (ret pieceRange) {
107 if r.readaheadFunc != nil {
108 ra = r.readaheadFunc()
111 // Needs to be at least 1, because [x, x) means we don't want
118 if ra > r.length-r.pos {
119 ra = r.length - r.pos
121 ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
125 func (r *reader) Read(b []byte) (n int, err error) {
126 return r.ReadContext(context.Background(), b)
129 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
132 // TODO: Rework reader piece priorities so we don't have to push updates in to the Client
133 // and take the lock here.
138 n, err = r.readOnceAt(ctx, b, r.pos)
140 if err == nil && len(b) > 0 {
141 panic("expected error")
151 if r.pos >= r.length {
153 } else if err == io.EOF {
154 err = io.ErrUnexpectedEOF
159 var closedChan = make(chan struct{})
165 // Wait until some data should be available to read. Tickles the client if it isn't. Returns how
166 // much should be readable without blocking.
167 func (r *reader) waitAvailable(ctx context.Context, pos, wanted int64, wait bool) (avail int64, err error) {
171 avail = r.available(pos, wanted)
172 readerCond := t.piece(int((r.offset + pos) / t.info.PieceLength)).readerCond.Signaled()
177 var dontWait <-chan struct{}
178 if !wait || wanted == 0 {
179 dontWait = closedChan
182 case <-r.t.closed.Done():
183 err = errors.New("torrent closed")
188 case <-r.t.dataDownloadDisallowed.On():
189 err = errors.New("torrent data downloading disabled")
190 case <-r.t.networkingEnabled.Off():
191 err = errors.New("torrent networking disabled")
200 // Adds the reader's torrent offset to the reader object offset (for example the reader might be
201 // constrainted to a particular file within the torrent).
202 func (r *reader) torrentOffset(readerPos int64) int64 {
203 return r.offset + readerPos
206 // Performs at most one successful read to torrent storage.
207 func (r *reader) readOnceAt(ctx context.Context, b []byte, pos int64) (n int, err error) {
214 avail, err = r.waitAvailable(ctx, pos, int64(len(b)), n == 0)
218 firstPieceIndex := pieceIndex(r.torrentOffset(pos) / r.t.info.PieceLength)
219 firstPieceOffset := r.torrentOffset(pos) % r.t.info.PieceLength
220 b1 := missinggo.LimitLen(b, avail)
221 n, err = r.t.readAt(b1, r.torrentOffset(pos))
227 // TODO: Just reset pieces in the readahead window. This might help
228 // prevent thrashing with small caches and file and piece priorities.
229 r.log(log.Fstr("error reading torrent %s piece %d offset %d, %d bytes: %v",
230 r.t.infoHash.HexString(), firstPieceIndex, firstPieceOffset, len(b1), err))
231 if !r.t.updatePieceCompletion(firstPieceIndex) {
232 r.log(log.Fstr("piece %d completion unchanged", firstPieceIndex))
234 // Update the rest of the piece completions in the readahead window, without alerting to
235 // changes (since only the first piece, the one above, could have generated the read error
236 // we're currently handling).
237 if r.pieces.begin != firstPieceIndex {
238 panic(fmt.Sprint(r.pieces.begin, firstPieceIndex))
240 for index := r.pieces.begin + 1; index < r.pieces.end; index++ {
241 r.t.updatePieceCompletion(index)
248 func (r *reader) Close() error {
255 func (r *reader) posChanged() {
256 to := r.piecesUncached()
262 // log.Printf("reader pos changed %v->%v", from, to)
263 r.t.readerPosChanged(from, to)
266 func (r *reader) Seek(off int64, whence int) (newPos int64, err error) {
275 newPos = r.length + off
278 return 0, errors.New("bad whence")
283 r.contiguousReadStartPos = newPos
290 func (r *reader) log(m log.Msg) {
291 r.t.logger.Log(m.Skip(1))
294 // Implementation inspired by https://news.ycombinator.com/item?id=27019613.
295 func (r *reader) defaultReadaheadFunc() int64 {
296 return r.pos - r.contiguousReadStartPos