NAME
Net::BitTorrent::Torrent::PiecePicker - Algorithmic Piece Selection
SYNOPSIS
use Net::BitTorrent::Torrent::PiecePicker qw[:all]; # Import strategies
my $picker = Net::BitTorrent::Torrent::PiecePicker->new(
bitfield => $my_bitfield,
strategy => RAREST_FIRST
);
# Update global swarm availability
$picker->update_availability($peer_bitfield, 1); # peer joined
$picker->update_availability($peer_bitfield, -1); # peer left
# Pick the next piece to request from a peer
my $idx = $picker->pick_piece($peer_bitfield, \%blocks_pending);
DESCRIPTION
Net::BitTorrent::Torrent::PiecePicker implements the selection logic used to decide which torrent piece to request next. A good picker is essential for swarm health and performance.
SELECTION STRATEGIES
RAREST_FIRST (Default)
Prioritizes pieces that have the lowest availability in the local swarm. This ensures that rare pieces are replicated quickly, preventing "stalled" torrents where the last few pieces are missing.
SEQUENTIAL
Picks pieces in simple numerical order. Useful for linear media playback where early data is needed first.
STREAMING
A hybrid approach that prioritizes early pieces while still respecting per-piece priorities.
METHODS
pick_piece( $peer_bitfield, \%blocks_pending )
Finds the "best" piece to request from a specific peer based on the current strategy.
Filters out pieces we already have or have already skipped (priority 0).
Accounts for End Game mode.
Uses randomization to break ties and prevent "thundering herd" issues.
pick_block( $peer, \%blocks_pending )
Selects the next available block (16KiB) to request from a specific peer.
Unlike pick_piece, which returns a whole piece index, pick_block iterates through the prioritized candidates and returns the first block that is not already pending or received. This naturally allows the client to work on multiple pieces simultaneously (multi-piece parallelism) to keep peer pipelines full.
update_availability( $bitfield, $delta )
Increments or decrements the availability count for every piece in the provided bitfield. This is called whenever a peer's BITFIELD, HAVE, or HAVE_ALL message is processed.
set_priority( $index, $priority )
Weights a specific piece.
enter_end_game( )
Enables End Game mode. In this mode, the picker becomes more aggressive, allowing requests for the same block to be sent to multiple peers simultaneously to finish the torrent faster.
AUTHOR
Sanko Robinson <sanko@cpan.org>
COPYRIGHT
Copyright (C) 2008-2026 by Sanko Robinson.
This library is free software; you can redistribute it and/or modify it under the terms of the Artistic License 2.0.