9 "github.com/anacrolix/log"
10 "github.com/anacrolix/missinggo"
13 type Reader interface {
17 missinggo.ReadContexter
22 // Piece range by piece index, [begin, end).
23 type pieceRange struct {
27 // Accesses Torrent data via a Client. Reads block until the data is
28 // available. Seeks and readahead also drive Client behaviour.
32 // Adjust the read/seek window to handle Readers locked to File extents
35 // Ensure operations that change the position are exclusive, like Read()
39 // Required when modifying pos and readahead, or reading them without
44 // The cached piece range this reader wants downloaded. The zero value
45 // corresponds to nothing. We cache this so that changes can be detected,
46 // and bubbled up to the Torrent only as required.
50 var _ io.ReadCloser = &reader{}
52 // Don't wait for pieces to complete and be verified. Read calls return as
53 // soon as they can when the underlying chunks become available.
54 func (r *reader) SetResponsive() {
56 r.t.cl.event.Broadcast()
59 // Disable responsive mode. TODO: Remove?
60 func (r *reader) SetNonResponsive() {
62 r.t.cl.event.Broadcast()
65 // Configure the number of bytes ahead of a read that should also be
66 // prioritized in preparation for further reads.
67 func (r *reader) SetReadahead(readahead int64) {
69 r.readahead = readahead
76 // How many bytes are available to read. Max is the most we could require.
77 func (r *reader) available(off, max int64) (ret int64) {
80 req, ok := r.t.offsetRequest(off)
84 if !r.responsive && !r.t.pieceComplete(pieceIndex(req.Index)) {
87 if !r.t.haveChunk(req) {
90 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
95 // Ensure that ret hasn't exceeded our original max.
102 func (r *reader) waitReadable(off int64) {
103 // We may have been sent back here because we were told we could read but
108 // Calculates the pieces this reader wants downloaded, ignoring the cached
109 // value at r.pieces.
110 func (r *reader) piecesUncached() (ret pieceRange) {
113 // Needs to be at least 1, because [x, x) means we don't want
117 if ra > r.length-r.pos {
118 ra = r.length - r.pos
120 ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
124 func (r *reader) Read(b []byte) (n int, err error) {
125 return r.ReadContext(context.Background(), b)
128 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
129 // This is set under the Client lock if the Context is canceled. I think we coordinate on a
130 // separate variable so as to avoid false negatives with race conditions due to Contexts being
133 if ctx.Done() != nil {
134 ctx, cancel := context.WithCancel(ctx)
135 // Abort the goroutine when the function returns.
145 // Hmmm, if a Read gets stuck, this means you can't change position for
146 // other purposes. That seems reasonable, but unusual.
148 defer r.opMu.Unlock()
149 n, err = r.readOnceAt(b, r.pos, &ctxErr)
152 panic("expected error")
162 if r.pos >= r.length {
164 } else if err == io.EOF {
165 err = io.ErrUnexpectedEOF
170 // Wait until some data should be available to read. Tickles the client if it
171 // isn't. Returns how much should be readable without blocking.
172 func (r *reader) waitAvailable(pos, wanted int64, ctxErr *error, wait bool) (avail int64, err error) {
174 defer r.t.cl.unlock()
176 avail = r.available(pos, wanted)
180 if r.t.closed.IsSet() {
181 err = errors.New("torrent closed")
188 if r.t.dataDownloadDisallowed || !r.t.networkingEnabled {
189 err = errors.New("downloading disabled and data not already available")
199 // Adds the reader's torrent offset to the reader object offset (for example the reader might be
200 // constrainted to a particular file within the torrent).
201 func (r *reader) torrentOffset(readerPos int64) int64 {
202 return r.offset + readerPos
205 // Performs at most one successful read to torrent storage.
206 func (r *reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) {
213 avail, err = r.waitAvailable(pos, int64(len(b)), ctxErr, n == 0)
217 firstPieceIndex := pieceIndex(r.torrentOffset(pos) / r.t.info.PieceLength)
218 firstPieceOffset := r.torrentOffset(pos) % r.t.info.PieceLength
219 b1 := missinggo.LimitLen(b, avail)
220 n, err = r.t.readAt(b1, r.torrentOffset(pos))
226 // TODO: Just reset pieces in the readahead window. This might help
227 // prevent thrashing with small caches and file and piece priorities.
228 r.log(log.Fstr("error reading torrent %s piece %d offset %d, %d bytes: %v",
229 r.t.infoHash.HexString(), firstPieceIndex, firstPieceOffset, len(b1), err))
230 if !r.t.updatePieceCompletion(firstPieceIndex) {
231 r.log(log.Fstr("piece %d completion unchanged", firstPieceIndex))
237 func (r *reader) Close() error {
239 defer r.t.cl.unlock()
244 func (r *reader) posChanged() {
245 to := r.piecesUncached()
251 // log.Printf("reader pos changed %v->%v", from, to)
252 r.t.readerPosChanged(from, to)
255 func (r *reader) Seek(off int64, whence int) (ret int64, err error) {
257 defer r.opMu.Unlock()
267 r.pos = r.length + off
269 err = errors.New("bad whence")
277 func (r *reader) log(m log.Msg) {
278 r.t.logger.Log(m.Skip(1))