atomashpolskiy / bt

BitTorrent library and client with DHT, magnet links, encryption and more
https://atomashpolskiy.github.io/bt/
Apache License 2.0
2.4k stars 382 forks source link

how to download the file range pieces? #206

Open pangoo-reuse opened 2 years ago

pangoo-reuse commented 2 years ago

like .torrent contains 2 files , file1,file2. file1 is a video file.
for example ,file1 has 60 pieces , i want to play file1 when download, i want to play third seconds first,or fast jump 5th seconds , i want bt downloader download 5th seconds (like 5 -10 pieces) first,so what shoud i do ?thx a lot

jokechen102 commented 1 year ago

Did your question solved? I have the same question ,too.

pvishnyakov commented 1 year ago

Implement FilePrioritySkipSelector to select the file and PieceSelector to tell BtClient what pieces you need, several hints:

    private final FilePrioritySkipSelector filePrioritySkipSelector =
            torrentFile ->
                    torrent.getFiles().indexOf(torrentFile)==selectedFileIndex
                            ? FilePriority.HIGH_PRIORITY
                            : FilePriority.SKIP;
    private final PieceSelector pieceSelector = new PieceSelector() {
        @Override
        public IntStream getNextPieces(BitSet bitSet, PieceStatistics pieceStatistics) {
            return IntStream.of(piecesToDownload);
        }
    };
    private boolean piecesDownloaded() {
        for (int i:piecesToDownload) if (!pieceMap[i]) return false;
        return true;
    }
    private BtClient createClient(URI uri) {
        try {
            return Bt.client(runtime)
                    .storage(storage)
                    .torrent(uri.toURL())
                    .afterTorrentFetched(tf -> {
...
                        pieceMap = new boolean[piecesInTorrent];
                            piecesToDownload = IntStream.concat(IntStream.range(firstFilePiece, firstFilePiece+piecesToPrepare), IntStream.rangeClosed(lastFilePiece-criticalEndPieces+1, lastFilePiece)).toArray();
                        runtime.getEventSource().onPieceVerified(torrent.getTorrentId(), event -> {
                            pieceMap[event.getPieceIndex()]=true;
                            if (piecesDownloaded()) {
                                                             // update piecesToDownload array to supply next portion of pieces
                            }
                        });
                    })
                    .fileSelector(filePrioritySkipSelector)
                    .selector(pieceSelector)
                    .stopWhenDownloaded()
                    .build();
        } catch (Exception e) {
            log("Error creating BT client", e);
            return null;
        }
    }