@@ -458,44 +458,40 @@ func (m *ManagerCtx) transcodeFromSegment(index int) error {
458458 m .mu .Lock ()
459459 defer m .mu .Unlock ()
460460
461- segmentsTotal := len (m .segments )
462- if segmentsTotal <= m .segmentBufferMax {
463- // if all our segments can fit in the buffer
464- // then we should transcode all of them
465- // regardless of the index
461+ // Determine the upper bound (exclusive) of the segment range we will inspect
462+ upperBound := len (m .segments )
463+ if upperBound <= m .segmentBufferMax {
464+ // All segments fit into the buffer – transcode everything
466465 index = 0
467- } else if index + m .segmentBufferMax < segmentsTotal {
468- // cap transocded segments to the buffer size
469- segmentsTotal = index + m .segmentBufferMax
466+ } else if index + m .segmentBufferMax < upperBound {
467+ // Restrict the window to the current index + buffer size
468+ upperBound = index + m .segmentBufferMax
470469 }
471470
472- offset , limit := 0 , 0
473- for i := index ; i < segmentsTotal - 1 ; i ++ {
471+ processedCount , pendingCount := 0 , 0 // processedCount is the number of segments already transcoded or enqueued
472+ for i := index ; i < upperBound ; i ++ {
474473 _ , isEnqueued := m .waitForSegment (i )
475474 isTranscoded := m .isSegmentTranscoded (i )
476475
477- // increase offset if transcoded without limit
478- if (isTranscoded || isEnqueued ) && limit == 0 {
479- offset ++
480- } else
481- // increase limit if is not transcoded
482- if ! (isTranscoded || isEnqueued ) {
483- limit ++
484- } else
485- // break otherwise
486- {
476+ // Skip already-handled segments until we find the first pending one
477+ if (isTranscoded || isEnqueued ) && pendingCount == 0 {
478+ processedCount ++
479+ } else if ! (isTranscoded || isEnqueued ) {
480+ // Count segments that still need to be transcoded
481+ pendingCount ++
482+ } else {
483+ // Once we have a mix of handled and pending segments, stop the scan
487484 break
488485 }
489486 }
490487
491- // if offset is greater than our minimal offset,
492- // or limit is 0, we have enough segments available
493- if offset > m .segmentBufferMin || limit == 0 {
488+ // If we already have enough handled segments in the buffer, or no work is pending, exit early
489+ if processedCount > m .segmentBufferMin || pendingCount == 0 {
494490 return nil
495491 }
496492
497- // otherwise transcode chosen segment range
498- return m .transcodeSegments (offset + index , limit )
493+ // Otherwise, transcode the pending segment window
494+ return m .transcodeSegments (index + processedCount , pendingCount )
499495}
500496
501497func (m * ManagerCtx ) Start () (err error ) {
0 commit comments