@@ -34,6 +34,10 @@ double ptsToSeconds(int64_t pts, const AVRational& timeBase) {
3434 return ptsToSeconds (pts, timeBase.den );
3535}
3636
37+ int64_t secondsToClosestPts (double seconds, const AVRational& timeBase) {
38+ return static_cast <int64_t >(std::round (seconds * timeBase.den ));
39+ }
40+
3741struct AVInput {
3842 UniqueAVFormatContext formatContext;
3943 std::unique_ptr<AVIOBytesContext> ioBytesContext;
@@ -663,7 +667,7 @@ void VideoDecoder::maybeSeekToBeforeDesiredPts() {
663667 for (int streamIndex : activeStreamIndices_) {
664668 StreamInfo& streamInfo = streams_[streamIndex];
665669 // clang-format off: clang format clashes
666- streamInfo.discardFramesBeforePts = *maybeDesiredPts_ * streamInfo.timeBase . den ;
670+ streamInfo.discardFramesBeforePts = secondsToClosestPts ( *maybeDesiredPts_, streamInfo.timeBase ) ;
667671 // clang-format on
668672 }
669673
@@ -686,16 +690,18 @@ void VideoDecoder::maybeSeekToBeforeDesiredPts() {
686690 }
687691 int firstActiveStreamIndex = *activeStreamIndices_.begin ();
688692 const auto & firstStreamInfo = streams_[firstActiveStreamIndex];
689- int64_t desiredPts = *maybeDesiredPts_ * firstStreamInfo.timeBase .den ;
693+ int64_t desiredPts =
694+ secondsToClosestPts (*maybeDesiredPts_, firstStreamInfo.timeBase );
690695
691696 // For some encodings like H265, FFMPEG sometimes seeks past the point we
692697 // set as the max_ts. So we use our own index to give it the exact pts of
693698 // the key frame that we want to seek to.
694699 // See https://github.com/pytorch/torchcodec/issues/179 for more details.
695700 // See https://trac.ffmpeg.org/ticket/11137 for the underlying ffmpeg bug.
696701 if (!firstStreamInfo.keyFrames .empty ()) {
697- int desiredKeyFrameIndex =
698- getKeyFrameIndexForPts (firstStreamInfo, desiredPts);
702+ int desiredKeyFrameIndex = getKeyFrameIndexForPtsUsingScannedIndex (
703+ firstStreamInfo.keyFrames , desiredPts);
704+ desiredKeyFrameIndex = std::max (desiredKeyFrameIndex, 0 );
699705 desiredPts = firstStreamInfo.keyFrames [desiredKeyFrameIndex].pts ;
700706 }
701707
0 commit comments