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 func (r *reader) readable(off int64) (ret bool) {
77 if r.t.closed.IsSet() {
80 req, ok := r.t.offsetRequest(r.torrentOffset(off))
85 return r.t.haveChunk(req)
87 return r.t.pieceComplete(pieceIndex(req.Index))
90 // How many bytes are available to read. Max is the most we could require.
91 func (r *reader) available(off, max int64) (ret int64) {
94 req, ok := r.t.offsetRequest(off)
98 if !r.responsive && !r.t.pieceComplete(pieceIndex(req.Index)) {
101 if !r.t.haveChunk(req) {
104 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
109 // Ensure that ret hasn't exceeded our original max.
116 func (r *reader) waitReadable(off int64) {
117 // We may have been sent back here because we were told we could read but
122 // Calculates the pieces this reader wants downloaded, ignoring the cached
123 // value at r.pieces.
124 func (r *reader) piecesUncached() (ret pieceRange) {
127 // Needs to be at least 1, because [x, x) means we don't want
131 if ra > r.length-r.pos {
132 ra = r.length - r.pos
134 ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
138 func (r *reader) Read(b []byte) (n int, err error) {
139 return r.ReadContext(context.Background(), b)
142 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
143 // This is set under the Client lock if the Context is canceled.
145 if ctx.Done() != nil {
146 ctx, cancel := context.WithCancel(ctx)
147 // Abort the goroutine when the function returns.
157 // Hmmm, if a Read gets stuck, this means you can't change position for
158 // other purposes. That seems reasonable, but unusual.
160 defer r.opMu.Unlock()
163 n1, err = r.readOnceAt(b, r.pos, &ctxErr)
166 panic("expected error")
177 if r.pos >= r.length {
179 } else if err == io.EOF {
180 err = io.ErrUnexpectedEOF
185 // Wait until some data should be available to read. Tickles the client if it
186 // isn't. Returns how much should be readable without blocking.
187 func (r *reader) waitAvailable(pos, wanted int64, ctxErr *error) (avail int64, err error) {
189 defer r.t.cl.unlock()
191 avail = r.available(pos, wanted)
195 if r.t.closed.IsSet() {
196 err = errors.New("torrent closed")
207 // Adds the reader's torrent offset to the reader object offset (for example the reader might be
208 // constrainted to a particular file within the torrent).
209 func (r *reader) torrentOffset(readerPos int64) int64 {
210 return r.offset + readerPos
213 // Performs at most one successful read to torrent storage.
214 func (r *reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) {
221 avail, err = r.waitAvailable(pos, int64(len(b)), ctxErr)
225 firstPieceIndex := pieceIndex(r.torrentOffset(pos) / r.t.info.PieceLength)
226 firstPieceOffset := r.torrentOffset(pos) % r.t.info.PieceLength
227 b1 := missinggo.LimitLen(b, avail)
228 n, err = r.t.readAt(b1, r.torrentOffset(pos))
234 // TODO: Just reset pieces in the readahead window. This might help
235 // prevent thrashing with small caches and file and piece priorities.
236 r.log(log.Fstr("error reading torrent %s piece %d offset %d, %d bytes: %v",
237 r.t.infoHash.HexString(), firstPieceIndex, firstPieceOffset, len(b1), err))
238 if !r.t.updatePieceCompletion(firstPieceIndex) {
239 r.log(log.Fstr("piece %d completion unchanged", firstPieceIndex))
245 func (r *reader) Close() error {
247 defer r.t.cl.unlock()
252 func (r *reader) posChanged() {
253 to := r.piecesUncached()
259 // log.Printf("reader pos changed %v->%v", from, to)
260 r.t.readerPosChanged(from, to)
263 func (r *reader) Seek(off int64, whence int) (ret int64, err error) {
265 defer r.opMu.Unlock()
275 r.pos = r.length + off
277 err = errors.New("bad whence")
285 func (r *reader) log(m log.Msg) {
286 r.t.logger.Log(m.Skip(1))