9 "github.com/anacrolix/missinggo"
10 "golang.org/x/net/context"
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) {
93 req, ok := r.t.offsetRequest(off)
97 if !r.t.haveChunk(req) {
100 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
105 // Ensure that ret hasn't exceeded our original max.
112 func (r *reader) waitReadable(off int64) {
113 // We may have been sent back here because we were told we could read but
118 // Calculates the pieces this reader wants downloaded, ignoring the cached
119 // value at r.pieces.
120 func (r *reader) piecesUncached() (ret pieceRange) {
123 // Needs to be at least 1, because [x, x) means we don't want
127 if ra > r.length-r.pos {
128 ra = r.length - r.pos
130 ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
134 func (r *reader) Read(b []byte) (n int, err error) {
135 return r.ReadContext(context.Background(), b)
138 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
139 // This is set under the Client lock if the Context is canceled.
141 if ctx.Done() != nil {
142 ctx, cancel := context.WithCancel(ctx)
143 // Abort the goroutine when the function returns.
149 r.t.cl.event.Broadcast()
153 // Hmmm, if a Read gets stuck, this means you can't change position for
154 // other purposes. That seems reasonable, but unusual.
156 defer r.opMu.Unlock()
159 n1, err = r.readOnceAt(b, r.pos, &ctxErr)
162 panic("expected error")
173 if r.pos >= r.length {
175 } else if err == io.EOF {
176 err = io.ErrUnexpectedEOF
181 // Wait until some data should be available to read. Tickles the client if it
182 // isn't. Returns how much should be readable without blocking.
183 func (r *reader) waitAvailable(pos, wanted int64, ctxErr *error) (avail int64) {
185 defer r.t.cl.mu.Unlock()
186 for !r.readable(pos) && *ctxErr == nil {
189 return r.available(pos, wanted)
192 func (r *reader) torrentOffset(readerPos int64) int64 {
193 return r.offset + readerPos
196 // Performs at most one successful read to torrent storage.
197 func (r *reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) {
203 avail := r.waitAvailable(pos, int64(len(b)), ctxErr)
205 if r.t.closed.IsSet() {
206 err = errors.New("torrent closed")
214 pi := int(r.torrentOffset(pos) / r.t.info.PieceLength)
215 ip := r.t.info.Piece(pi)
216 po := r.torrentOffset(pos) % r.t.info.PieceLength
217 b1 := missinggo.LimitLen(b, ip.Length()-po, avail)
218 n, err = r.t.readAt(b1, r.torrentOffset(pos))
224 log.Printf("error reading torrent %q piece %d offset %d, %d bytes: %s", r.t, pi, po, len(b1), err)
225 r.t.updateAllPieceCompletions()
226 r.t.updateAllPiecePriorities()
231 func (r *reader) Close() error {
233 defer r.t.cl.mu.Unlock()
238 func (r *reader) posChanged() {
239 to := r.piecesUncached()
245 r.t.readerPosChanged(from, to)
248 func (r *reader) Seek(off int64, whence int) (ret int64, err error) {
250 defer r.opMu.Unlock()
260 r.pos = r.length + off
262 err = errors.New("bad whence")