Project import generated by Copybara.

GitOrigin-RevId: 0517756260533d374df93679965ca662d0ec6943
This commit is contained in:
MediaPipe Team
2020-01-10 13:13:24 -08:00
committed by Hadon Nash
parent 38ee2603a7
commit ae6be10afe
192 changed files with 16410 additions and 592 deletions
+46
View File
@@ -65,6 +65,15 @@ proto_library(
],
)
proto_library(
name = "video_pre_stream_calculator_proto",
srcs = ["video_pre_stream_calculator.proto"],
visibility = ["//visibility:public"],
deps = [
"//mediapipe/framework:calculator_proto",
],
)
mediapipe_cc_proto_library(
name = "motion_analysis_calculator_cc_proto",
srcs = ["motion_analysis_calculator.proto"],
@@ -98,6 +107,16 @@ mediapipe_cc_proto_library(
deps = [":box_tracker_calculator_proto"],
)
mediapipe_cc_proto_library(
name = "video_pre_stream_calculator_cc_proto",
srcs = ["video_pre_stream_calculator.proto"],
cc_deps = [
"//mediapipe/framework:calculator_cc_proto",
],
visibility = ["//visibility:public"],
deps = [":video_pre_stream_calculator_proto"],
)
mediapipe_cc_proto_library(
name = "flow_to_image_calculator_cc_proto",
srcs = ["flow_to_image_calculator.proto"],
@@ -280,6 +299,19 @@ cc_library(
alwayslink = 1,
)
cc_library(
name = "video_pre_stream_calculator",
srcs = ["video_pre_stream_calculator.cc"],
visibility = ["//visibility:public"],
deps = [
":video_pre_stream_calculator_cc_proto",
"//mediapipe/framework:calculator_framework",
"//mediapipe/framework/formats:image_frame",
"//mediapipe/framework/formats:video_stream_header",
],
alwayslink = 1,
)
filegroup(
name = "test_videos",
srcs = [
@@ -411,3 +443,17 @@ cc_test(
"//mediapipe/util/tracking:tracking_cc_proto",
],
)
cc_test(
name = "video_pre_stream_calculator_test",
srcs = ["video_pre_stream_calculator_test.cc"],
deps = [
":video_pre_stream_calculator",
"//mediapipe/framework:calculator_framework",
"//mediapipe/framework/formats:image_frame",
"//mediapipe/framework/formats:video_stream_header",
"//mediapipe/framework/port:gtest_main",
"//mediapipe/framework/port:parse_text_proto",
"//mediapipe/framework/port:status",
],
)
@@ -72,6 +72,8 @@ ImageFormat::Format GetImageFormat(int num_channels) {
// OpenCV's VideoCapture doesn't decode audio tracks. If the audio tracks need
// to be saved, specify an output side packet with tag "SAVED_AUDIO_PATH".
// The calculator will call FFmpeg binary to save audio tracks as an aac file.
// If the audio tracks can't be extracted by FFmpeg, the output side packet
// will contain an empty std::string.
//
// Example config:
// node {
@@ -150,13 +152,23 @@ class OpenCvVideoDecoderCalculator : public CalculatorBase {
if (cc->OutputSidePackets().HasTag("SAVED_AUDIO_PATH")) {
#ifdef HAVE_FFMPEG
std::string saved_audio_path = std::tmpnam(nullptr);
system(absl::StrCat("ffmpeg -nostats -loglevel 0 -i ", input_file_path,
" -vn -f adts ", saved_audio_path)
.c_str());
cc->OutputSidePackets()
.Tag("SAVED_AUDIO_PATH")
.Set(MakePacket<std::string>(saved_audio_path));
std::string ffmpeg_command =
absl::StrCat("ffmpeg -nostats -loglevel 0 -i ", input_file_path,
" -vn -f adts ", saved_audio_path);
system(ffmpeg_command.c_str());
int status_code = system(absl::StrCat("ls ", saved_audio_path).c_str());
if (status_code == 0) {
cc->OutputSidePackets()
.Tag("SAVED_AUDIO_PATH")
.Set(MakePacket<std::string>(saved_audio_path));
} else {
LOG(WARNING) << "FFmpeg can't extract audio from " << input_file_path
<< " by executing the following command: "
<< ffmpeg_command;
cc->OutputSidePackets()
.Tag("SAVED_AUDIO_PATH")
.Set(MakePacket<std::string>(std::string()));
}
#else
return ::mediapipe::InvalidArgumentErrorBuilder(MEDIAPIPE_LOC)
<< "OpenCVVideoDecoderCalculator can't save the audio file "
@@ -55,8 +55,12 @@ TEST(OpenCvVideoDecoderCalculatorTest, TestMp4Avc720pVideo) {
EXPECT_EQ(640, header.height);
EXPECT_FLOAT_EQ(6.0f, header.duration);
EXPECT_FLOAT_EQ(30.0f, header.frame_rate);
EXPECT_EQ(180, runner.Outputs().Tag("VIDEO").packets.size());
for (int i = 0; i < 180; ++i) {
// The number of the output packets should be 180.
// Some OpenCV version returns the first two frames with the same timestamp on
// macos and we might miss one frame here.
int num_of_packets = runner.Outputs().Tag("VIDEO").packets.size();
EXPECT_GE(num_of_packets, 179);
for (int i = 0; i < num_of_packets; ++i) {
Packet image_frame_packet = runner.Outputs().Tag("VIDEO").packets[i];
cv::Mat output_mat =
formats::MatView(&(image_frame_packet.Get<ImageFrame>()));
@@ -141,8 +145,12 @@ TEST(OpenCvVideoDecoderCalculatorTest, TestMkvVp8Video) {
EXPECT_EQ(320, header.height);
EXPECT_FLOAT_EQ(6.0f, header.duration);
EXPECT_FLOAT_EQ(30.0f, header.frame_rate);
EXPECT_EQ(180, runner.Outputs().Tag("VIDEO").packets.size());
for (int i = 0; i < 180; ++i) {
// The number of the output packets should be 180.
// Some OpenCV version returns the first two frames with the same timestamp on
// macos and we might miss one frame here.
int num_of_packets = runner.Outputs().Tag("VIDEO").packets.size();
EXPECT_GE(num_of_packets, 179);
for (int i = 0; i < num_of_packets; ++i) {
Packet image_frame_packet = runner.Outputs().Tag("VIDEO").packets[i];
cv::Mat output_mat =
formats::MatView(&(image_frame_packet.Get<ImageFrame>()));
@@ -183,14 +183,20 @@ class OpenCvVideoEncoderCalculator : public CalculatorBase {
#ifdef HAVE_FFMPEG
const std::string& audio_file_path =
cc->InputSidePackets().Tag("AUDIO_FILE_PATH").Get<std::string>();
// A temp output file is needed because FFmpeg can't do in-place editing.
const std::string temp_file_path = std::tmpnam(nullptr);
system(absl::StrCat("mv ", output_file_path_, " ", temp_file_path,
"&& ffmpeg -nostats -loglevel 0 -i ", temp_file_path,
" -i ", audio_file_path,
" -c copy -map 0:v:0 -map 1:a:0 ", output_file_path_,
"&& rm ", temp_file_path)
.c_str());
if (audio_file_path.empty()) {
LOG(WARNING) << "OpenCvVideoEncoderCalculator isn't able to attach the "
"audio tracks to the generated video because the audio "
"file path is not specified.";
} else {
// A temp output file is needed because FFmpeg can't do in-place editing.
const std::string temp_file_path = std::tmpnam(nullptr);
system(absl::StrCat("mv ", output_file_path_, " ", temp_file_path,
"&& ffmpeg -nostats -loglevel 0 -i ", temp_file_path,
" -i ", audio_file_path,
" -c copy -map 0:v:0 -map 1:a:0 ", output_file_path_,
"&& rm ", temp_file_path)
.c_str());
}
#else
return ::mediapipe::InvalidArgumentErrorBuilder(MEDIAPIPE_LOC)
@@ -210,8 +210,8 @@ TEST(OpenCvVideoEncoderCalculatorTest, TestMkvVp8Video) {
EXPECT_EQ(video_header.frame_rate,
static_cast<double>(cap.get(cv::CAP_PROP_FPS)));
EXPECT_EQ(video_header.duration,
static_cast<int>(cap.get(cv::CAP_PROP_FRAME_COUNT) /
cap.get(cv::CAP_PROP_FPS)));
static_cast<int>(std::round(cap.get(cv::CAP_PROP_FRAME_COUNT) /
cap.get(cv::CAP_PROP_FPS))));
}
} // namespace
@@ -0,0 +1,142 @@
// Copyright 2019 The MediaPipe Authors.
//
// Licensed 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 "mediapipe/calculators/video/video_pre_stream_calculator.pb.h"
#include "mediapipe/framework/calculator_framework.h"
#include "mediapipe/framework/formats/image_frame.h"
#include "mediapipe/framework/formats/video_stream_header.h"
namespace mediapipe {
// Sets up VideoHeader based on the 1st ImageFrame and emits it with timestamp
// PreStream. Note that this calculator only fills in format, width, and height,
// i.e. frame_rate and duration will not be filled, unless:
// 1) an existing VideoHeader is provided at PreStream(). In such case, the
// frame_rate and duration, if they exist, will be copied from the existing
// VideoHeader.
// 2) you specify frame_rate and duration through the options. In this case, the
// options will overwrite the existing VideoHeader if it is available.
//
// Example config:
// node {
// calculator: "VideoPreStreamCalculator"
// input_stream: "FRAME:cropped_frames"
// input_stream: "VIDEO_PRESTREAM:original_video_header"
// output_stream: "cropped_frames_video_header"
// }
//
// or
//
// node {
// calculator: "VideoPreStreamCalculator"
// input_stream: "cropped_frames"
// output_stream: "video_header"
// }
class VideoPreStreamCalculator : public CalculatorBase {
public:
static ::mediapipe::Status GetContract(CalculatorContract* cc);
::mediapipe::Status Open(CalculatorContext* cc) override;
::mediapipe::Status Process(CalculatorContext* cc) override;
private:
::mediapipe::Status ProcessWithFrameRateInPreStream(CalculatorContext* cc);
::mediapipe::Status ProcessWithFrameRateInOptions(CalculatorContext* cc);
std::unique_ptr<VideoHeader> header_;
bool frame_rate_in_prestream_ = false;
bool emitted_ = false;
};
REGISTER_CALCULATOR(VideoPreStreamCalculator);
::mediapipe::Status VideoPreStreamCalculator::GetContract(
CalculatorContract* cc) {
if (!cc->Inputs().UsesTags()) {
cc->Inputs().Index(0).Set<ImageFrame>();
} else {
cc->Inputs().Tag("FRAME").Set<ImageFrame>();
cc->Inputs().Tag("VIDEO_PRESTREAM").Set<VideoHeader>();
}
cc->Outputs().Index(0).Set<VideoHeader>();
return ::mediapipe::OkStatus();
}
::mediapipe::Status VideoPreStreamCalculator::Open(CalculatorContext* cc) {
frame_rate_in_prestream_ = cc->Inputs().UsesTags() &&
cc->Inputs().HasTag("FRAME") &&
cc->Inputs().HasTag("VIDEO_PRESTREAM");
header_ = absl::make_unique<VideoHeader>();
return ::mediapipe::OkStatus();
}
::mediapipe::Status VideoPreStreamCalculator::ProcessWithFrameRateInPreStream(
CalculatorContext* cc) {
cc->GetCounter("ProcessWithFrameRateInPreStream")->Increment();
if (cc->InputTimestamp() == Timestamp::PreStream()) {
RET_CHECK(cc->Inputs().Tag("FRAME").IsEmpty());
RET_CHECK(!cc->Inputs().Tag("VIDEO_PRESTREAM").IsEmpty());
*header_ = cc->Inputs().Tag("VIDEO_PRESTREAM").Get<VideoHeader>();
RET_CHECK_NE(header_->frame_rate, 0.0) << "frame rate should be non-zero";
} else {
RET_CHECK(cc->Inputs().Tag("VIDEO_PRESTREAM").IsEmpty())
<< "Packet on VIDEO_PRESTREAM must come in at Timestamp::PreStream().";
RET_CHECK(!cc->Inputs().Tag("FRAME").IsEmpty());
const auto& frame = cc->Inputs().Tag("FRAME").Get<ImageFrame>();
header_->format = frame.Format();
header_->width = frame.Width();
header_->height = frame.Height();
RET_CHECK_NE(header_->frame_rate, 0.0) << "frame rate should be non-zero";
cc->Outputs().Index(0).Add(header_.release(), Timestamp::PreStream());
emitted_ = true;
}
return ::mediapipe::OkStatus();
}
::mediapipe::Status VideoPreStreamCalculator::Process(CalculatorContext* cc) {
cc->GetCounter("Process")->Increment();
if (emitted_) {
return ::mediapipe::OkStatus();
}
if (frame_rate_in_prestream_) {
return ProcessWithFrameRateInPreStream(cc);
} else {
return ProcessWithFrameRateInOptions(cc);
}
}
::mediapipe::Status VideoPreStreamCalculator::ProcessWithFrameRateInOptions(
CalculatorContext* cc) {
cc->GetCounter("ProcessWithFrameRateInOptions")->Increment();
RET_CHECK_NE(cc->InputTimestamp(), Timestamp::PreStream());
const auto& frame = cc->Inputs().Index(0).Get<ImageFrame>();
header_->format = frame.Format();
header_->width = frame.Width();
header_->height = frame.Height();
const auto& options = cc->Options<VideoPreStreamCalculatorOptions>();
if (options.fps().has_value()) {
header_->frame_rate = options.fps().value();
} else if (options.fps().has_ratio()) {
const VideoPreStreamCalculatorOptions::Fps::Rational32& ratio =
options.fps().ratio();
if (ratio.numerator() > 0 && ratio.denominator() > 0) {
header_->frame_rate =
static_cast<double>(ratio.numerator()) / ratio.denominator();
}
}
RET_CHECK_NE(header_->frame_rate, 0.0) << "frame rate should be non-zero";
cc->Outputs().Index(0).Add(header_.release(), Timestamp::PreStream());
emitted_ = true;
return ::mediapipe::OkStatus();
}
} // namespace mediapipe
@@ -0,0 +1,43 @@
// Copyright 2019 The MediaPipe Authors.
//
// Licensed 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.
syntax = "proto2";
package mediapipe;
import "mediapipe/framework/calculator.proto";
message VideoPreStreamCalculatorOptions {
extend CalculatorOptions {
optional VideoPreStreamCalculatorOptions ext = 151386123;
}
// An arbitrary number of frames per second.
// Prefer the StandardFps enum to store industry-standard, safe FPS values.
message Fps {
// The possibly approximated value of the frame rate, in frames per second.
// Unsafe to use in accurate computations because prone to rounding errors.
// For example, the 23.976 FPS value has no exact representation as a
// double.
optional double value = 1;
message Rational32 {
optional int32 numerator = 1;
optional int32 denominator = 2;
}
// The exact value of the frame rate, as a rational number.
optional Rational32 ratio = 2;
}
optional Fps fps = 1;
}
@@ -0,0 +1,186 @@
// Copyright 2019 The MediaPipe Authors.
//
// Licensed 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 "mediapipe/framework/calculator_framework.h"
#include "mediapipe/framework/formats/image_frame.h"
#include "mediapipe/framework/formats/video_stream_header.h"
#include "mediapipe/framework/port/gmock.h"
#include "mediapipe/framework/port/gtest.h"
#include "mediapipe/framework/port/parse_text_proto.h"
#include "mediapipe/framework/port/status.h"
#include "mediapipe/framework/port/status_matchers.h"
namespace mediapipe {
namespace {
TEST(VideoPreStreamCalculatorTest, ProcessesWithFrameRateInOptions) {
auto config = ParseTextProtoOrDie<CalculatorGraphConfig>(R"(
input_stream: "input"
node {
calculator: "VideoPreStreamCalculator"
input_stream: "input"
output_stream: "output"
options {
[mediapipe.VideoPreStreamCalculatorOptions.ext] { fps { value: 3 } }
}
})");
CalculatorGraph graph;
MP_ASSERT_OK(graph.Initialize(config));
auto poller_status = graph.AddOutputStreamPoller("output");
MP_ASSERT_OK(poller_status.status());
OutputStreamPoller& poller = poller_status.ValueOrDie();
MP_ASSERT_OK(graph.StartRun({}));
MP_ASSERT_OK(graph.AddPacketToInputStream(
"input",
Adopt(new ImageFrame(ImageFormat::SRGB, 1, 2)).At(Timestamp(0))));
// It is *not* VideoPreStreamCalculator's job to detect errors in an
// ImageFrame stream. It just waits for the 1st ImageFrame, extracts info for
// VideoHeader, and emits it. Thus, the following is fine.
MP_ASSERT_OK(graph.AddPacketToInputStream(
"input",
Adopt(new ImageFrame(ImageFormat::SRGBA, 3, 4)).At(Timestamp(1))));
MP_ASSERT_OK(graph.CloseInputStream("input"));
Packet packet;
ASSERT_TRUE(poller.Next(&packet));
const auto& video_header = packet.Get<VideoHeader>();
EXPECT_EQ(video_header.format, ImageFormat::SRGB);
EXPECT_EQ(video_header.width, 1);
EXPECT_EQ(video_header.height, 2);
EXPECT_EQ(video_header.frame_rate, 3);
EXPECT_EQ(packet.Timestamp(), Timestamp::PreStream());
ASSERT_FALSE(poller.Next(&packet));
MP_EXPECT_OK(graph.WaitUntilDone());
}
TEST(VideoPreStreamCalculatorTest, ProcessesWithFrameRateInPreStream) {
auto config = ParseTextProtoOrDie<CalculatorGraphConfig>(R"(
input_stream: "frame"
input_stream: "input_header"
node {
calculator: "VideoPreStreamCalculator"
input_stream: "FRAME:frame"
input_stream: "VIDEO_PRESTREAM:input_header"
output_stream: "output_header"
})");
CalculatorGraph graph;
MP_ASSERT_OK(graph.Initialize(config));
auto poller_status = graph.AddOutputStreamPoller("output_header");
MP_ASSERT_OK(poller_status.status());
OutputStreamPoller& poller = poller_status.ValueOrDie();
MP_ASSERT_OK(graph.StartRun({}));
auto input_header = absl::make_unique<VideoHeader>();
input_header->frame_rate = 3.0;
MP_ASSERT_OK(graph.AddPacketToInputStream(
"input_header",
Adopt(input_header.release()).At(Timestamp::PreStream())));
MP_ASSERT_OK(graph.CloseInputStream("input_header"));
MP_ASSERT_OK(graph.AddPacketToInputStream(
"frame",
Adopt(new ImageFrame(ImageFormat::SRGB, 1, 2)).At(Timestamp(0))));
MP_ASSERT_OK(graph.CloseInputStream("frame"));
Packet packet;
ASSERT_TRUE(poller.Next(&packet));
const auto& output_header = packet.Get<VideoHeader>();
EXPECT_EQ(output_header.format, ImageFormat::SRGB);
EXPECT_EQ(output_header.width, 1);
EXPECT_EQ(output_header.height, 2);
EXPECT_EQ(output_header.frame_rate, 3.0);
EXPECT_EQ(packet.Timestamp(), Timestamp::PreStream());
ASSERT_FALSE(poller.Next(&packet));
MP_EXPECT_OK(graph.WaitUntilDone());
}
TEST(VideoPreStreamCalculatorTest, FailsWithoutFrameRateInOptions) {
auto config = ParseTextProtoOrDie<CalculatorGraphConfig>(R"(
input_stream: "frame"
node {
calculator: "VideoPreStreamCalculator"
input_stream: "frame"
output_stream: "output_header"
})");
CalculatorGraph graph;
MP_ASSERT_OK(graph.Initialize(config));
MP_ASSERT_OK(graph.StartRun({}));
MP_ASSERT_OK(graph.AddPacketToInputStream(
"frame",
Adopt(new ImageFrame(ImageFormat::SRGB, 1, 2)).At(Timestamp(0))));
MP_ASSERT_OK(graph.CloseInputStream("frame"));
::mediapipe::Status status = graph.WaitUntilDone();
EXPECT_FALSE(status.ok());
EXPECT_THAT(status.ToString(),
testing::HasSubstr("frame rate should be non-zero"));
}
// Input header missing.
TEST(VideoPreStreamCalculatorTest, FailsWithoutFrameRateInPreStream1) {
auto config = ParseTextProtoOrDie<CalculatorGraphConfig>(R"(
input_stream: "frame"
input_stream: "input_header"
node {
calculator: "VideoPreStreamCalculator"
input_stream: "FRAME:frame"
input_stream: "VIDEO_PRESTREAM:input_header"
output_stream: "output_header"
}
)");
CalculatorGraph graph;
MP_ASSERT_OK(graph.Initialize(config));
MP_ASSERT_OK(graph.StartRun({}));
MP_ASSERT_OK(graph.AddPacketToInputStream(
"frame",
Adopt(new ImageFrame(ImageFormat::SRGB, 1, 2)).At(Timestamp(0))));
MP_ASSERT_OK(graph.CloseInputStream("frame"));
MP_ASSERT_OK(graph.CloseInputStream("input_header"));
::mediapipe::Status status = graph.WaitUntilDone();
EXPECT_FALSE(status.ok());
EXPECT_THAT(status.ToString(),
testing::HasSubstr("frame rate should be non-zero"));
}
// Input header not at prestream (before, with, and after frame data).
TEST(VideoPreStreamCalculatorTest, FailsWithoutFrameRateInPreStream2) {
auto config = ParseTextProtoOrDie<CalculatorGraphConfig>(R"(
input_stream: "frame"
input_stream: "input_header"
node {
calculator: "VideoPreStreamCalculator"
input_stream: "FRAME:frame"
input_stream: "VIDEO_PRESTREAM:input_header"
output_stream: "output_header"
}
)");
for (int64 timestamp = -1; timestamp < 2; ++timestamp) {
CalculatorGraph graph;
MP_ASSERT_OK(graph.Initialize(config));
MP_ASSERT_OK(graph.StartRun({}));
auto input_header = absl::make_unique<VideoHeader>();
input_header->frame_rate = 3.0;
MP_ASSERT_OK(graph.AddPacketToInputStream(
"input_header",
Adopt(input_header.release()).At(Timestamp(timestamp))));
MP_ASSERT_OK(graph.CloseInputStream("input_header"));
MP_ASSERT_OK(graph.AddPacketToInputStream(
"frame",
Adopt(new ImageFrame(ImageFormat::SRGB, 1, 2)).At(Timestamp(0))));
MP_ASSERT_OK(graph.CloseInputStream("frame"));
::mediapipe::Status status = graph.WaitUntilDone();
EXPECT_FALSE(status.ok());
}
}
} // namespace
} // namespace mediapipe