9 "github.com/anacrolix/missinggo"
10 "golang.org/x/net/context"
13 // Piece range by piece index, [begin, end).
14 type pieceRange struct {
18 // Accesses Torrent data via a Client. Reads block until the data is
19 // available. Seeks and readahead also drive Client behaviour.
23 // Ensure operations that change the position are exclusive, like Read()
27 // Required when modifying pos and readahead, or reading them without
32 // The cached piece range this reader wants downloaded. The zero value
33 // corresponds to nothing. We cache this so that changes can be detected,
34 // and bubbled up to the Torrent only as required.
38 var _ io.ReadCloser = &Reader{}
40 // Don't wait for pieces to complete and be verified. Read calls return as
41 // soon as they can when the underlying chunks become available.
42 func (r *Reader) SetResponsive() {
46 // Disable responsive mode.
47 func (r *Reader) SetNonResponsive() {
51 // Configure the number of bytes ahead of a read that should also be
52 // prioritized in preparation for further reads.
53 func (r *Reader) SetReadahead(readahead int64) {
55 r.readahead = readahead
58 defer r.t.cl.mu.Unlock()
62 // Return reader's current position.
63 func (r *Reader) CurrentPos() int64 {
67 func (r *Reader) readable(off int64) (ret bool) {
68 if r.t.closed.IsSet() {
71 req, ok := r.t.offsetRequest(off)
76 return r.t.haveChunk(req)
78 return r.t.pieceComplete(int(req.Index))
81 // How many bytes are available to read. Max is the most we could require.
82 func (r *Reader) available(off, max int64) (ret int64) {
84 req, ok := r.t.offsetRequest(off)
88 if !r.t.haveChunk(req) {
91 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
96 // Ensure that ret hasn't exceeded our original max.
103 func (r *Reader) waitReadable(off int64) {
104 // We may have been sent back here because we were told we could read but
109 // Calculates the pieces this reader wants downloaded, ignoring the cached
110 // value at r.pieces.
111 func (r *Reader) piecesUncached() (ret pieceRange) {
116 ret.begin, ret.end = r.t.byteRegionPieces(r.pos, ra)
120 func (r *Reader) Read(b []byte) (n int, err error) {
121 return r.ReadContext(context.Background(), b)
124 func (r *Reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
125 // This is set under the Client lock if the Context is canceled.
127 if ctx.Done() != nil {
128 ctx, cancel := context.WithCancel(ctx)
129 // Abort the goroutine when the function returns.
135 r.t.cl.event.Broadcast()
139 // Hmmm, if a Read gets stuck, this means you can't change position for
140 // other purposes. That seems reasonable, but unusual.
142 defer r.opMu.Unlock()
145 n1, err = r.readOnceAt(b, r.pos, &ctxErr)
148 panic("expected error")
159 if r.pos >= r.t.length {
161 } else if err == io.EOF {
162 err = io.ErrUnexpectedEOF
167 // Wait until some data should be available to read. Tickles the client if it
168 // isn't. Returns how much should be readable without blocking.
169 func (r *Reader) waitAvailable(pos, wanted int64, ctxErr *error) (avail int64) {
171 defer r.t.cl.mu.Unlock()
172 for !r.readable(pos) && *ctxErr == nil {
175 return r.available(pos, wanted)
178 // Performs at most one successful read to torrent storage.
179 func (r *Reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) {
180 if pos >= r.t.length {
185 avail := r.waitAvailable(pos, int64(len(b)), ctxErr)
187 if r.t.closed.IsSet() {
188 err = errors.New("torrent closed")
197 pi := int(pos / r.t.info.PieceLength)
198 ip := r.t.info.Piece(pi)
199 po := pos % r.t.info.PieceLength
200 missinggo.LimitLen(&b1, ip.Length()-po)
201 n, err = r.t.readAt(b1, pos)
207 log.Printf("error reading torrent %q piece %d offset %d, %d bytes: %s", r.t, pi, po, len(b1), err)
208 r.t.updateAllPieceCompletions()
209 r.t.updateAllPiecePriorities()
214 func (r *Reader) Close() error {
216 defer r.t.cl.mu.Unlock()
221 func (r *Reader) posChanged() {
222 to := r.piecesUncached()
228 r.t.readerPosChanged(from, to)
231 func (r *Reader) Seek(off int64, whence int) (ret int64, err error) {
233 defer r.opMu.Unlock()
243 r.pos = r.t.info.TotalLength() + off
245 err = errors.New("bad whence")
253 func (r *Reader) Torrent() *Torrent {