| 1 | /* |
| 2 | * Copyright 2026 LiveKit, Inc. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #include "jetson_plane_layout.h" |
| 18 | |
| 19 | namespace livekit { |
| 20 | |
| 21 | int ResolvePlaneStride(const PlaneLayoutHints& hints, |
| 22 | int expected_height, |
| 23 | int min_stride, |
| 24 | int fallback) { |
| 25 | // 1) NvBufferPlane::fmt.stride if present and sane. |
| 26 | if (hints.fmt_stride >= min_stride) { |
| 27 | return hints.fmt_stride; |
| 28 | } |
| 29 | |
| 30 | // 2) NvBufSurfaceFromFd pitch (ground truth for this plane fd). |
| 31 | if (hints.probed_pitch >= min_stride) { |
| 32 | return hints.probed_pitch; |
| 33 | } |
| 34 | |
| 35 | // 3) Derive from the mapped plane length. fmt.height can be misleading (e.g. |
| 36 | // a UV plane reporting full luma height), which would yield an under-stride |
| 37 | // (pitch/2) and a green image. Only accept a derived value that meets |
| 38 | // min_stride; prefer fmt.height as the divisor, then expected_height. |
| 39 | int best = 0; |
| 40 | if (hints.plane_length > 0) { |
| 41 | if (hints.fmt_height > 0) { |
| 42 | const int derived = hints.plane_length / hints.fmt_height; |
| 43 | if (derived >= min_stride) { |
| 44 | best = derived; |
| 45 | } |
| 46 | } |
| 47 | if (best == 0 && expected_height > 0) { |
| 48 | const int derived = hints.plane_length / expected_height; |
| 49 | if (derived >= min_stride) { |
| 50 | best = derived; |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | int stride = best > 0 ? best : fallback; |
| 56 | if (stride < min_stride) { |
| 57 | stride = min_stride; |
| 58 | } |
| 59 | |
| 60 | // Cap stride to what the allocation can accommodate so we never walk past the |
| 61 | // mapped plane. (This should not normally trigger.) |
| 62 | if (expected_height > 0 && hints.plane_length > 0) { |
| 63 | const int max_stride = hints.plane_length / expected_height; |
| 64 | if (max_stride > 0 && stride > max_stride) { |
| 65 | stride = max_stride; |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | return stride; |
| 70 | } |
| 71 | |
| 72 | int ResolvePlaneHeight(bool have_probe, int probed_height, int expected_height) { |
| 73 | if (have_probe && probed_height >= expected_height) { |
| 74 | return probed_height; |
| 75 | } |
| 76 | return expected_height; |
| 77 | } |
| 78 | |
| 79 | } // namespace livekit |