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) tickleClient() {
108 func (r *Reader) waitReadable(off int64) {
109 // We may have been sent back here because we were told we could read but
114 // Calculates the pieces this reader wants downloaded, ignoring the cached
115 // value at r.pieces.
116 func (r *Reader) piecesUncached() (ret pieceRange) {
121 ret.begin, ret.end = r.t.byteRegionPieces(r.pos, ra)
125 func (r *Reader) Read(b []byte) (n int, err error) {
126 return r.ReadContext(b, context.Background())
129 func (r *Reader) ReadContext(b []byte, ctx context.Context) (n int, err error) {
130 // This is set under the Client lock if the Context is canceled.
132 if ctx.Done() != nil {
133 ctx, cancel := context.WithCancel(ctx)
134 // Abort the goroutine when the function returns.
140 r.t.cl.event.Broadcast()
144 // Hmmm, if a Read gets stuck, this means you can't change position for
145 // other purposes. That seems reasonable, but unusual.
147 defer r.opMu.Unlock()
150 n1, err = r.readOnceAt(b, r.pos, &ctxErr)
153 panic("expected error")
164 if r.pos >= r.t.length {
166 } else if err == io.EOF {
167 err = io.ErrUnexpectedEOF
172 // Wait until some data should be available to read. Tickles the client if it
173 // isn't. Returns how much should be readable without blocking.
174 func (r *Reader) waitAvailable(pos, wanted int64, ctxErr *error) (avail int64) {
176 defer r.t.cl.mu.Unlock()
177 for !r.readable(pos) && *ctxErr == nil {
180 return r.available(pos, wanted)
183 // Performs at most one successful read to torrent storage.
184 func (r *Reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) {
185 if pos >= r.t.length {
190 avail := r.waitAvailable(pos, int64(len(b)), ctxErr)
192 if r.t.closed.IsSet() {
193 err = errors.New("torrent closed")
202 pi := int(pos / r.t.Info().PieceLength)
203 ip := r.t.Info().Piece(pi)
204 po := pos % r.t.Info().PieceLength
205 missinggo.LimitLen(&b1, ip.Length()-po)
206 n, err = r.t.readAt(b1, pos)
211 log.Printf("error reading torrent %q piece %d offset %d, %d bytes: %s", r.t, pi, po, len(b1), err)
213 r.t.updateAllPieceCompletions()
214 r.t.updateAllPiecePriorities()
219 func (r *Reader) Close() error {
221 defer r.t.cl.mu.Unlock()
226 func (r *Reader) posChanged() {
227 to := r.piecesUncached()
233 r.t.readerPosChanged(from, to)
236 func (r *Reader) Seek(off int64, whence int) (ret int64, err error) {
238 defer r.opMu.Unlock()
248 r.pos = r.t.info.TotalLength() + off
250 err = errors.New("bad whence")
258 func (r *Reader) Torrent() *Torrent {