10 "github.com/anacrolix/missinggo"
11 "github.com/anacrolix/torrent/peer_protocol"
14 type Reader interface {
18 missinggo.ReadContexter
23 // Piece range by piece index, [begin, end).
24 type pieceRange struct {
28 // Accesses Torrent data via a Client. Reads block until the data is
29 // available. Seeks and readahead also drive Client behaviour.
33 // Adjust the read/seek window to handle Readers locked to File extents
36 // Ensure operations that change the position are exclusive, like Read()
40 // Required when modifying pos and readahead, or reading them without
45 // The cached piece range this reader wants downloaded. The zero value
46 // corresponds to nothing. We cache this so that changes can be detected,
47 // and bubbled up to the Torrent only as required.
51 var _ io.ReadCloser = &reader{}
53 // Don't wait for pieces to complete and be verified. Read calls return as
54 // soon as they can when the underlying chunks become available.
55 func (r *reader) SetResponsive() {
57 r.t.cl.event.Broadcast()
60 // Disable responsive mode. TODO: Remove?
61 func (r *reader) SetNonResponsive() {
63 r.t.cl.event.Broadcast()
66 // Configure the number of bytes ahead of a read that should also be
67 // prioritized in preparation for further reads.
68 func (r *reader) SetReadahead(readahead int64) {
70 r.readahead = readahead
77 func (r *reader) readable(off int64) (ret bool) {
78 if r.t.closed.IsSet() {
81 req, ok := r.t.offsetRequest(r.torrentOffset(off))
86 return r.t.haveChunk(req)
88 return r.t.pieceComplete(pieceIndex(req.Index))
91 // How many bytes are available to read. Max is the most we could require.
92 func (r *reader) available(off, max int64) (ret int64) {
95 req, ok := r.t.offsetRequest(off)
99 if !r.t.haveChunk(req) {
102 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
107 // Ensure that ret hasn't exceeded our original max.
114 func (r *reader) waitReadable(off int64) {
115 // We may have been sent back here because we were told we could read but
120 // Calculates the pieces this reader wants downloaded, ignoring the cached
121 // value at r.pieces.
122 func (r *reader) piecesUncached() (ret pieceRange) {
125 // Needs to be at least 1, because [x, x) means we don't want
129 if ra > r.length-r.pos {
130 ra = r.length - r.pos
132 ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
136 func (r *reader) Read(b []byte) (n int, err error) {
137 return r.ReadContext(context.Background(), b)
140 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
141 // This is set under the Client lock if the Context is canceled.
143 if ctx.Done() != nil {
144 ctx, cancel := context.WithCancel(ctx)
145 // Abort the goroutine when the function returns.
155 // Hmmm, if a Read gets stuck, this means you can't change position for
156 // other purposes. That seems reasonable, but unusual.
158 defer r.opMu.Unlock()
161 n1, err = r.readOnceAt(b, r.pos, &ctxErr)
164 panic("expected error")
175 if r.pos >= r.length {
177 } else if err == io.EOF {
178 err = io.ErrUnexpectedEOF
183 // Wait until some data should be available to read. Tickles the client if it
184 // isn't. Returns how much should be readable without blocking.
185 func (r *reader) waitAvailable(pos, wanted int64, ctxErr *error) (avail int64) {
187 defer r.t.cl.unlock()
188 for !r.readable(pos) && *ctxErr == nil {
191 return r.available(pos, wanted)
194 func (r *reader) torrentOffset(readerPos int64) int64 {
195 return r.offset + readerPos
198 // Performs at most one successful read to torrent storage.
199 func (r *reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) {
205 avail := r.waitAvailable(pos, int64(len(b)), ctxErr)
207 if r.t.closed.IsSet() {
208 err = errors.New("torrent closed")
216 pi := peer_protocol.Integer(r.torrentOffset(pos) / r.t.info.PieceLength)
217 ip := r.t.info.Piece(int(pi))
218 po := r.torrentOffset(pos) % r.t.info.PieceLength
219 b1 := missinggo.LimitLen(b, ip.Length()-po, avail)
220 n, err = r.t.readAt(b1, r.torrentOffset(pos))
226 // TODO: Just reset pieces in the readahead window. This might help
227 // prevent thrashing with small caches and file and piece priorities.
228 log.Printf("error reading torrent %q piece %d offset %d, %d bytes: %s", r.t, pi, po, len(b1), err)
229 r.t.updateAllPieceCompletions()
230 r.t.updateAllPiecePriorities()
235 func (r *reader) Close() error {
237 defer r.t.cl.unlock()
242 func (r *reader) posChanged() {
243 to := r.piecesUncached()
249 // log.Printf("reader pos changed %v->%v", from, to)
250 r.t.readerPosChanged(from, to)
253 func (r *reader) Seek(off int64, whence int) (ret int64, err error) {
255 defer r.opMu.Unlock()
265 r.pos = r.length + off
267 err = errors.New("bad whence")