10 "github.com/anacrolix/missinggo"
11 "golang.org/x/net/context"
14 // Piece range by piece index, [begin, end).
15 type pieceRange struct {
19 // Accesses Torrent data via a Client. Reads block until the data is
20 // available. Seeks and readahead also drive Client behaviour.
24 // Ensure operations that change the position are exclusive, like Read()
28 // Required when modifying pos and readahead, or reading them without
33 // The cached piece range this reader wants downloaded. The zero value
34 // corresponds to nothing. We cache this so that changes can be detected,
35 // and bubbled up to the Torrent only as required.
39 var _ io.ReadCloser = &Reader{}
41 // Don't wait for pieces to complete and be verified. Read calls return as
42 // soon as they can when the underlying chunks become available.
43 func (r *Reader) SetResponsive() {
47 // Disable responsive mode.
48 func (r *Reader) SetNonResponsive() {
52 // Configure the number of bytes ahead of a read that should also be
53 // prioritized in preparation for further reads.
54 func (r *Reader) SetReadahead(readahead int64) {
56 r.readahead = readahead
59 defer r.t.cl.mu.Unlock()
63 // Return reader's current position.
64 func (r *Reader) CurrentPos() int64 {
68 func (r *Reader) readable(off int64) (ret bool) {
69 if r.t.closed.IsSet() {
72 req, ok := r.t.offsetRequest(off)
77 return r.t.haveChunk(req)
79 return r.t.pieceComplete(int(req.Index))
82 // How many bytes are available to read. Max is the most we could require.
83 func (r *Reader) available(off, max int64) (ret int64) {
85 req, ok := r.t.offsetRequest(off)
89 if !r.t.haveChunk(req) {
92 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
97 // Ensure that ret hasn't exceeded our original max.
104 func (r *Reader) waitReadable(off int64) {
105 // We may have been sent back here because we were told we could read but
110 // Calculates the pieces this reader wants downloaded, ignoring the cached
111 // value at r.pieces.
112 func (r *Reader) piecesUncached() (ret pieceRange) {
117 ret.begin, ret.end = r.t.byteRegionPieces(r.pos, ra)
121 func (r *Reader) Read(b []byte) (n int, err error) {
122 return r.ReadContext(context.Background(), b)
125 func (r *Reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
126 // This is set under the Client lock if the Context is canceled.
128 if ctx.Done() != nil {
129 ctx, cancel := context.WithCancel(ctx)
130 // Abort the goroutine when the function returns.
136 r.t.cl.event.Broadcast()
140 // Hmmm, if a Read gets stuck, this means you can't change position for
141 // other purposes. That seems reasonable, but unusual.
143 defer r.opMu.Unlock()
146 n1, err = r.readOnceAt(b, r.pos, &ctxErr)
149 panic("expected error")
160 if r.pos >= r.t.length {
162 } else if err == io.EOF {
163 err = io.ErrUnexpectedEOF
168 // Wait until some data should be available to read. Tickles the client if it
169 // isn't. Returns how much should be readable without blocking.
170 func (r *Reader) waitAvailable(pos, wanted int64, ctxErr *error) (avail int64) {
172 defer r.t.cl.mu.Unlock()
173 for !r.readable(pos) && *ctxErr == nil {
176 return r.available(pos, wanted)
179 // Performs at most one successful read to torrent storage.
180 func (r *Reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) {
181 if pos >= r.t.length {
186 avail := r.waitAvailable(pos, int64(len(b)), ctxErr)
188 if r.t.closed.IsSet() {
189 err = errors.New("torrent closed")
198 pi := int(pos / r.t.info.PieceLength)
199 ip := r.t.info.Piece(pi)
200 po := pos % r.t.info.PieceLength
201 missinggo.LimitLen(&b1, ip.Length()-po)
202 n, err = r.t.readAt(b1, pos)
208 log.Printf("error reading torrent %q piece %d offset %d, %d bytes: %s", r.t, pi, po, len(b1), err)
209 r.t.updateAllPieceCompletions()
210 r.t.updateAllPiecePriorities()
215 func (r *Reader) Close() error {
217 defer r.t.cl.mu.Unlock()
222 func (r *Reader) posChanged() {
223 to := r.piecesUncached()
229 r.t.readerPosChanged(from, to)
232 func (r *Reader) Seek(off int64, whence int) (ret int64, err error) {
234 defer r.opMu.Unlock()
244 r.pos = r.t.info.TotalLength() + off
246 err = errors.New("bad whence")
254 func (r *Reader) Torrent() *Torrent {