diff --git a/docs/source/user_guide/read.rst b/docs/source/user_guide/read.rst index d55a141c1..1b036e034 100644 --- a/docs/source/user_guide/read.rst +++ b/docs/source/user_guide/read.rst @@ -331,6 +331,26 @@ Implementation Guidance - Do not assume identical overflow semantics across C++ and Java; tests should validate acceptable ranges and nullability. - For timestamp handling, consider precision/range constraints in C++ when interoperating with Java-produced data splits. +Reading Video Columns +--------------------- + +Paimon C++ reads scalar BLOB columns from v1 ``.video`` files that match only +the six-index layout (29-byte footer). It rejects files whose estimated peak +index memory exceeds 64 MiB. + +Reimport five-index or ambiguous files with a Java reader for the source +layout and a current Java writer. Verify row counts, frame ordinals and row +alignment in C++ before switching. + +Non-null rows return frame descriptors even with ``blob-as-descriptor=false``. +Open them with ``Blob::FromDescriptor()``. Use ``FrameIndex()`` for the zero-based +frame ordinal, ``NewInputStream()`` for the encoded payload, and ``MoovOffset()`` +and ``MoovLength()`` for the optional MP4 ``moov`` range. + +Use Java Paimon to write video columns. C++ rejects writes to +``video-frame-field`` columns and rejects frame descriptors in ordinary BLOB +writes. + .. _data-evolution-deletion-vectors: Deletion Vectors on Data-Evolution Tables diff --git a/include/paimon/data/blob.h b/include/paimon/data/blob.h index 0b66ce7b6..bfdeac967 100644 --- a/include/paimon/data/blob.h +++ b/include/paimon/data/blob.h @@ -75,8 +75,22 @@ class PAIMON_EXPORT Blob { /// Gets the URI of the blob. const std::string& Uri() const; + /// Whether this blob refers to one logical frame in an encoded video payload. + bool IsVideoFrame() const; + + /// Zero-based frame ordinal, or -1 for a regular blob. + int64_t FrameIndex() const; + + /// Offset and length of the MP4 moov box relative to the encoded video payload. + /// Both values are 0 if absent. + int64_t MoovOffset() const; + int64_t MoovLength() const; + /// Creates an input stream for reading the blob data. /// + /// For a video frame descriptor, the stream contains the encoded video payload. + /// Use `FrameIndex()` to locate the logical frame when decoding the payload. + /// /// @param fs The file system to use for reading. /// @return A result containing the input stream or an error. Result> NewInputStream( diff --git a/src/paimon/CMakeLists.txt b/src/paimon/CMakeLists.txt index 4ab30167d..87a1fa09e 100644 --- a/src/paimon/CMakeLists.txt +++ b/src/paimon/CMakeLists.txt @@ -30,6 +30,7 @@ set(PAIMON_COMMON_SRCS common/data/blob_descriptor.cpp common/data/blob_view.cpp common/data/blob_view_struct.cpp + common/data/video_frame_descriptor.cpp common/data/blob_utils.cpp common/data/columnar/columnar_array.cpp common/data/columnar/columnar_map.cpp diff --git a/src/paimon/common/data/blob.cpp b/src/paimon/common/data/blob.cpp index 707dd475d..adfb268b0 100644 --- a/src/paimon/common/data/blob.cpp +++ b/src/paimon/common/data/blob.cpp @@ -24,6 +24,7 @@ #include "arrow/c/bridge.h" #include "paimon/common/data/blob_utils.h" +#include "paimon/common/data/video_frame_descriptor.h" #include "paimon/common/io/offset_input_stream.h" #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/common/utils/path_util.h" @@ -40,21 +41,28 @@ class Blob::Impl { public: explicit Impl(std::unique_ptr&& descriptor) : descriptor_(std::move(descriptor)) {} + explicit Impl(std::unique_ptr&& video_frame) + : video_frame_(std::move(video_frame)) {} PAIMON_UNIQUE_PTR SerializeDescriptor(const std::shared_ptr& pool) const { - return descriptor_->Serialize(pool); + return video_frame_ ? video_frame_->Serialize(pool) : descriptor_->Serialize(pool); } const BlobDescriptor* GetDescriptor() const { - return descriptor_.get(); + return video_frame_ ? &video_frame_->Payload() : descriptor_.get(); } const std::string& Uri() const { - return descriptor_->Uri(); + return GetDescriptor()->Uri(); + } + + const VideoFrameDescriptor* VideoFrame() const { + return video_frame_.get(); } private: std::unique_ptr descriptor_; + std::unique_ptr video_frame_; }; Result> Blob::FromPath(const std::string& path) { @@ -74,6 +82,11 @@ Blob::Blob(std::unique_ptr&& impl) : impl_(std::move(impl)) {} Blob::~Blob() = default; Result> Blob::FromDescriptor(const char* buffer, uint64_t length) { + if (VideoFrameDescriptor::HasMagic(buffer, length)) { + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr video_frame, + VideoFrameDescriptor::Deserialize(buffer, length)); + return std::unique_ptr(new Blob(std::make_unique(std::move(video_frame)))); + } PAIMON_ASSIGN_OR_RAISE(std::unique_ptr descriptor, BlobDescriptor::Deserialize(buffer, length)); @@ -89,6 +102,22 @@ const std::string& Blob::Uri() const { return impl_->Uri(); } +bool Blob::IsVideoFrame() const { + return impl_->VideoFrame() != nullptr; +} + +int64_t Blob::FrameIndex() const { + return impl_->VideoFrame() ? impl_->VideoFrame()->FrameIndex() : -1; +} + +int64_t Blob::MoovOffset() const { + return impl_->VideoFrame() ? impl_->VideoFrame()->MoovOffset() : 0; +} + +int64_t Blob::MoovLength() const { + return impl_->VideoFrame() ? impl_->VideoFrame()->MoovLength() : 0; +} + Result> Blob::NewInputStream( const std::shared_ptr& fs) const { if (fs == nullptr) { diff --git a/src/paimon/common/data/blob_defs.h b/src/paimon/common/data/blob_defs.h index 8dbb681b1..51c076d73 100644 --- a/src/paimon/common/data/blob_defs.h +++ b/src/paimon/common/data/blob_defs.h @@ -50,6 +50,9 @@ class BlobDefs { /// Metadata value identifying a Paimon Blob extension type field. static constexpr char kExtensionTypeValue[] = "paimon.type.blob"; + /// Java Paimon table option naming scalar BLOB fields stored as video frames. + static constexpr char kVideoFrameFieldOption[] = "video-frame-field"; + /// A bin_length value of -1 in the index indicates a null blob entry. static constexpr int64_t kNullBinLength = -1; /// A bin_length value of -2 in the index indicates a placeholder blob entry, written by diff --git a/src/paimon/common/data/blob_descriptor.cpp b/src/paimon/common/data/blob_descriptor.cpp index 5a020c9fc..947575ede 100644 --- a/src/paimon/common/data/blob_descriptor.cpp +++ b/src/paimon/common/data/blob_descriptor.cpp @@ -22,6 +22,7 @@ #include #include "fmt/format.h" +#include "paimon/common/data/video_frame_descriptor.h" #include "paimon/common/io/memory_segment_output_stream.h" #include "paimon/common/memory/memory_segment_utils.h" #include "paimon/io/byte_array_input_stream.h" @@ -73,6 +74,12 @@ PAIMON_UNIQUE_PTR BlobDescriptor::Serialize(const std::shared_ptr> BlobDescriptor::Deserialize(const char* buffer, uint64_t size) { + if (buffer == nullptr || size == 0) { + return Status::Invalid("empty blob descriptor"); + } + if (VideoFrameDescriptor::HasMagic(buffer, size)) { + return Status::Invalid("video frame descriptors must be opened with Blob::FromDescriptor"); + } auto input_stream = std::make_shared(buffer, size); DataInputStream in(std::move(input_stream)); in.SetOrder(ByteOrder::PAIMON_LITTLE_ENDIAN); @@ -91,6 +98,13 @@ Result> BlobDescriptor::Deserialize(const char* } } PAIMON_ASSIGN_OR_RAISE(int32_t uri_length, in.ReadValue()); + PAIMON_ASSIGN_OR_RAISE(int64_t uri_start, in.GetPos()); + constexpr uint64_t kTailSize = 2 * sizeof(int64_t); + const uint64_t remaining = size - uri_start; + if (uri_length < 0 || remaining < kTailSize || + static_cast(uri_length) > remaining - kTailSize) { + return Status::Invalid("invalid blob descriptor length"); + } std::string uri(uri_length, '\0'); PAIMON_RETURN_NOT_OK(in.Read(uri.data(), uri.size())); PAIMON_ASSIGN_OR_RAISE(int64_t offset, in.ReadValue()); @@ -99,7 +113,7 @@ Result> BlobDescriptor::Deserialize(const char* } Result BlobDescriptor::IsBlobDescriptor(const char* buffer, uint64_t size) { - if (size < kMinDescriptorLength) { + if (buffer == nullptr || size < kMinDescriptorLength) { return false; } auto input_stream = std::make_shared(buffer, size); diff --git a/src/paimon/common/data/blob_utils.cpp b/src/paimon/common/data/blob_utils.cpp index fd12cbcd9..1afd2d5b2 100644 --- a/src/paimon/common/data/blob_utils.cpp +++ b/src/paimon/common/data/blob_utils.cpp @@ -195,7 +195,7 @@ bool BlobUtils::IsBlobMetadata(const std::shared_ptr BlobUtils::ToArrowField( diff --git a/src/paimon/common/data/video_frame_descriptor.cpp b/src/paimon/common/data/video_frame_descriptor.cpp new file mode 100644 index 000000000..c213054e3 --- /dev/null +++ b/src/paimon/common/data/video_frame_descriptor.cpp @@ -0,0 +1,111 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#include "paimon/common/data/video_frame_descriptor.h" + +#include +#include +#include +#include + +#include "paimon/common/io/memory_segment_output_stream.h" +#include "paimon/common/memory/memory_segment_utils.h" +#include "paimon/io/byte_array_input_stream.h" +#include "paimon/io/data_input_stream.h" + +namespace paimon { +namespace { + +constexpr int8_t kVersion = 1; +constexpr std::string_view kMagic = "MRFOEDIV"; // 0x564944454F46524D in little endian +constexpr uint64_t kHeaderSize = sizeof(kVersion) + kMagic.size(); +constexpr uint64_t kFixedSize = kHeaderSize + sizeof(int32_t) + 5 * sizeof(int64_t); + +} // namespace + +VideoFrameDescriptor::VideoFrameDescriptor(std::unique_ptr payload, + int64_t frame_index, int64_t moov_offset, + int64_t moov_length) + : payload_(std::move(payload)), + frame_index_(frame_index), + moov_offset_(moov_offset), + moov_length_(moov_length) {} + +Result> VideoFrameDescriptor::Create( + const std::string& uri, int64_t offset, int64_t length, int64_t frame_index, + int64_t moov_offset, int64_t moov_length) { + if (frame_index < 0 || moov_offset < 0 || moov_length < 0 || + uri.size() > std::numeric_limits::max() || + (moov_length == 0 ? moov_offset != 0 + : moov_offset > length || moov_length > length - moov_offset)) { + return Status::Invalid("invalid video frame descriptor range"); + } + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr payload, + BlobDescriptor::Create(uri, offset, length)); + return std::unique_ptr( + new VideoFrameDescriptor(std::move(payload), frame_index, moov_offset, moov_length)); +} + +bool VideoFrameDescriptor::HasMagic(const char* buffer, uint64_t size) { + return buffer != nullptr && size >= kHeaderSize && + std::string_view(buffer + sizeof(kVersion), kMagic.size()) == kMagic; +} + +Result> VideoFrameDescriptor::Deserialize(const char* buffer, + uint64_t size) { + if (size < kFixedSize || !HasMagic(buffer, size) || buffer[0] != kVersion) { + return Status::Invalid("invalid or unsupported video frame descriptor header"); + } + DataInputStream input(std::make_shared(buffer, size)); + input.SetOrder(ByteOrder::PAIMON_LITTLE_ENDIAN); + PAIMON_RETURN_NOT_OK(input.Seek(kHeaderSize)); + PAIMON_ASSIGN_OR_RAISE(int32_t uri_length, input.ReadValue()); + if (uri_length < 0 || static_cast(uri_length) != size - kFixedSize) { + return Status::Invalid("invalid video frame descriptor length"); + } + std::string uri(uri_length, '\0'); + PAIMON_RETURN_NOT_OK(input.Read(uri.data(), uri_length)); + PAIMON_ASSIGN_OR_RAISE(int64_t offset, input.ReadValue()); + PAIMON_ASSIGN_OR_RAISE(int64_t length, input.ReadValue()); + PAIMON_ASSIGN_OR_RAISE(int64_t frame_index, input.ReadValue()); + PAIMON_ASSIGN_OR_RAISE(int64_t moov_offset, input.ReadValue()); + PAIMON_ASSIGN_OR_RAISE(int64_t moov_length, input.ReadValue()); + return Create(uri, offset, length, frame_index, moov_offset, moov_length); +} + +PAIMON_UNIQUE_PTR VideoFrameDescriptor::Serialize( + const std::shared_ptr& pool) const { + const std::string& uri = payload_->Uri(); + const int32_t segment_size = std::min( + kFixedSize + uri.size(), MemorySegmentOutputStream::DEFAULT_SEGMENT_SIZE); + MemorySegmentOutputStream output(segment_size, pool); + output.SetOrder(ByteOrder::PAIMON_LITTLE_ENDIAN); + output.WriteValue(kVersion); + output.Write(kMagic.data(), kMagic.size()); + output.WriteValue(uri.size()); + output.Write(uri.data(), uri.size()); + output.WriteValue(payload_->Offset()); + output.WriteValue(payload_->Length()); + output.WriteValue(frame_index_); + output.WriteValue(moov_offset_); + output.WriteValue(moov_length_); + return MemorySegmentUtils::CopyToBytes(output.Segments(), 0, output.CurrentSize(), pool.get()); +} + +} // namespace paimon diff --git a/src/paimon/common/data/video_frame_descriptor.h b/src/paimon/common/data/video_frame_descriptor.h new file mode 100644 index 000000000..00873734a --- /dev/null +++ b/src/paimon/common/data/video_frame_descriptor.h @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#pragma once + +#include +#include +#include + +#include "paimon/data/blob_descriptor.h" +#include "paimon/visibility.h" + +namespace paimon { + +/// Wire representation of a frame in an encoded video. The moov range is relative to its payload. +class PAIMON_EXPORT VideoFrameDescriptor { + public: + static Result> Create(const std::string& uri, + int64_t offset, int64_t length, + int64_t frame_index, + int64_t moov_offset, + int64_t moov_length); + + static bool HasMagic(const char* buffer, uint64_t size); + static Result> Deserialize(const char* buffer, + uint64_t size); + + PAIMON_UNIQUE_PTR Serialize(const std::shared_ptr& pool) const; + + const BlobDescriptor& Payload() const { + return *payload_; + } + + int64_t FrameIndex() const { + return frame_index_; + } + + int64_t MoovOffset() const { + return moov_offset_; + } + + int64_t MoovLength() const { + return moov_length_; + } + + private: + VideoFrameDescriptor(std::unique_ptr payload, int64_t frame_index, + int64_t moov_offset, int64_t moov_length); + + std::unique_ptr payload_; + int64_t frame_index_; + int64_t moov_offset_; + int64_t moov_length_; +}; + +} // namespace paimon diff --git a/src/paimon/common/reader/data_file_reader_factory.cpp b/src/paimon/common/reader/data_file_reader_factory.cpp index edaac8301..b481d64c3 100644 --- a/src/paimon/common/reader/data_file_reader_factory.cpp +++ b/src/paimon/common/reader/data_file_reader_factory.cpp @@ -41,9 +41,9 @@ namespace { // files (FormatTable::ParseFormat accepts only parquet/orc), so this only concerns the managed // table path. bool FormatSupportsPrefetch(const std::string& format_identifier) { - return format_identifier != "blob" && format_identifier != "avro" && - format_identifier != "lance" && format_identifier != "mosaic" && - format_identifier != "vortex"; + return format_identifier != "blob" && format_identifier != "video" && + format_identifier != "avro" && format_identifier != "lance" && + format_identifier != "mosaic" && format_identifier != "vortex"; } } // namespace diff --git a/src/paimon/core/append/append_only_writer.cpp b/src/paimon/core/append/append_only_writer.cpp index 97e7853b2..3550f4426 100644 --- a/src/paimon/core/append/append_only_writer.cpp +++ b/src/paimon/core/append/append_only_writer.cpp @@ -29,6 +29,7 @@ #include "arrow/c/helpers.h" #include "arrow/type.h" #include "arrow/util/key_value_metadata.h" +#include "paimon/common/data/blob_defs.h" #include "paimon/common/data/shredding/shredding_write_plan_factories.h" #include "paimon/common/metrics/metrics_impl.h" #include "paimon/common/types/row_kind.h" @@ -37,6 +38,7 @@ #include "paimon/common/utils/checked_cast.h" #include "paimon/common/utils/long_counter.h" #include "paimon/common/utils/scope_guard.h" +#include "paimon/common/utils/string_utils.h" #include "paimon/core/append/bucketed_append_compact_manager.h" #include "paimon/core/io/append_data_file_writer_factory.h" #include "paimon/core/io/blob_data_file_writer_factory.h" @@ -189,6 +191,17 @@ Status AppendOnlyWriter::Flush(bool wait_for_latest_compaction, bool forced_full } AppendOnlyWriter::RollingFileWriterResult AppendOnlyWriter::CreateRollingRowWriter() { + const auto& table_options = options_.ToMap(); + const auto video_fields = table_options.find(BlobDefs::kVideoFrameFieldOption); + if (video_fields != table_options.end()) { + for (std::string field : StringUtils::Split(video_fields->second, ",")) { + StringUtils::Trim(&field); + if (write_schema_->GetFieldIndex(field) >= 0) { + return Status::NotImplemented( + fmt::format("writing video-frame-field '{}' is not supported", field)); + } + } + } if (options_.GetVectorFileFormat()) { arrow::FieldVector main_fields; arrow::FieldVector vector_fields; diff --git a/src/paimon/core/operation/abstract_split_read.cpp b/src/paimon/core/operation/abstract_split_read.cpp index f14e2cede..6c2043d55 100644 --- a/src/paimon/core/operation/abstract_split_read.cpp +++ b/src/paimon/core/operation/abstract_split_read.cpp @@ -463,7 +463,8 @@ Result> AbstractSplitRead::CreateFieldMappingRe file_reader = std::make_unique(std::move(file_reader), arrow_pool_); } std::set skip_map_selected_keys_filter_field_ids; - if (file_format_identifier != "blob") { + const bool is_blob_file = BlobUtils::IsBlobFile(file_meta->file_name); + if (!is_blob_file) { std::pair, std::set> shredding_result; PAIMON_ASSIGN_OR_RAISE(shredding_result, ApplyShreddingReaderIfNeeded(std::move(file_reader), read_schema)); @@ -474,7 +475,7 @@ Result> AbstractSplitRead::CreateFieldMappingRe // A blob file has no self-describing schema: its physical fields are declared by the // file meta's write cols instead of queried from the format reader. std::optional> file_field_names; - if (file_format_identifier == "blob") { + if (is_blob_file) { file_field_names = file_meta->write_cols; } file_reader = std::make_unique( diff --git a/src/paimon/core/utils/blob_view_lookup.cpp b/src/paimon/core/utils/blob_view_lookup.cpp index 30999fe62..d6dfba625 100644 --- a/src/paimon/core/utils/blob_view_lookup.cpp +++ b/src/paimon/core/utils/blob_view_lookup.cpp @@ -28,6 +28,7 @@ #include "arrow/c/bridge.h" #include "fmt/format.h" #include "paimon/catalog/catalog.h" +#include "paimon/common/data/video_frame_descriptor.h" #include "paimon/common/executor/future.h" #include "paimon/common/table/special_fields.h" #include "paimon/common/utils/arrow/status_utils.h" @@ -252,10 +253,10 @@ Status BlobViewLookup::ExtractBlobDescriptors(const Identifier& identifier, std::string_view bytes = binary_array->GetView(row); PAIMON_ASSIGN_OR_RAISE(bool is_descriptor, BlobDescriptor::IsBlobDescriptor( bytes.data(), bytes.size())); - if (!is_descriptor) { + if (!is_descriptor && !VideoFrameDescriptor::HasMagic(bytes.data(), bytes.size())) { return Status::Invalid( - "requires blob field value to be a serialized BlobDescriptor in source " - "table."); + "requires a serialized BlobDescriptor or VideoFrameDescriptor in the " + "source table."); } auto descriptor_bytes = std::make_shared(bytes.size(), pool.get()); std::memcpy(descriptor_bytes->data(), bytes.data(), bytes.size()); diff --git a/src/paimon/format/blob/CMakeLists.txt b/src/paimon/format/blob/CMakeLists.txt index 239a936a9..8a4a9f1c6 100644 --- a/src/paimon/format/blob/CMakeLists.txt +++ b/src/paimon/format/blob/CMakeLists.txt @@ -14,8 +14,12 @@ # See the License for the specific language governing permissions and # limitations under the License. -set(PAIMON_BLOB_FILE_FORMAT blob_file_batch_reader.cpp blob_file_format_factory.cpp - blob_format_writer.cpp blob_stats_extractor.cpp) +set(PAIMON_BLOB_FILE_FORMAT + blob_file_batch_reader.cpp + blob_file_format_factory.cpp + blob_format_writer.cpp + blob_stats_extractor.cpp + video_file_batch_reader.cpp) add_paimon_lib(paimon_blob_file_format SOURCES @@ -41,6 +45,7 @@ if(PAIMON_BUILD_TESTS) blob_stats_extractor_test.cpp blob_writer_builder_test.cpp blob_file_format_factory_test.cpp + video_file_batch_reader_test.cpp EXTRA_INCLUDES ${BLOB_INCLUDE_DIR} STATIC_LINK_LIBS diff --git a/src/paimon/format/blob/blob_file_format_factory.cpp b/src/paimon/format/blob/blob_file_format_factory.cpp index 8d0f858df..058a61d84 100644 --- a/src/paimon/format/blob/blob_file_format_factory.cpp +++ b/src/paimon/format/blob/blob_file_format_factory.cpp @@ -20,10 +20,87 @@ #include +#include "paimon/common/data/blob_defs.h" +#include "paimon/common/reader/blob_read_context.h" +#include "paimon/common/utils/options_utils.h" #include "paimon/factories/factory.h" #include "paimon/format/blob/blob_file_format.h" +#include "paimon/format/blob/video_file_batch_reader.h" namespace paimon::blob { +namespace { + +class VideoReaderBuilder : public ReaderBuilder, public BlobReadContextAwareBuilder { + public: + VideoReaderBuilder(int32_t batch_size, bool emit_placeholder_sentinel) + : batch_size_(batch_size), emit_placeholder_sentinel_(emit_placeholder_sentinel) {} + + ReaderBuilder* WithMemoryPool(const std::shared_ptr& pool) override { + pool_ = pool; + return this; + } + + void SetBlobReadContext(const std::shared_ptr& context) override { + blob_context_ = context; + } + + Result> Build( + const std::shared_ptr& input) const override { + return VideoFileBatchReader::Create(input, batch_size_, pool_, emit_placeholder_sentinel_, + blob_context_); + } + + private: + int32_t batch_size_; + bool emit_placeholder_sentinel_; + std::shared_ptr pool_ = GetDefaultPool(); + std::shared_ptr blob_context_; +}; + +class VideoFileFormat : public FileFormat { + public: + explicit VideoFileFormat(bool emit_placeholder_sentinel) + : emit_placeholder_sentinel_(emit_placeholder_sentinel) {} + + const std::string& Identifier() const override { + static const std::string identifier = "video"; + return identifier; + } + + Result> CreateReaderBuilder(int32_t batch_size) const override { + return std::make_unique(batch_size, emit_placeholder_sentinel_); + } + + Result> CreateWriterBuilder(::ArrowSchema*, + int32_t) const override { + return Status::NotImplemented("video writing is not supported"); + } + + Result> CreateStatsExtractor( + ::ArrowSchema*) const override { + return Status::NotImplemented("video stats extraction is not supported"); + } + + private: + bool emit_placeholder_sentinel_; +}; + +class VideoFileFormatFactory : public FileFormatFactory { + public: + const char* Identifier() const override { + return "video"; + } + + Result> Create( + const std::map& options) const override { + PAIMON_ASSIGN_OR_RAISE(bool emit_placeholder_sentinel, + OptionsUtils::GetValueFromMap( + options, BlobDefs::kEmitPlaceholderSentinelKey, false)); + return std::make_unique(emit_placeholder_sentinel); + } +}; + +} // namespace const char BlobFileFormatFactory::IDENTIFIER[] = "blob"; @@ -33,5 +110,6 @@ Result> BlobFileFormatFactory::Create( } REGISTER_PAIMON_FACTORY(BlobFileFormatFactory); +REGISTER_PAIMON_FACTORY(VideoFileFormatFactory); } // namespace paimon::blob diff --git a/src/paimon/format/blob/blob_format_writer.cpp b/src/paimon/format/blob/blob_format_writer.cpp index 1838849e7..33f8c2d39 100644 --- a/src/paimon/format/blob/blob_format_writer.cpp +++ b/src/paimon/format/blob/blob_format_writer.cpp @@ -32,6 +32,7 @@ #include "arrow/util/utf8.h" #include "paimon/common/data/blob_defs.h" #include "paimon/common/data/blob_utils.h" +#include "paimon/common/data/video_frame_descriptor.h" #include "paimon/common/io/offset_input_stream.h" #include "paimon/common/memory/memory_segment_utils.h" #include "paimon/common/metrics/metrics_impl.h" @@ -419,6 +420,9 @@ Result> BlobFormatWriter::WriteBlobElements( Result BlobFormatWriter::OpenBlobInputStream( std::string_view blob_data, std::optional element_index) { + if (VideoFrameDescriptor::HasMagic(blob_data.data(), blob_data.size())) { + return Status::NotImplemented("video frame descriptors cannot be written to .blob files"); + } // Whether blob_data is a serialized BlobDescriptor is detected by its magic header rather // than taken from a blob_as_descriptor option, so each value may hold either form. PAIMON_ASSIGN_OR_RAISE(bool is_descriptor, diff --git a/src/paimon/format/blob/blob_format_writer_test.cpp b/src/paimon/format/blob/blob_format_writer_test.cpp index 866411363..3e3ca507c 100644 --- a/src/paimon/format/blob/blob_format_writer_test.cpp +++ b/src/paimon/format/blob/blob_format_writer_test.cpp @@ -32,6 +32,7 @@ #include "gtest/gtest.h" #include "paimon/common/data/blob_defs.h" #include "paimon/common/data/blob_utils.h" +#include "paimon/common/data/video_frame_descriptor.h" #include "paimon/common/utils/arrow/mem_utils.h" #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/common/utils/checked_cast.h" @@ -714,6 +715,22 @@ TEST_P(BlobFormatWriterTest, TestAddBatchWithNullValues) { ArrowArrayRelease(null_c_array.get()); } +TEST_F(BlobFormatWriterWriteNullTest, TestRejectVideoFrameDescriptor) { + const std::string path = dir_->Str() + "/payload.mp4"; + ASSERT_OK(file_system_->WriteFile(path, "encoded", true)); + ASSERT_OK_AND_ASSIGN(std::unique_ptr frame, + VideoFrameDescriptor::Create(path, 0, 7, 42, 0, 0)); + auto bytes = frame->Serialize(pool_); + ASSERT_OK_AND_ASSIGN(std::shared_ptr array, + MakeBlobArrayFromBytes(std::string(bytes->data(), bytes->size()))); + ASSERT_OK_AND_ASSIGN( + std::shared_ptr writer, + BlobFormatWriter::Create(output_stream_, struct_type_, /*write_null_on_missing_file=*/true, + /*write_null_on_fetch_failure=*/true, file_system_, pool_)); + ASSERT_NOK_WITH_MSG(AddBatchOnce(writer, array), + "video frame descriptors cannot be written to .blob files"); +} + TEST_F(BlobFormatWriterWriteNullTest, TestWriteNullOnMissingFile) { ASSERT_OK_AND_ASSIGN( std::shared_ptr writer, diff --git a/src/paimon/format/blob/video_file_batch_reader.cpp b/src/paimon/format/blob/video_file_batch_reader.cpp new file mode 100644 index 000000000..1563cc5e2 --- /dev/null +++ b/src/paimon/format/blob/video_file_batch_reader.cpp @@ -0,0 +1,427 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#include "paimon/format/blob/video_file_batch_reader.h" + +#include +#include +#include + +#include "arrow/api.h" +#include "arrow/c/bridge.h" +#include "paimon/common/data/blob_defs.h" +#include "paimon/common/data/blob_utils.h" +#include "paimon/common/data/video_frame_descriptor.h" +#include "paimon/common/metrics/metrics_impl.h" +#include "paimon/common/reader/blob_read_context.h" +#include "paimon/common/utils/arrow/mem_utils.h" +#include "paimon/common/utils/arrow/status_utils.h" +#include "paimon/common/utils/delta_varint_compressor.h" +#include "paimon/fs/file_system.h" +#include "paimon/io/byte_array_input_stream.h" +#include "paimon/io/data_input_stream.h" + +namespace paimon::blob { +namespace { + +// Encoded video payloads, six delta varint indexes, then the footer. +// The footer stores six little endian int32 index lengths followed by the magic and version. +constexpr int64_t kFooterSize = 29; +constexpr int64_t kLegacyFooterSize = 25; +constexpr int32_t kMagic = 0x4F454449; +constexpr int8_t kVersion = 1; +constexpr uint64_t kMaxIndexMemoryBytes = 64 * 1024 * 1024; +constexpr int64_t kNullReference = -1; +constexpr int64_t kPlaceholderReference = -2; + +using IndexLengths = std::array; + +struct IndexLayout { + int64_t start; + uint64_t decoded_bytes = 0; + uint64_t decode_peak_bytes = 0; +}; + +Status ReadAtFully(InputStream* input, int64_t offset, char* data, int64_t size) { + for (int64_t read = 0; read < size;) { + const Result n = input->Read(data + read, size - read, offset + read); + // An I/O failure leaves the layout undetermined. + if (!n.ok()) { + return n.status().IsInvalid() + ? Status::IOError("failed to read video file. ", n.status().ToString()) + : n.status(); + } + if (n.value() <= 0) { + return Status::IOError("truncated video file"); + } + read += n.value(); + } + return Status::OK(); +} + +Result PlanIndexes(const IndexLengths& lengths, int64_t footer_start) { + if (footer_start < 0) { + return Status::Invalid("video file is smaller than its footer"); + } + IndexLayout layout{footer_start}; + for (int32_t length : lengths) { + if (length < 0 || length > layout.start) { + return Status::Invalid("video indexes exceed the file size"); + } + layout.start -= length; + // A varint can be one byte. The decoder holds both deltas and decoded values. + const uint64_t decoded_bytes = static_cast(length) * sizeof(int64_t); + layout.decode_peak_bytes = + std::max(layout.decode_peak_bytes, layout.decoded_bytes + length + 2 * decoded_bytes); + layout.decoded_bytes += decoded_bytes; + } + return layout; +} + +Status CheckIndexBudget(const IndexLayout& layout, uint64_t materialized_bytes) { + if (std::max(layout.decode_peak_bytes, layout.decoded_bytes + materialized_bytes) > + kMaxIndexMemoryBytes) { + return Status::CapacityError("video indexes exceed the memory budget of ", + kMaxIndexMemoryBytes, " bytes"); + } + return Status::OK(); +} + +Result> ReadIndex(InputStream* input, int64_t* offset, int32_t length) { + std::vector bytes(length); + PAIMON_RETURN_NOT_OK(ReadAtFully(input, *offset, bytes.data(), length)); + *offset += length; + return DeltaVarintCompressor::Decompress(bytes); +} + +bool IsValidFrameRun(int64_t length, int64_t reference, int64_t first, size_t video_count, + int64_t rows) { + return length > 0 && length <= std::numeric_limits::max() - rows && + (reference == kNullReference || reference == kPlaceholderReference || + (reference >= 0 && static_cast(reference) < video_count && first >= 0)); +} + +Status ValidateLegacyLayout(InputStream* input, const IndexLengths& lengths, int64_t index_start) { + // Before apache/paimon#10905, the payload area contained videos followed by keyframe + // indexes. The footer had two physical indexes and three run indexes. + int64_t offset = index_start; + PAIMON_ASSIGN_OR_RAISE(std::vector videos, ReadIndex(input, &offset, lengths[1])); + PAIMON_ASSIGN_OR_RAISE(std::vector keyframes, ReadIndex(input, &offset, lengths[2])); + if (videos.size() != keyframes.size()) { + return Status::Invalid("legacy video and keyframe indexes have different counts"); + } + int64_t remaining = index_start; + for (size_t i = 0; i < videos.size(); ++i) { + if (videos[i] <= 0 || videos[i] > remaining || keyframes[i] < 0 || + keyframes[i] > remaining - videos[i]) { + return Status::Invalid("invalid legacy video or keyframe length"); + } + remaining -= videos[i] + keyframes[i]; + } + if (remaining != 0) { + return Status::Invalid("legacy payload length does not match its indexes"); + } + + PAIMON_ASSIGN_OR_RAISE(std::vector runs, ReadIndex(input, &offset, lengths[3])); + PAIMON_ASSIGN_OR_RAISE(std::vector references, ReadIndex(input, &offset, lengths[4])); + PAIMON_ASSIGN_OR_RAISE(std::vector first_frames, + ReadIndex(input, &offset, lengths[5])); + if (runs.size() != references.size() || runs.size() != first_frames.size()) { + return Status::Invalid("legacy video run indexes have different counts"); + } + int64_t rows = 0; + for (size_t i = 0; i < runs.size(); ++i) { + if (!IsValidFrameRun(runs[i], references[i], first_frames[i], videos.size(), rows)) { + return Status::Invalid("invalid legacy video frame run"); + } + rows += runs[i]; + } + return Status::OK(); +} + +} // namespace + +VideoFileBatchReader::VideoFileBatchReader(std::string uri, int32_t batch_size, + std::shared_ptr pool, + bool emit_placeholder_sentinel, + const std::shared_ptr& blob_context) + : uri_(std::move(uri)), + batch_size_(batch_size), + pool_(std::move(pool)), + arrow_pool_(GetArrowPool(pool_)), + metrics_(std::make_shared()), + emit_placeholder_sentinel_(emit_placeholder_sentinel), + blob_context_(blob_context) {} + +Result> VideoFileBatchReader::Create( + const std::shared_ptr& input, int32_t batch_size, + const std::shared_ptr& pool, bool emit_placeholder_sentinel, + const std::shared_ptr& blob_context) { + if (!input || !pool || batch_size <= 0) { + return Status::Invalid("invalid video reader input, pool, or batch size"); + } + PAIMON_ASSIGN_OR_RAISE(int64_t size, input->Length()); + if (size < kLegacyFooterSize) { + return Status::Invalid( + "corrupt or unsupported .video layout. File is smaller than its footer"); + } + // Both layouts end with the same five lengths, magic and version. The index data + // for those lengths starts four bytes earlier in the six-index interpretation. + char footer[kFooterSize] = {}; + const int64_t footer_size = std::min(size, kFooterSize); + PAIMON_RETURN_NOT_OK(ReadAtFully(input.get(), size - footer_size, + footer + kFooterSize - footer_size, footer_size)); + DataInputStream footer_input(std::make_shared(footer, sizeof(footer))); + footer_input.SetOrder(ByteOrder::PAIMON_LITTLE_ENDIAN); + IndexLengths index_lengths; + for (int32_t& index_length : index_lengths) { + PAIMON_ASSIGN_OR_RAISE(index_length, footer_input.ReadValue()); + } + PAIMON_ASSIGN_OR_RAISE(int32_t magic, footer_input.ReadValue()); + PAIMON_ASSIGN_OR_RAISE(int8_t version, footer_input.ReadValue()); + if (magic != kMagic || version != kVersion) { + return Status::Invalid("corrupt or unsupported .video footer"); + } + + // Check both budgets before reading index data. The legacy probe frees its decoded + // indexes before the six-index reader allocates its own. + const Result modern_layout = PlanIndexes(index_lengths, size - kFooterSize); + if (modern_layout.ok()) { + // Each group has equal entry counts, bounded by its shortest encoded index. + const uint64_t videos = std::min({index_lengths[0], index_lengths[1], index_lengths[2]}); + const uint64_t runs = std::min({index_lengths[3], index_lengths[4], index_lengths[5]}); + PAIMON_RETURN_NOT_OK(CheckIndexBudget( + modern_layout.value(), videos * sizeof(VideoRange) + runs * sizeof(FrameRun))); + } + IndexLengths legacy_lengths = index_lengths; + legacy_lengths[0] = 0; + const Result legacy_layout = PlanIndexes(legacy_lengths, size - kLegacyFooterSize); + Status legacy_status = legacy_layout.status(); + if (legacy_layout.ok()) { + PAIMON_RETURN_NOT_OK(CheckIndexBudget(legacy_layout.value(), 0)); + legacy_status = + ValidateLegacyLayout(input.get(), legacy_lengths, legacy_layout.value().start); + if (!legacy_status.ok() && !legacy_status.IsInvalid()) { + return legacy_status; + } + } + + std::unique_ptr reader; + Status modern_status = modern_layout.status(); + if (modern_layout.ok()) { + PAIMON_ASSIGN_OR_RAISE(std::string uri, input->GetUri()); + reader.reset(new VideoFileBatchReader(std::move(uri), batch_size, pool, + emit_placeholder_sentinel, blob_context)); + modern_status = + reader->ReadSixIndexLayout(input.get(), index_lengths, modern_layout.value().start); + if (!modern_status.ok() && !modern_status.IsInvalid()) { + return modern_status; + } + } + if (legacy_status.ok()) { + if (modern_status.ok()) { + return Status::Invalid( + "ambiguous v1 .video layout. Both five-index and six-index " + "validation passed. Reimport the file"); + } + return Status::Invalid("Legacy five-index .video files require reimport"); + } + if (!modern_status.ok()) { + return Status::Invalid("corrupt or unsupported .video layout. ", modern_status.ToString()); + } + return reader; +} + +Status VideoFileBatchReader::ReadSixIndexLayout(InputStream* input, + const IndexLengths& index_lengths, + int64_t index_start) { + std::array, 6> indexes; + int64_t index_offset = index_start; + for (size_t i = 0; i < indexes.size(); ++i) { + PAIMON_ASSIGN_OR_RAISE(indexes[i], ReadIndex(input, &index_offset, index_lengths[i])); + } + + const auto& video_lengths = indexes[0]; + const auto& moov_offsets = indexes[1]; + const auto& moov_lengths = indexes[2]; + const auto& run_lengths = indexes[3]; + const auto& references = indexes[4]; + const auto& first_frames = indexes[5]; + if (video_lengths.size() != moov_offsets.size() || + video_lengths.size() != moov_lengths.size() || run_lengths.size() != references.size() || + run_lengths.size() != first_frames.size()) { + return Status::Invalid("video indexes have inconsistent entry counts"); + } + + int64_t payload_offset = 0; + videos_.reserve(video_lengths.size()); + for (size_t i = 0; i < video_lengths.size(); ++i) { + const int64_t length = video_lengths[i]; + if (length <= 0 || length > index_start - payload_offset) { + return Status::Invalid("invalid video payload length"); + } + const int64_t moov_offset = moov_offsets[i]; + const int64_t moov_length = moov_lengths[i]; + if (moov_offset < 0 || moov_length < 0 || moov_offset > length || + moov_length > length - moov_offset || (moov_length == 0 && moov_offset != 0)) { + return Status::Invalid("invalid moov range in video payload"); + } + videos_.push_back({payload_offset, length, moov_offset, moov_length}); + payload_offset += length; + } + if (payload_offset != index_start) { + return Status::Invalid("video payload length does not match its index"); + } + + int64_t rows = 0; + runs_.reserve(run_lengths.size()); + for (size_t i = 0; i < run_lengths.size(); ++i) { + const int64_t length = run_lengths[i]; + const int64_t ref = references[i]; + const int64_t first = first_frames[i]; + if (!IsValidFrameRun(length, ref, first, video_lengths.size(), rows) || + (ref >= 0 && first > std::numeric_limits::max() - (length - 1))) { + return Status::Invalid("invalid video frame run"); + } + rows += length; + runs_.push_back({static_cast(rows), ref, first}); + } + row_count_ = rows; + return Status::OK(); +} + +Result> VideoFileBatchReader::GetFileSchema() const { + return Status::NotImplemented("video files have no self-describing schema"); +} + +Status VideoFileBatchReader::SetReadSchema(::ArrowSchema* schema, const std::shared_ptr&, + const std::optional& selection) { + if (!schema) { + return Status::Invalid("video read schema is null"); + } + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr arrow_schema, + arrow::ImportSchema(schema)); + if (arrow_schema->num_fields() != 1 || !BlobUtils::IsBlobField(arrow_schema->field(0))) { + return Status::Invalid("video reader requires one scalar BLOB field"); + } + // Create() bounds row_count_ by INT32_MAX. Seek once to check the entire upper range, + // including bitmap entries above INT32_MAX, which appear negative when dereferenced. + if (selection && + selection->EqualOrLarger(static_cast(row_count_)) != selection->End()) { + return Status::Invalid("video selection row exceeds row count"); + } + + selection_ = selection; + read_row_count_ = selection ? selection->Cardinality() : row_count_; + previous_selected_rows_.clear(); + field_ = arrow_schema->field(0); + current_ = 0; + previous_batch_size_ = 0; + return Status::OK(); +} + +Result VideoFileBatchReader::GetPreviousBatchFileRowId(uint64_t batch_row_id) const { + if (batch_row_id >= previous_batch_size_) { + return Status::Invalid("video batch row ID is out of range"); + } + return selection_ ? previous_selected_rows_[batch_row_id] + : current_ - previous_batch_size_ + batch_row_id; +} + +Result VideoFileBatchReader::GetNumberOfRows() const { + return row_count_; +} + +std::shared_ptr VideoFileBatchReader::GetReaderMetrics() const { + return metrics_; +} + +void VideoFileBatchReader::Close() { + closed_ = true; +} + +Result VideoFileBatchReader::NextBatch() { + if (closed_ || !field_) { + return Status::Invalid("video reader is closed or read schema is unset"); + } + if (current_ >= read_row_count_) { + previous_batch_size_ = 0; + return BatchReader::MakeEofBatch(); + } + const BlobBatchRequest* request = + blob_context_ && blob_context_->request ? &blob_context_->request.value() : nullptr; + if (request && request->max_rows <= 0) { + return Status::Invalid("video read batch row limit must be positive"); + } + const uint64_t batch_limit = request ? std::min(batch_size_, request->max_rows) : batch_size_; + const uint64_t count = std::min(batch_limit, read_row_count_ - current_); + std::vector selected_rows; + if (selection_) { + const int32_t start = + previous_selected_rows_.empty() ? 0 : previous_selected_rows_.back() + 1; + auto selected = selection_->EqualOrLarger(start); + selected_rows.reserve(count); + for (uint64_t i = 0; i < count; ++i, ++selected) { + selected_rows.push_back(*selected); + } + } + arrow::LargeBinaryBuilder builder(arrow_pool_.get()); + PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.Reserve(count)); + for (uint64_t i = 0; i < count; ++i) { + if (request && !request->read_payload) { + PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.AppendNull()); + continue; + } + const uint64_t row = selection_ ? selected_rows[i] : current_ + i; + const auto run = + std::upper_bound(runs_.begin(), runs_.end(), row, + [](uint64_t row, const FrameRun& run) { return row < run.end; }); + if (run->reference == kNullReference) { + PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.AppendNull()); + } else if (run->reference == kPlaceholderReference) { + if (!emit_placeholder_sentinel_) { + return Status::Invalid("video placeholder requires the blob fallback read path"); + } + PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.Append(BlobDefs::PlaceholderSentinelView())); + } else { + const auto& video = videos_[run->reference]; + const uint64_t run_start = run == runs_.begin() ? 0 : (run - 1)->end; + const int64_t frame = run->first_frame + static_cast(row - run_start); + PAIMON_ASSIGN_OR_RAISE( + std::unique_ptr descriptor, + VideoFrameDescriptor::Create(uri_, video.offset, video.length, frame, + video.moov_offset, video.moov_length)); + auto bytes = descriptor->Serialize(pool_); + PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.Append(bytes->data(), bytes->size())); + } + } + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr values, builder.Finish()); + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr array, + arrow::StructArray::Make({values}, {field_})); + auto c_array = std::make_unique<::ArrowArray>(); + auto c_schema = std::make_unique<::ArrowSchema>(); + PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportArray(*array, c_array.get(), c_schema.get())); + PAIMON_RETURN_NOT_OK(AddArrowArrayLifetime(c_array.get(), c_schema.get(), arrow_pool_)); + current_ += count; + previous_batch_size_ = count; + previous_selected_rows_ = std::move(selected_rows); + return std::make_pair(std::move(c_array), std::move(c_schema)); +} + +} // namespace paimon::blob diff --git a/src/paimon/format/blob/video_file_batch_reader.h b/src/paimon/format/blob/video_file_batch_reader.h new file mode 100644 index 000000000..b50f3c823 --- /dev/null +++ b/src/paimon/format/blob/video_file_batch_reader.h @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "paimon/reader/file_batch_reader.h" + +namespace arrow { +class Field; +class MemoryPool; +} // namespace arrow + +namespace paimon { +class InputStream; +class MemoryPool; +struct BlobReadContext; +} // namespace paimon + +namespace paimon::blob { + +/// Reads the row index of a Paimon v1 .video file and emits lazy frame descriptors. +class VideoFileBatchReader : public FileBatchReader { + public: + static Result> Create( + const std::shared_ptr& input, int32_t batch_size, + const std::shared_ptr& pool, bool emit_placeholder_sentinel, + const std::shared_ptr& blob_context); + + Result> GetFileSchema() const override; + Status SetReadSchema(::ArrowSchema* schema, const std::shared_ptr& predicate, + const std::optional& selection) override; + Result NextBatch() override; + Result GetPreviousBatchFileRowId(uint64_t batch_row_id) const override; + Result GetNumberOfRows() const override; + std::shared_ptr GetReaderMetrics() const override; + void Close() override; + bool SupportPreciseBitmapSelection() const override { + return true; + } + + private: + struct VideoRange { + int64_t offset; + int64_t length; + int64_t moov_offset; + int64_t moov_length; + }; + + struct FrameRun { + uint64_t end; + int64_t reference; + int64_t first_frame; + }; + + VideoFileBatchReader(std::string uri, int32_t batch_size, std::shared_ptr pool, + bool emit_placeholder_sentinel, + const std::shared_ptr& blob_context); + + Status ReadSixIndexLayout(InputStream* input, const std::array& index_lengths, + int64_t index_start); + + std::string uri_; + int32_t batch_size_; + std::shared_ptr pool_; + std::shared_ptr arrow_pool_; + std::shared_ptr field_; + std::shared_ptr metrics_; + bool emit_placeholder_sentinel_; + std::shared_ptr blob_context_; + std::vector videos_; + std::vector runs_; + std::optional selection_; + std::vector previous_selected_rows_; + uint64_t row_count_ = 0; + uint64_t read_row_count_ = 0; + uint64_t current_ = 0; + uint64_t previous_batch_size_ = 0; + bool closed_ = false; +}; + +} // namespace paimon::blob diff --git a/src/paimon/format/blob/video_file_batch_reader_test.cpp b/src/paimon/format/blob/video_file_batch_reader_test.cpp new file mode 100644 index 000000000..e4d0d8e32 --- /dev/null +++ b/src/paimon/format/blob/video_file_batch_reader_test.cpp @@ -0,0 +1,376 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#include "paimon/format/blob/video_file_batch_reader.h" + +#include +#include + +#include "arrow/api.h" +#include "arrow/c/bridge.h" +#include "arrow/c/helpers.h" +#include "gtest/gtest.h" +#include "paimon/common/data/blob_defs.h" +#include "paimon/common/data/blob_utils.h" +#include "paimon/common/data/video_frame_descriptor.h" +#include "paimon/common/reader/blob_read_context.h" +#include "paimon/common/utils/delta_varint_compressor.h" +#include "paimon/data/blob.h" +#include "paimon/data/blob_descriptor.h" +#include "paimon/format/file_format.h" +#include "paimon/format/file_format_factory.h" +#include "paimon/fs/local/local_file_system.h" +#include "paimon/io/byte_array_input_stream.h" +#include "paimon/testing/mock/mock_file_system.h" +#include "paimon/testing/utils/testharness.h" +#include "paimon/testing/utils/video_test_utils.h" + +namespace paimon::test { +namespace { + +using blob::VideoFileBatchReader; + +void Append32(std::string* data, uint32_t value) { + for (int32_t i = 0; i < 4; ++i) { + data->push_back(static_cast(value >> (8 * i))); + } +} + +void AppendVideoFooter(std::string* data, const std::vector& index_lengths) { + for (uint32_t length : index_lengths) { + Append32(data, length); + } + Append32(data, 0x4f454449); + data->push_back(1); +} + +std::string MakeVideoFile(bool placeholder = false, int64_t first_moov_length = 3) { + std::string data = "VIDEOfilm"; + const std::vector> indexes = { + {5, 4}, {2, 0}, {first_moov_length, 0}, {2, 1, 1}, {0, placeholder ? -2 : -1, 1}, + {4, 0, 9}}; + std::vector sizes; + for (const auto& values : indexes) { + const auto bytes = DeltaVarintCompressor::Compress(values); + sizes.push_back(bytes.size()); + data.append(bytes.data(), bytes.size()); + } + AppendVideoFooter(&data, sizes); + return data; +} + +TEST(VideoFileBatchReaderTest, ReadsJavaCompatibleRunsAndSelection) { + auto dir = paimon::test::UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + auto fs = std::make_shared(); + const std::string path = dir->Str() + "/part.video"; + ASSERT_OK(fs->WriteFile(path, MakeVideoFile(), true)); + ASSERT_OK_AND_ASSIGN(auto input, fs->Open(path)); + std::shared_ptr shared_input(std::move(input)); + ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", {})); + ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(2)); + ASSERT_OK_AND_ASSIGN(auto reader, builder->Build(shared_input)); + ASSERT_OK_AND_ASSIGN(uint64_t row_count, reader->GetNumberOfRows()); + ASSERT_EQ(row_count, 4); + + auto schema = arrow::schema({BlobUtils::ToArrowField("video", true)}); + ::ArrowSchema c_schema; + ASSERT_TRUE(arrow::ExportSchema(*schema, &c_schema).ok()); + ASSERT_OK(reader->SetReadSchema(&c_schema, nullptr, std::nullopt)); + + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + ASSERT_OK_AND_ASSIGN(uint64_t row_id, reader->GetPreviousBatchFileRowId(0)); + ASSERT_EQ(row_id, 0); + auto imported = arrow::ImportArray(batch.first.get(), batch.second.get()); + ASSERT_TRUE(imported.ok()) << imported.status(); + auto array = imported.ValueOrDie(); + auto rows = std::dynamic_pointer_cast(array); + auto blobs = std::dynamic_pointer_cast(rows->field(0)); + ASSERT_EQ(blobs->length(), 2); + for (int32_t i = 0; i < 2; ++i) { + auto bytes = blobs->GetView(i); + ASSERT_OK_AND_ASSIGN(auto blob, Blob::FromDescriptor(bytes.data(), bytes.size())); + ASSERT_TRUE(blob->IsVideoFrame()); + ASSERT_EQ(blob->FrameIndex(), 4 + i); + ASSERT_EQ(blob->MoovOffset(), 2); + ASSERT_EQ(blob->MoovLength(), 3); + ASSERT_OK_AND_ASSIGN(bool recognized, + BlobDescriptor::IsBlobDescriptor(bytes.data(), bytes.size())); + ASSERT_FALSE(recognized); + auto serialized = blob->ToDescriptor(GetDefaultPool()); + ASSERT_EQ(std::string_view(serialized->data(), serialized->size()), bytes); + ASSERT_OK_AND_ASSIGN(auto payload, blob->ToData(fs, GetDefaultPool())); + ASSERT_EQ(std::string_view(payload->data(), payload->size()), "VIDEO"); + } + + ASSERT_OK_AND_ASSIGN(batch, reader->NextBatch()); + imported = arrow::ImportArray(batch.first.get(), batch.second.get()); + ASSERT_TRUE(imported.ok()) << imported.status(); + array = imported.ValueOrDie(); + rows = std::dynamic_pointer_cast(array); + blobs = std::dynamic_pointer_cast(rows->field(0)); + ASSERT_TRUE(blobs->IsNull(0)); + auto bytes = blobs->GetView(1); + ASSERT_OK_AND_ASSIGN(auto blob, Blob::FromDescriptor(bytes.data(), bytes.size())); + ASSERT_EQ(blob->FrameIndex(), 9); + ASSERT_EQ(blob->MoovOffset(), 0); + ASSERT_EQ(blob->MoovLength(), 0); + ASSERT_OK_AND_ASSIGN(auto second_payload, blob->ToData(fs, GetDefaultPool())); + ASSERT_EQ(std::string_view(second_payload->data(), second_payload->size()), "film"); + + ::ArrowSchema selected_schema; + ASSERT_TRUE(arrow::ExportSchema(*schema, &selected_schema).ok()); + RoaringBitmap32 bitmap; + bitmap.Add(0); + bitmap.Add(3); + ASSERT_OK(reader->SetReadSchema(&selected_schema, nullptr, bitmap)); + ASSERT_OK_AND_ASSIGN(batch, reader->NextBatch()); + ASSERT_OK_AND_ASSIGN(row_id, reader->GetPreviousBatchFileRowId(0)); + ASSERT_EQ(row_id, 0); + ASSERT_OK_AND_ASSIGN(row_id, reader->GetPreviousBatchFileRowId(1)); + ASSERT_EQ(row_id, 3); + + ::ArrowSchema empty_schema; + ASSERT_TRUE(arrow::ExportSchema(*schema, &empty_schema).ok()); + ASSERT_OK(reader->SetReadSchema(&empty_schema, nullptr, RoaringBitmap32())); + ASSERT_OK_AND_ASSIGN(auto empty_batch, reader->NextBatch()); + ASSERT_TRUE(BatchReader::IsEofBatch(empty_batch)); + ASSERT_NOK(reader->GetPreviousBatchFileRowId(0)); + reader.reset(); + // The exported array keeps its Arrow allocator alive after the reader is destroyed. + imported = arrow::ImportArray(batch.first.get(), batch.second.get()); + ASSERT_TRUE(imported.ok()) << imported.status(); + ASSERT_EQ(imported.ValueOrDie()->length(), 2); +} + +TEST(VideoFileBatchReaderTest, RoundTripsJavaFrameDescriptor) { + ASSERT_OK_AND_ASSIGN(std::string bytes, ReadJavaVideoFixture("video-frame-descriptor-v1.hex")); + ASSERT_OK_AND_ASSIGN(std::unique_ptr blob, + Blob::FromDescriptor(bytes.data(), bytes.size())); + ASSERT_TRUE(blob->IsVideoFrame()); + ASSERT_EQ(blob->Uri(), "s3://bucket/视频.mp4"); + ASSERT_EQ(blob->FrameIndex(), 42); + ASSERT_EQ(blob->MoovOffset(), 0); + ASSERT_EQ(blob->MoovLength(), 0); + auto serialized = blob->ToDescriptor(GetDefaultPool()); + ASSERT_EQ(std::string_view(serialized->data(), serialized->size()), bytes); + ASSERT_OK_AND_ASSIGN( + std::unique_ptr frame, + VideoFrameDescriptor::Create("s3://bucket/视频.mp4", /*offset=*/7, /*length=*/99, + /*frame_index=*/42, /*moov_offset=*/0, /*moov_length=*/0)); + auto encoded = frame->Serialize(GetDefaultPool()); + ASSERT_EQ(std::string_view(encoded->data(), encoded->size()), bytes); + ASSERT_NOK(BlobDescriptor::Deserialize(bytes.data(), bytes.size())); + ASSERT_NOK(Blob::FromDescriptor(bytes.data(), 5)); + ASSERT_NOK(Blob::FromDescriptor(bytes.data(), bytes.size() - 1)); +} + +TEST(VideoFileBatchReaderTest, RejectsInvalidFooter) { + auto dir = paimon::test::UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + auto fs = std::make_shared(); + const std::string path = dir->Str() + "/bad.video"; + auto bytes = MakeVideoFile(); + bytes.back() = 2; + ASSERT_OK(fs->WriteFile(path, bytes, true)); + ASSERT_OK_AND_ASSIGN(auto input, fs->Open(path)); + std::shared_ptr shared_input(std::move(input)); + ASSERT_NOK(VideoFileBatchReader::Create(shared_input, 2, GetDefaultPool(), false, nullptr)); +} + +TEST(VideoFileBatchReaderTest, RejectsLegacyAndAmbiguousVideoLayouts) { + // Five indexes describe two 25-byte videos, no keyframe indexes and four + // one-row runs. The same bytes also encode two 22-byte videos with no moov + // ranges and four 25-row runs when read using the six-index footer. + std::string bytes(50, '\0'); + bytes[44] = 44; // Six-index video lengths: 22, 22. + constexpr char indexes[] = + "\x32\x00" // Legacy video lengths: 25, 25. + "\x00\x00" // Legacy keyframe lengths: 0, 0. + "\x02\x00\x00\x00" // Legacy run lengths: 1, 1, 1, 1. + "\x00\x02\x01\x02" // Legacy references: 0, 1, 0, 1. + "\x02\x00\x00\x00"; // Legacy first frames: 1, 1, 1, 1. + bytes.append(indexes, sizeof(indexes) - 1); + AppendVideoFooter(&bytes, {2, 2, 4, 4, 4}); + auto input = std::make_shared(bytes.data(), bytes.size()); + ASSERT_NOK_WITH_MSG(VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr), + "ambiguous v1 .video layout"); + + // This byte belongs to the five-index payload and the six-index video lengths. + // Zero video lengths invalidate only the six-index interpretation. + bytes[44] = 0; + ASSERT_NOK_WITH_MSG(VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr), + "Legacy five-index .video files require reimport"); +} + +TEST(VideoFileBatchReaderTest, ReadsDenseSelectionInSmallBatches) { + constexpr int32_t kRows = 512 * 1024 * 1024; + const auto runs = DeltaVarintCompressor::Compress({kRows}); + std::string bytes(runs.data(), runs.size()); + bytes.append("\x01\x00", 2); // One NULL reference and first frame 0. + AppendVideoFooter(&bytes, {0, 0, 0, static_cast(runs.size()), 1, 1}); + auto input = std::make_shared(bytes.data(), bytes.size()); + auto context = std::make_shared(); + ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, + VideoFileBatchReader::Create(input, 4, GetDefaultPool(), false, context)); + auto schema = arrow::schema({BlobUtils::ToArrowField("video", true)}); + ::ArrowSchema c_schema; + ASSERT_TRUE(arrow::ExportSchema(*schema, &c_schema).ok()); + std::optional bitmap(std::in_place); + bitmap->AddRange(1, kRows); + bitmap->RemoveRange(2, 5); + ASSERT_OK(reader->SetReadSchema(&c_schema, nullptr, bitmap)); + bitmap.reset(); + + context->request = BlobBatchRequest{2, /*read_payload=*/false}; + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + ASSERT_EQ(batch.first->length, 2); + ASSERT_EQ(reader->GetPreviousBatchFileRowId(0).value(), 1); + ASSERT_EQ(reader->GetPreviousBatchFileRowId(1).value(), 5); + ArrowArrayRelease(batch.first.get()); + ArrowSchemaRelease(batch.second.get()); + + context->request = BlobBatchRequest{3, /*read_payload=*/true}; + ASSERT_OK_AND_ASSIGN(batch, reader->NextBatch()); + ASSERT_EQ(batch.first->length, 3); + ASSERT_EQ(reader->GetPreviousBatchFileRowId(2).value(), 8); + ASSERT_EQ(reader->GetPreviousBatchFileRowId(0).value(), 6); + ASSERT_NOK(reader->GetPreviousBatchFileRowId(3)); + ArrowArrayRelease(batch.first.get()); + ArrowSchemaRelease(batch.second.get()); + + for (int32_t invalid : {kRows, -1}) { + ASSERT_TRUE(arrow::ExportSchema(*schema, &c_schema).ok()); + ASSERT_NOK_WITH_MSG( + reader->SetReadSchema(&c_schema, nullptr, RoaringBitmap32::From({1, invalid})), + "video selection row exceeds row count"); + } +} + +TEST(VideoFileBatchReaderTest, RejectsOversizedIndexesBeforeReadingThem) { + class FooterOnlyStream : public MockInputStream { + public: + explicit FooterOnlyStream(const std::vector& index_lengths) + : footer_offset_( + std::accumulate(index_lengths.begin(), index_lengths.end(), int64_t{0})) { + AppendVideoFooter(&footer_, index_lengths); + } + + Result Length() const override { + return footer_offset_ + footer_.size(); + } + + Result Read(char* buffer, int64_t size, int64_t offset) override { + if (offset != footer_offset_ || size != static_cast(footer_.size())) { + return Status::IOError("unexpected index read"); + } + std::memcpy(buffer, footer_.data(), footer_.size()); + return size; + } + + private: + int64_t footer_offset_; + std::string footer_; + }; + + constexpr uint32_t kMiB = 1024 * 1024; + // A single 64 MiB index exceeds the decode budget. Three 1.5 MiB run indexes fit + // during decoding but exceed the budget once the runs and decoded indexes coexist. + constexpr uint32_t kRunIndexBytes = 3 * kMiB / 2; + for (const std::vector& lengths : + {std::vector{64 * kMiB, 0, 0, 0, 0, 0}, + std::vector{0, 0, 0, kRunIndexBytes, kRunIndexBytes, kRunIndexBytes}}) { + auto result = VideoFileBatchReader::Create(std::make_shared(lengths), 2, + GetDefaultPool(), false, nullptr); + ASSERT_TRUE(result.status().IsCapacityError()) << result.status(); + } +} + +TEST(VideoFileBatchReaderTest, ReadsLargeIndexWithinMemoryBudget) { + constexpr uint32_t kRuns = 1024 * 1024; + // Each run contains one NULL row. The indexes encode deltas as single-byte varints. + std::string bytes(3 * kRuns, '\0'); + bytes[0] = 2; // Run length 1. + bytes[kRuns] = 1; // Video reference -1. + AppendVideoFooter(&bytes, {0, 0, 0, kRuns, kRuns, kRuns}); + auto input = std::make_shared(bytes.data(), bytes.size()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, + VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr)); + ASSERT_OK_AND_ASSIGN(uint64_t rows, reader->GetNumberOfRows()); + ASSERT_EQ(rows, kRuns); +} + +TEST(VideoFileBatchReaderTest, RejectsMoovRangeOutsideVideo) { + auto dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + auto fs = std::make_shared(); + const std::string path = dir->Str() + "/bad.video"; + ASSERT_OK( + fs->WriteFile(path, MakeVideoFile(/*placeholder=*/false, /*first_moov_length=*/4), true)); + ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs->Open(path)); + auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); + ASSERT_NOK_WITH_MSG(result, "corrupt or unsupported .video layout"); + ASSERT_NOK_WITH_MSG(result, "invalid moov range"); +} + +TEST(VideoFileBatchReaderTest, ExposesPlaceholdersOnlyForBlobFallback) { + auto dir = paimon::test::UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + auto fs = std::make_shared(); + const std::string path = dir->Str() + "/part.video"; + ASSERT_OK(fs->WriteFile(path, MakeVideoFile(/*placeholder=*/true), true)); + auto schema = arrow::schema({BlobUtils::ToArrowField("video", true)}); + for (bool fallback : {false, true}) { + std::map options; + if (fallback) { + options[BlobDefs::kEmitPlaceholderSentinelKey] = "true"; + } + ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", options)); + ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(4)); + auto* context_builder = dynamic_cast(builder.get()); + ASSERT_TRUE(context_builder); + auto context = std::make_shared(); + context_builder->SetBlobReadContext(context); + ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs->Open(path)); + ASSERT_OK_AND_ASSIGN(auto reader, builder->Build(input)); + ::ArrowSchema c_schema; + ASSERT_TRUE(arrow::ExportSchema(*schema, &c_schema).ok()); + ASSERT_OK(reader->SetReadSchema(&c_schema, nullptr, std::nullopt)); + if (!fallback) { + ASSERT_NOK(reader->NextBatch()); + continue; + } + context->request = BlobBatchRequest{2, /*read_payload=*/false}; + ASSERT_OK_AND_ASSIGN(auto skipped_batch, reader->NextBatch()); + auto skipped = arrow::ImportArray(skipped_batch.first.get(), skipped_batch.second.get()); + ASSERT_TRUE(skipped.ok()) << skipped.status(); + ASSERT_EQ(skipped.ValueOrDie()->length(), 2); + context->request = BlobBatchRequest{1, /*read_payload=*/true}; + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + auto imported = arrow::ImportArray(batch.first.get(), batch.second.get()); + ASSERT_TRUE(imported.ok()) << imported.status(); + auto rows = std::static_pointer_cast(imported.ValueOrDie()); + auto blobs = std::static_pointer_cast(rows->field(0)); + ASSERT_EQ(blobs->length(), 1); + ASSERT_EQ(blobs->GetView(0), BlobDefs::PlaceholderSentinelView()); + } +} + +} // namespace +} // namespace paimon::test diff --git a/src/paimon/testing/utils/video_test_utils.h b/src/paimon/testing/utils/video_test_utils.h new file mode 100644 index 000000000..f767d5f06 --- /dev/null +++ b/src/paimon/testing/utils/video_test_utils.h @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#pragma once + +#include +#include +#include + +#include "paimon/result.h" +#include "paimon/status.h" +#include "paimon/testing/utils/testharness.h" + +namespace paimon::test { + +// Apache Paimon's Java fixtures from apache/paimon#10905 (5faef60f6fee). +inline Result ReadJavaVideoFixture(const std::string& name) { + std::ifstream input(GetDataDir() + "/video_format.data/" + name); + if (!input) { + return Status::IOError("cannot open Java video fixture ", name); + } + std::string bytes; + for (std::string line; std::getline(input, line);) { + if (line.empty() || line.front() == '#') { + continue; + } + if (line.size() % 2 != 0) { + return Status::Invalid("odd length in Java video fixture ", name); + } + for (size_t i = 0; i < line.size(); i += 2) { + unsigned char byte = 0; + const char* end = line.data() + i + 2; + const auto parsed = std::from_chars(line.data() + i, end, byte, 16); + if (parsed.ec != std::errc() || parsed.ptr != end) { + return Status::Invalid("invalid hex in Java video fixture ", name); + } + bytes.push_back(static_cast(byte)); + } + } + if (bytes.empty() || !input.eof()) { + return Status::Invalid("empty or unreadable Java video fixture ", name); + } + return bytes; +} + +} // namespace paimon::test diff --git a/test/inte/blob_table_inte_test.cpp b/test/inte/blob_table_inte_test.cpp index 1bd320e49..9d03b8fb1 100644 --- a/test/inte/blob_table_inte_test.cpp +++ b/test/inte/blob_table_inte_test.cpp @@ -84,6 +84,7 @@ #include "paimon/testing/utils/io_exception_helper.h" #include "paimon/testing/utils/test_helper.h" #include "paimon/testing/utils/testharness.h" +#include "paimon/testing/utils/video_test_utils.h" #include "paimon/write_context.h" namespace paimon { @@ -1328,6 +1329,99 @@ std::shared_ptr MakeBlobUpdateArray( return std::dynamic_pointer_cast(array); } +TEST_P(BlobTableInteTest, TestReadVideoLayersInManagedSplit) { + const arrow::FieldVector fields = {arrow::field("id", arrow::int32()), + BlobUtils::ToArrowField("video", /*nullable=*/true)}; + const std::map options = { + {Options::FILE_FORMAT, GetParam()}, {Options::FILE_SYSTEM, "local"}, + {Options::ROW_TRACKING_ENABLED, "true"}, {Options::DATA_EVOLUTION_ENABLED, "true"}, + {BlobDefs::kVideoFrameFieldOption, "video"}, + }; + CreateTable(fields, /*partition_keys=*/{}, options); + const std::string table_path = PathUtil::JoinPath(dir_->Str(), "foo.db/bar"); + auto id_array = + arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_({fields[0]}), "[[10], [20]]") + .ValueOrDie(); + // The table option is present, but a projection that excludes video can still write. + ASSERT_OK_AND_ASSIGN(auto commit_messages, WriteArray(table_path, {}, {"id"}, {id_array})); + ASSERT_OK(Commit(table_path, commit_messages)); + auto video_array = MakeBlobUpdateArray(fields[1], {"payload"}); + ASSERT_NOK_WITH_MSG(WriteArray(table_path, {}, {"video"}, {video_array}), + "writing video-frame-field 'video' is not supported"); + + ASSERT_OK_AND_ASSIGN(std::shared_ptr plan, ScanTable(table_path)); + ASSERT_EQ(plan->Splits().size(), 1); + auto main_split = std::dynamic_pointer_cast(plan->Splits()[0]); + ASSERT_TRUE(main_split); + auto files = main_split->DataFiles(); + ASSERT_EQ(files.size(), 1); + const auto& data_file = files[0]; + ASSERT_TRUE(data_file->first_row_id); + const int64_t first_row_id = data_file->first_row_id.value(); + const int64_t sequence = data_file->max_sequence_number; + auto fs = dir_->GetFileSystem(); + + ASSERT_OK_AND_ASSIGN(std::string base, ReadJavaVideoFixture("video-v1-moov.hex")); + // Two runs with no physical payloads: the first falls back, the second overwrites with NULL. + constexpr char overlay[] = + "\x02\x00\x03\x02\x00\x00" // Run lengths, references, first frames. + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x02\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00" + "IDEO\x01"; + ASSERT_OK( + fs->WriteFile(PathUtil::JoinPath(main_split->BucketPath(), "base.video"), base, true)); + ASSERT_OK(fs->WriteFile(PathUtil::JoinPath(main_split->BucketPath(), "overlay.video"), + std::string(overlay, sizeof(overlay) - 1), true)); + auto make_video_meta = [&](const std::string& name, int64_t file_size, int64_t seq) { + return DataFileMeta::ForAppend(name, file_size, /*row_count=*/2, SimpleStats::EmptyStats(), + seq, seq, /*schema_id=*/0, FileSource::Append(), + std::nullopt, std::nullopt, first_row_id, + std::vector{"video"}); + }; + ASSERT_OK_AND_ASSIGN(std::shared_ptr older, + make_video_meta("base.video", base.size(), sequence + 1)); + ASSERT_OK_AND_ASSIGN(std::shared_ptr newer, + make_video_meta("overlay.video", sizeof(overlay) - 1, sequence + 2)); + files.push_back(older); + files.push_back(newer); + ASSERT_OK_AND_ASSIGN(std::shared_ptr split, + DataSplitImpl::Builder(main_split->Partition(), main_split->Bucket(), + main_split->BucketPath(), std::move(files)) + .WithSnapshot(main_split->SnapshotId()) + .WithTotalBuckets(main_split->TotalBuckets()) + .RawConvertible(false) + .Build()); + auto video_plan = + std::make_shared(plan->SnapshotId(), std::vector>{split}); + ASSERT_OK_AND_ASSIGN( + std::shared_ptr result, + ReadTable(table_path, {"id", "video", "_ROW_ID"}, video_plan, + /*predicate=*/nullptr, {{Options::BLOB_AS_DESCRIPTOR, "false"}})); + ASSERT_TRUE(result); + auto rows = + checked_pointer_cast(arrow::Concatenate(result->chunks()).ValueOrDie()); + ASSERT_EQ(rows->length(), 2); + auto ids = checked_pointer_cast(rows->GetFieldByName("id")); + auto row_ids = checked_pointer_cast(rows->GetFieldByName("_ROW_ID")); + auto video = checked_pointer_cast(rows->GetFieldByName("video")); + ASSERT_EQ(ids->Value(0), 10); + ASSERT_EQ(ids->Value(1), 20); + ASSERT_EQ(row_ids->Value(0), first_row_id); + ASSERT_EQ(row_ids->Value(1), first_row_id + 1); + ASSERT_TRUE(video->IsNull(1)); + ASSERT_FALSE(video->IsNull(0)); + const std::string_view bytes = video->GetView(0); + ASSERT_OK_AND_ASSIGN(std::unique_ptr frame, + Blob::FromDescriptor(bytes.data(), bytes.size())); + ASSERT_TRUE(frame->IsVideoFrame()); + ASSERT_EQ(frame->FrameIndex(), 7); + ASSERT_EQ(frame->MoovOffset(), 16); + ASSERT_EQ(frame->MoovLength(), 8); + ASSERT_OK_AND_ASSIGN(auto payload, frame->ToData(fs, pool_)); + ASSERT_EQ(std::string_view(payload->data(), payload->size()), + std::string_view(base).substr(0, 24)); +} + TEST_P(BlobTableInteTest, TestDataEvolutionBlobPartialUpdateFallback) { // the blob column is updated to null below, so it must be nullable arrow::FieldVector fields = {arrow::field("f0", arrow::int32()), @@ -4550,6 +4644,92 @@ TEST_P(BlobTableInteTest, TestBlobViewFieldWithUpstreamDescriptorBlob) { << "expected:" << expected_with_rk->ToString(); } +TEST_P(BlobTableInteTest, TestBlobViewFieldWithUpstreamVideo) { + if (GetParam() == "mosaic") { + GTEST_SKIP() << "Mosaic does not support inline BLOB view fields"; + } + const auto downstream_fields = CreateBlobViewTable(/*deletion_vectors_enabled=*/false); + const std::string downstream_path = PathUtil::JoinPath(dir_->Str(), "foo.db/bar"); + const Identifier upstream_identifier("foo", "video_source"); + const arrow::FieldVector upstream_fields = {downstream_fields[0], + BlobUtils::ToArrowField("video", true)}; + const std::map upstream_options = { + {Options::FILE_FORMAT, GetParam()}, + {Options::FILE_SYSTEM, "local"}, + {Options::BUCKET, "-1"}, + {Options::ROW_TRACKING_ENABLED, "true"}, + {Options::DATA_EVOLUTION_ENABLED, "true"}, + {BlobDefs::kVideoFrameFieldOption, "video"}}; + ASSERT_OK_AND_ASSIGN(std::shared_ptr catalog, Catalog::Create(dir_->Str(), {})); + ArrowSchema upstream_schema; + ASSERT_TRUE(arrow::ExportSchema(*arrow::schema(upstream_fields), &upstream_schema).ok()); + ASSERT_OK(catalog->CreateTable(upstream_identifier, &upstream_schema, {}, {}, upstream_options, + /*ignore_if_exists=*/false)); + ASSERT_OK_AND_ASSIGN(std::string upstream_path, catalog->GetTableLocation(upstream_identifier)); + + auto id_rows = checked_pointer_cast( + arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_({upstream_fields[0]}), + "[[10], [20]]") + .ValueOrDie()); + ASSERT_OK_AND_ASSIGN(auto upstream_messages, WriteArray(upstream_path, {}, {"f0"}, {id_rows})); + ASSERT_EQ(upstream_messages.size(), 1); + auto upstream_message = std::dynamic_pointer_cast(upstream_messages[0]); + ASSERT_TRUE(upstream_message); + auto& new_files = upstream_message->data_increment_.new_files_; + ASSERT_EQ(new_files.size(), 1); + + // Attach a Java-written video alongside the data file so the upstream catalog scan sees it. + ASSERT_OK_AND_ASSIGN(std::string video, ReadJavaVideoFixture("video-v1-moov.hex")); + const std::string video_name = "frames.video"; + auto fs = dir_->GetFileSystem(); + ASSERT_OK(fs->WriteFile(PathUtil::JoinPath(upstream_path, "bucket-0/" + video_name), video, + /*overwrite=*/false)); + const auto& data_file = new_files[0]; + ASSERT_OK_AND_ASSIGN(std::shared_ptr video_file, + DataFileMeta::ForAppend( + video_name, video.size(), /*row_count=*/2, SimpleStats::EmptyStats(), + data_file->min_sequence_number, data_file->max_sequence_number, + data_file->schema_id, FileSource::Append(), std::nullopt, std::nullopt, + std::nullopt, std::vector{"video"})); + new_files.push_back(std::move(video_file)); + ASSERT_OK(Commit(upstream_path, upstream_messages)); + + arrow::LargeBinaryBuilder view_builder; + for (const int64_t row_id : {1, 0}) { + BlobViewStruct view(upstream_identifier, /*field_id=*/1, row_id); + ASSERT_OK_AND_ASSIGN(PAIMON_UNIQUE_PTR bytes, view.Serialize(pool_)); + ASSERT_TRUE(view_builder.Append(bytes->data(), bytes->size()).ok()); + } + std::shared_ptr view_array; + ASSERT_TRUE(view_builder.Finish(&view_array).ok()); + auto downstream_rows = + arrow::StructArray::Make({id_rows->field(0), view_array}, downstream_fields).ValueOrDie(); + ASSERT_OK_AND_ASSIGN(auto downstream_messages, + WriteArray(downstream_path, {}, {"f0", "view"}, {downstream_rows})); + ASSERT_OK(Commit(downstream_path, downstream_messages)); + + ASSERT_OK_AND_ASSIGN(auto result, ScanAndReadResult(downstream_path, {"view"})); + ASSERT_TRUE(result); + auto rows = + checked_pointer_cast(arrow::Concatenate(result->chunks()).ValueOrDie()); + ASSERT_EQ(rows->length(), 2); + auto views = checked_pointer_cast(rows->GetFieldByName("view")); + ASSERT_TRUE(views); + for (int64_t row = 0; row < views->length(); ++row) { + ASSERT_FALSE(views->IsNull(row)); + const std::string_view bytes = views->GetView(row); + ASSERT_OK_AND_ASSIGN(std::unique_ptr frame, + Blob::FromDescriptor(bytes.data(), bytes.size())); + ASSERT_TRUE(frame->IsVideoFrame()); + ASSERT_EQ(frame->FrameIndex(), 8 - row); + ASSERT_EQ(frame->MoovOffset(), 16); + ASSERT_EQ(frame->MoovLength(), 8); + ASSERT_OK_AND_ASSIGN(auto payload, frame->ToData(fs, pool_)); + ASSERT_EQ(std::string_view(payload->data(), payload->size()), + std::string_view(video).substr(0, 24)); + } +} + TEST_P(BlobTableInteTest, TestBlobViewFieldWithMultipleUpstreamTables) { auto file_format = GetParam(); if (file_format == "avro" || file_format == "mosaic") { diff --git a/test/test_data/video_format.data/video-frame-descriptor-v1.hex b/test/test_data/video_format.data/video-frame-descriptor-v1.hex new file mode 100644 index 000000000..a1db5dfc9 --- /dev/null +++ b/test/test_data/video_format.data/video-frame-descriptor-v1.hex @@ -0,0 +1,20 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + + +# Video frame descriptor v1 with optional moov range. +014d52464f454449561600000073333a2f2f6275636b65742fe8a786e9a2912e6d7034070000000000000063000000000000002a0000000000000000000000000000000000000000000000 diff --git a/test/test_data/video_format.data/video-v1-moov.hex b/test/test_data/video_format.data/video-v1-moov.hex new file mode 100644 index 000000000..c69fbfa96 --- /dev/null +++ b/test/test_data/video_format.data/video-v1-moov.hex @@ -0,0 +1,20 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + + +# Single video, moov at offset 16, two frames starting at 7. +0000000866747970000000086d646174000000086d6f6f7630201004000e0100000001000000010000000100000001000000010000004944454f01