@@ -1040,32 +1040,46 @@ VideoDecoder::BatchDecodedOutput VideoDecoder::getFramesAtIndices(
10401040 const auto & options = stream.options ;
10411041 BatchDecodedOutput output (frameIndices.size (), options, streamMetadata);
10421042
1043- auto previousFrameIndex = -1 ;
1043+ std::vector<size_t > argsort (frameIndices.size ());
1044+ for (size_t i = 0 ; i < argsort.size (); ++i) {
1045+ argsort[i] = i;
1046+ }
1047+ if (sortIndices) {
1048+ std::sort (
1049+ argsort.begin (), argsort.end (), [&frameIndices](size_t a, size_t b) {
1050+ return frameIndices[a] < frameIndices[b];
1051+ });
1052+ }
1053+
1054+ auto previousIndexInVideo = -1 ;
10441055 for (auto f = 0 ; f < frameIndices.size (); ++f) {
1045- auto frameIndex = frameIndices[f];
1046- if (frameIndex < 0 || frameIndex >= stream.allFrames .size ()) {
1056+ auto indexInOutput = argsort[f];
1057+ auto indexInVideo = frameIndices[argsort[f]];
1058+ if (indexInVideo < 0 || indexInVideo >= stream.allFrames .size ()) {
10471059 throw std::runtime_error (
1048- " Invalid frame index=" + std::to_string (frameIndex ));
1060+ " Invalid frame index=" + std::to_string (indexInVideo ));
10491061 }
1050- if ((f > 0 ) && (frameIndex == previousFrameIndex )) {
1062+ if ((f > 0 ) && (indexInVideo == previousIndexInVideo )) {
10511063 // Avoid decoding the same frame twice
1052- output.frames [f].copy_ (output.frames [f - 1 ]);
1053- output.ptsSeconds [f] = output.ptsSeconds [f - 1 ];
1054- output.durationSeconds [f] = output.durationSeconds [f - 1 ];
1064+ auto previousIndexInOutput = argsort[f - 1 ];
1065+ output.frames [indexInOutput].copy_ (output.frames [previousIndexInOutput]);
1066+ output.ptsSeconds [indexInOutput] =
1067+ output.ptsSeconds [previousIndexInOutput];
1068+ output.durationSeconds [indexInOutput] =
1069+ output.durationSeconds [previousIndexInOutput];
10551070 } else {
1056- DecodedOutput singleOut =
1057- getFrameAtIndex ( streamIndex, frameIndex , output.frames [f ]);
1071+ DecodedOutput singleOut = getFrameAtIndex (
1072+ streamIndex, indexInVideo , output.frames [indexInOutput ]);
10581073 if (options.colorConversionLibrary ==
10591074 ColorConversionLibrary::FILTERGRAPH) {
1060- output.frames [f ] = singleOut.frame ;
1075+ output.frames [indexInOutput ] = singleOut.frame ;
10611076 }
1062- output.ptsSeconds [f ] = singleOut.ptsSeconds ;
1063- output.durationSeconds [f ] = singleOut.durationSeconds ;
1077+ output.ptsSeconds [indexInOutput ] = singleOut.ptsSeconds ;
1078+ output.durationSeconds [indexInOutput ] = singleOut.durationSeconds ;
10641079 }
1065- previousFrameIndex = frameIndex ;
1080+ previousIndexInVideo = indexInVideo ;
10661081 }
10671082 output.frames = MaybePermuteHWC2CHW (options, output.frames );
1068-
10691083 return output;
10701084}
10711085
0 commit comments