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
72 defer r.t.cl.mu.Unlock()
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(int(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.t.haveChunk(req) {
101 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
106 // Ensure that ret hasn't exceeded our original max.
113 func (r *reader) waitReadable(off int64) {
114 // We may have been sent back here because we were told we could read but
119 // Calculates the pieces this reader wants downloaded, ignoring the cached
120 // value at r.pieces.
121 func (r *reader) piecesUncached() (ret pieceRange) {
124 // Needs to be at least 1, because [x, x) means we don't want
128 if ra > r.length-r.pos {
129 ra = r.length - r.pos
131 ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
135 func (r *reader) Read(b []byte) (n int, err error) {
136 return r.ReadContext(context.Background(), b)
139 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
140 // This is set under the Client lock if the Context is canceled.
142 if ctx.Done() != nil {
143 ctx, cancel := context.WithCancel(ctx)
144 // Abort the goroutine when the function returns.
150 r.t.cl.event.Broadcast()
154 // Hmmm, if a Read gets stuck, this means you can't change position for
155 // other purposes. That seems reasonable, but unusual.
157 defer r.opMu.Unlock()
160 n1, err = r.readOnceAt(b, r.pos, &ctxErr)
163 panic("expected error")
174 if r.pos >= r.length {
176 } else if err == io.EOF {
177 err = io.ErrUnexpectedEOF
182 // Wait until some data should be available to read. Tickles the client if it
183 // isn't. Returns how much should be readable without blocking.
184 func (r *reader) waitAvailable(pos, wanted int64, ctxErr *error) (avail int64) {
186 defer r.t.cl.mu.Unlock()
187 for !r.readable(pos) && *ctxErr == nil {
190 return r.available(pos, wanted)
193 func (r *reader) torrentOffset(readerPos int64) int64 {
194 return r.offset + readerPos
197 // Performs at most one successful read to torrent storage.
198 func (r *reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) {
204 avail := r.waitAvailable(pos, int64(len(b)), ctxErr)
206 if r.t.closed.IsSet() {
207 err = errors.New("torrent closed")
215 pi := int(r.torrentOffset(pos) / r.t.info.PieceLength)
216 ip := r.t.info.Piece(pi)
217 po := r.torrentOffset(pos) % r.t.info.PieceLength
218 b1 := missinggo.LimitLen(b, ip.Length()-po, avail)
219 n, err = r.t.readAt(b1, r.torrentOffset(pos))
225 // TODO: Just reset pieces in the readahead window. This might help
226 // prevent thrashing with small caches and file and piece priorities.
227 log.Printf("error reading torrent %q piece %d offset %d, %d bytes: %s", r.t, pi, po, len(b1), err)
228 r.t.updateAllPieceCompletions()
229 r.t.updateAllPiecePriorities()
234 func (r *reader) Close() error {
236 defer r.t.cl.mu.Unlock()
241 func (r *reader) posChanged() {
242 to := r.piecesUncached()
248 // log.Printf("reader pos changed %v->%v", from, to)
249 r.t.readerPosChanged(from, to)
252 func (r *reader) Seek(off int64, whence int) (ret int64, err error) {
254 defer r.opMu.Unlock()
264 r.pos = r.length + off
266 err = errors.New("bad whence")