10 "github.com/anacrolix/missinggo"
12 "github.com/anacrolix/torrent/peer_protocol"
15 type Reader interface {
19 missinggo.ReadContexter
24 // Piece range by piece index, [begin, end).
25 type pieceRange struct {
29 // Accesses Torrent data via a Client. Reads block until the data is
30 // available. Seeks and readahead also drive Client behaviour.
34 // Adjust the read/seek window to handle Readers locked to File extents
37 // Ensure operations that change the position are exclusive, like Read()
41 // Required when modifying pos and readahead, or reading them without
46 // The cached piece range this reader wants downloaded. The zero value
47 // corresponds to nothing. We cache this so that changes can be detected,
48 // and bubbled up to the Torrent only as required.
52 var _ io.ReadCloser = &reader{}
54 // Don't wait for pieces to complete and be verified. Read calls return as
55 // soon as they can when the underlying chunks become available.
56 func (r *reader) SetResponsive() {
58 r.t.cl.event.Broadcast()
61 // Disable responsive mode. TODO: Remove?
62 func (r *reader) SetNonResponsive() {
64 r.t.cl.event.Broadcast()
67 // Configure the number of bytes ahead of a read that should also be
68 // prioritized in preparation for further reads.
69 func (r *reader) SetReadahead(readahead int64) {
71 r.readahead = readahead
78 func (r *reader) readable(off int64) (ret bool) {
79 if r.t.closed.IsSet() {
82 req, ok := r.t.offsetRequest(r.torrentOffset(off))
87 return r.t.haveChunk(req)
89 return r.t.pieceComplete(pieceIndex(req.Index))
92 // How many bytes are available to read. Max is the most we could require.
93 func (r *reader) available(off, max int64) (ret int64) {
96 req, ok := r.t.offsetRequest(off)
100 if !r.t.haveChunk(req) {
103 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
108 // Ensure that ret hasn't exceeded our original max.
115 func (r *reader) waitReadable(off int64) {
116 // We may have been sent back here because we were told we could read but
121 // Calculates the pieces this reader wants downloaded, ignoring the cached
122 // value at r.pieces.
123 func (r *reader) piecesUncached() (ret pieceRange) {
126 // Needs to be at least 1, because [x, x) means we don't want
130 if ra > r.length-r.pos {
131 ra = r.length - r.pos
133 ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
137 func (r *reader) Read(b []byte) (n int, err error) {
138 return r.ReadContext(context.Background(), b)
141 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
142 // This is set under the Client lock if the Context is canceled.
144 if ctx.Done() != nil {
145 ctx, cancel := context.WithCancel(ctx)
146 // Abort the goroutine when the function returns.
156 // Hmmm, if a Read gets stuck, this means you can't change position for
157 // other purposes. That seems reasonable, but unusual.
159 defer r.opMu.Unlock()
162 n1, err = r.readOnceAt(b, r.pos, &ctxErr)
165 panic("expected error")
176 if r.pos >= r.length {
178 } else if err == io.EOF {
179 err = io.ErrUnexpectedEOF
184 // Wait until some data should be available to read. Tickles the client if it
185 // isn't. Returns how much should be readable without blocking.
186 func (r *reader) waitAvailable(pos, wanted int64, ctxErr *error) (avail int64) {
188 defer r.t.cl.unlock()
189 for !r.readable(pos) && *ctxErr == nil {
192 return r.available(pos, wanted)
195 func (r *reader) torrentOffset(readerPos int64) int64 {
196 return r.offset + readerPos
199 // Performs at most one successful read to torrent storage.
200 func (r *reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) {
206 avail := r.waitAvailable(pos, int64(len(b)), ctxErr)
208 if r.t.closed.IsSet() {
209 err = errors.New("torrent closed")
217 pi := peer_protocol.Integer(r.torrentOffset(pos) / r.t.info.PieceLength)
218 ip := r.t.info.Piece(int(pi))
219 po := r.torrentOffset(pos) % r.t.info.PieceLength
220 b1 := missinggo.LimitLen(b, ip.Length()-po, 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 log.Printf("error reading torrent %q piece %d offset %d, %d bytes: %s", r.t, pi, po, len(b1), err)
230 r.t.updateAllPieceCompletions()
231 r.t.updateAllPiecePriorities()
236 func (r *reader) Close() error {
238 defer r.t.cl.unlock()
243 func (r *reader) posChanged() {
244 to := r.piecesUncached()
250 // log.Printf("reader pos changed %v->%v", from, to)
251 r.t.readerPosChanged(from, to)
254 func (r *reader) Seek(off int64, whence int) (ret int64, err error) {
256 defer r.opMu.Unlock()
266 r.pos = r.length + off
268 err = errors.New("bad whence")