File: sync_decoder_test.cpp

package info (click to toggle)
pytorch-vision 0.21.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 20,228 kB
  • sloc: python: 65,904; cpp: 11,406; ansic: 2,459; java: 550; sh: 265; xml: 79; objc: 56; makefile: 33
file content (417 lines) | stat: -rw-r--r-- 12,710 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#include <c10/util/Logging.h>
#include <dirent.h>
#include <gtest/gtest.h>
#include "memory_buffer.h"
#include "sync_decoder.h"
#include "util.h"

using namespace ffmpeg;

namespace {
struct VideoFileStats {
  std::string name;
  size_t durationPts{0};
  int num{0};
  int den{0};
  int fps{0};
};

void gotAllTestFiles(
    const std::string& folder,
    std::vector<VideoFileStats>* stats) {
  DIR* d = opendir(folder.c_str());
  CHECK(d);
  struct dirent* dir;
  while ((dir = readdir(d))) {
    if (dir->d_type != DT_DIR && 0 != strcmp(dir->d_name, "README")) {
      VideoFileStats item;
      item.name = folder + '/' + dir->d_name;
      LOG(INFO) << "Found video file: " << item.name;
      stats->push_back(std::move(item));
    }
  }
  closedir(d);
}

void gotFilesStats(std::vector<VideoFileStats>& stats) {
  DecoderParameters params;
  params.timeoutMs = 10000;
  params.startOffset = 1000000;
  params.seekAccuracy = 100000;
  params.formats = {MediaFormat(0)};
  params.headerOnly = true;
  params.preventStaleness = false;
  size_t avgProvUs = 0;
  const size_t rounds = 100;
  for (auto& item : stats) {
    LOG(INFO) << "Decoding video file in memory: " << item.name;
    FILE* f = fopen(item.name.c_str(), "rb");
    CHECK(f != nullptr);
    fseek(f, 0, SEEK_END);
    std::vector<uint8_t> buffer(ftell(f));
    rewind(f);
    size_t s = fread(buffer.data(), 1, buffer.size(), f);
    TORCH_CHECK_EQ(buffer.size(), s);
    fclose(f);

    for (size_t i = 0; i < rounds; ++i) {
      SyncDecoder decoder;
      std::vector<DecoderMetadata> metadata;
      const auto now = std::chrono::steady_clock::now();
      CHECK(decoder.init(
          params,
          MemoryBuffer::getCallback(buffer.data(), buffer.size()),
          &metadata));
      const auto then = std::chrono::steady_clock::now();
      decoder.shutdown();
      avgProvUs +=
          std::chrono::duration_cast<std::chrono::microseconds>(then - now)
              .count();
      TORCH_CHECK_EQ(metadata.size(), 1);
      item.num = metadata[0].num;
      item.den = metadata[0].den;
      item.fps = metadata[0].fps;
      item.durationPts =
          av_rescale_q(metadata[0].duration, AV_TIME_BASE_Q, {1, item.fps});
    }
  }
  LOG(INFO) << "Probing (us) " << avgProvUs / stats.size() / rounds;
}

size_t measurePerformanceUs(
    const std::vector<VideoFileStats>& stats,
    size_t rounds,
    size_t num,
    size_t stride) {
  size_t avgClipDecodingUs = 0;
  std::srand(time(nullptr));
  for (const auto& item : stats) {
    FILE* f = fopen(item.name.c_str(), "rb");
    CHECK(f != nullptr);
    fseek(f, 0, SEEK_END);
    std::vector<uint8_t> buffer(ftell(f));
    rewind(f);
    size_t s = fread(buffer.data(), 1, buffer.size(), f);
    TORCH_CHECK_EQ(buffer.size(), s);
    fclose(f);

    for (size_t i = 0; i < rounds; ++i) {
      // randomy select clip
      size_t rOffset = std::rand();
      size_t fOffset = rOffset % item.durationPts;
      size_t clipFrames = num + (num - 1) * stride;
      if (fOffset + clipFrames > item.durationPts) {
        fOffset = item.durationPts - clipFrames;
      }

      DecoderParameters params;
      params.timeoutMs = 10000;
      params.startOffset = 1000000;
      params.seekAccuracy = 100000;
      params.preventStaleness = false;

      for (size_t n = 0; n < num; ++n) {
        std::list<DecoderOutputMessage> msgs;

        params.startOffset =
            av_rescale_q(fOffset, {1, item.fps}, AV_TIME_BASE_Q);
        params.endOffset = params.startOffset + 100;

        auto now = std::chrono::steady_clock::now();
        SyncDecoder decoder;
        CHECK(decoder.init(
            params,
            MemoryBuffer::getCallback(buffer.data(), buffer.size()),
            nullptr));
        DecoderOutputMessage out;
        while (0 == decoder.decode(&out, params.timeoutMs)) {
          msgs.push_back(std::move(out));
        }

        decoder.shutdown();

        const auto then = std::chrono::steady_clock::now();

        fOffset += 1 + stride;

        avgClipDecodingUs +=
            std::chrono::duration_cast<std::chrono::microseconds>(then - now)
                .count();
      }
    }
  }

  return avgClipDecodingUs / rounds / num / stats.size();
}

void runDecoder(SyncDecoder& decoder) {
  DecoderOutputMessage out;
  size_t audioFrames = 0, videoFrames = 0, totalBytes = 0;
  while (0 == decoder.decode(&out, 10000)) {
    if (out.header.format.type == TYPE_AUDIO) {
      ++audioFrames;
    } else if (out.header.format.type == TYPE_VIDEO) {
      ++videoFrames;
    } else if (out.header.format.type == TYPE_SUBTITLE && out.payload) {
      // deserialize
      LOG(INFO) << "Deserializing subtitle";
      AVSubtitle sub;
      memset(&sub, 0, sizeof(sub));
      EXPECT_TRUE(Util::deserialize(*out.payload, &sub));
      LOG(INFO) << "Found subtitles"
                << ", num rects: " << sub.num_rects;
      for (int i = 0; i < sub.num_rects; ++i) {
        std::string text = "picture";
        if (sub.rects[i]->type == SUBTITLE_TEXT) {
          text = sub.rects[i]->text;
        } else if (sub.rects[i]->type == SUBTITLE_ASS) {
          text = sub.rects[i]->ass;
        }

        LOG(INFO) << "Rect num: " << i << ", type:" << sub.rects[i]->type
                  << ", text: " << text;
      }

      avsubtitle_free(&sub);
    }
    if (out.payload) {
      totalBytes += out.payload->length();
    }
  }
  LOG(INFO) << "Decoded audio frames: " << audioFrames
            << ", video frames: " << videoFrames
            << ", total bytes: " << totalBytes;
}
} // namespace

TEST(SyncDecoder, TestSyncDecoderPerformance) {
  // Measure the average time of decoding per clip
  // 1. list of the videos in testing directory
  // 2. for each video got number of frames with timestamps
  // 3. randomly select frame offset
  // 4. adjust offset for number frames and strides,
  //    if it's out out upper boundary
  // 5. repeat multiple times, measuring and accumulating decoding time
  //    per clip.
  /*
  1) 4 x 2
  2) 8 x 8
  3) 16 x 8
  4) 32 x 4
  */
  const std::string kFolder = "pytorch/vision/test/assets/videos";
  std::vector<VideoFileStats> stats;
  gotAllTestFiles(kFolder, &stats);
  gotFilesStats(stats);

  const size_t kRounds = 10;

  auto new4x2 = measurePerformanceUs(stats, kRounds, 4, 2);
  auto new8x8 = measurePerformanceUs(stats, kRounds, 8, 8);
  auto new16x8 = measurePerformanceUs(stats, kRounds, 16, 8);
  auto new32x4 = measurePerformanceUs(stats, kRounds, 32, 4);
  LOG(INFO) << "Clip decoding (us)"
            << ", new(4x2): " << new4x2 << ", new(8x8): " << new8x8
            << ", new(16x8): " << new16x8 << ", new(32x4): " << new32x4;
}

TEST(SyncDecoder, Test) {
  SyncDecoder decoder;
  DecoderParameters params;
  params.timeoutMs = 10000;
  params.startOffset = 1000000;
  params.seekAccuracy = 100000;
  params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};
  params.uri = "pytorch/vision/test/assets/videos/R6llTwEh07w.mp4";
  CHECK(decoder.init(params, nullptr, nullptr));
  runDecoder(decoder);
  decoder.shutdown();
}

TEST(SyncDecoder, TestSubtitles) {
  SyncDecoder decoder;
  DecoderParameters params;
  params.timeoutMs = 10000;
  params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};
  params.uri = "vue/synergy/data/robotsub.mp4";
  CHECK(decoder.init(params, nullptr, nullptr));
  runDecoder(decoder);
  decoder.shutdown();
}

TEST(SyncDecoder, TestHeadersOnly) {
  SyncDecoder decoder;
  DecoderParameters params;
  params.timeoutMs = 10000;
  params.startOffset = 1000000;
  params.seekAccuracy = 100000;
  params.headerOnly = true;
  params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};

  params.uri = "pytorch/vision/test/assets/videos/R6llTwEh07w.mp4";
  CHECK(decoder.init(params, nullptr, nullptr));
  runDecoder(decoder);
  decoder.shutdown();

  params.uri = "pytorch/vision/test/assets/videos/SOX5yA1l24A.mp4";
  CHECK(decoder.init(params, nullptr, nullptr));
  runDecoder(decoder);
  decoder.shutdown();

  params.uri = "pytorch/vision/test/assets/videos/WUzgd7C1pWA.mp4";
  CHECK(decoder.init(params, nullptr, nullptr));
  runDecoder(decoder);
  decoder.shutdown();
}

TEST(SyncDecoder, TestHeadersOnlyDownSampling) {
  SyncDecoder decoder;
  DecoderParameters params;
  params.timeoutMs = 10000;
  params.startOffset = 1000000;
  params.seekAccuracy = 100000;
  params.headerOnly = true;
  MediaFormat format;
  format.type = TYPE_AUDIO;
  format.format.audio.samples = 8000;
  params.formats.insert(format);

  format.type = TYPE_VIDEO;
  format.format.video.width = 224;
  format.format.video.height = 224;
  params.formats.insert(format);

  params.uri = "pytorch/vision/test/assets/videos/R6llTwEh07w.mp4";
  CHECK(decoder.init(params, nullptr, nullptr));
  runDecoder(decoder);
  decoder.shutdown();

  params.uri = "pytorch/vision/test/assets/videos/SOX5yA1l24A.mp4";
  CHECK(decoder.init(params, nullptr, nullptr));
  runDecoder(decoder);
  decoder.shutdown();

  params.uri = "pytorch/vision/test/assets/videos/WUzgd7C1pWA.mp4";
  CHECK(decoder.init(params, nullptr, nullptr));
  runDecoder(decoder);
  decoder.shutdown();
}

TEST(SyncDecoder, TestInitOnlyNoShutdown) {
  SyncDecoder decoder;
  DecoderParameters params;
  params.timeoutMs = 10000;
  params.startOffset = 1000000;
  params.seekAccuracy = 100000;
  params.headerOnly = false;
  params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};
  params.uri = "pytorch/vision/test/assets/videos/R6llTwEh07w.mp4";
  std::vector<DecoderMetadata> metadata;
  CHECK(decoder.init(params, nullptr, &metadata));
}

TEST(SyncDecoder, TestMemoryBuffer) {
  SyncDecoder decoder;
  DecoderParameters params;
  params.timeoutMs = 10000;
  params.startOffset = 1000000;
  params.endOffset = 9000000;
  params.seekAccuracy = 10000;
  params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};

  FILE* f = fopen(
      "pytorch/vision/test/assets/videos/RATRACE_wave_f_nm_np1_fr_goo_37.avi",
      "rb");
  CHECK(f != nullptr);
  fseek(f, 0, SEEK_END);
  std::vector<uint8_t> buffer(ftell(f));
  rewind(f);
  size_t s = fread(buffer.data(), 1, buffer.size(), f);
  TORCH_CHECK_EQ(buffer.size(), s);
  fclose(f);
  CHECK(decoder.init(
      params,
      MemoryBuffer::getCallback(buffer.data(), buffer.size()),
      nullptr));
  LOG(INFO) << "Decoding from memory bytes: " << buffer.size();
  runDecoder(decoder);
  decoder.shutdown();
}

TEST(SyncDecoder, TestMemoryBufferNoSeekableWithFullRead) {
  SyncDecoder decoder;
  DecoderParameters params;
  params.timeoutMs = 10000;
  params.startOffset = 1000000;
  params.endOffset = 9000000;
  params.seekAccuracy = 10000;
  params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};

  FILE* f = fopen("pytorch/vision/test/assets/videos/R6llTwEh07w.mp4", "rb");
  CHECK(f != nullptr);
  fseek(f, 0, SEEK_END);
  std::vector<uint8_t> buffer(ftell(f));
  rewind(f);
  size_t s = fread(buffer.data(), 1, buffer.size(), f);
  TORCH_CHECK_EQ(buffer.size(), s);
  fclose(f);

  params.maxSeekableBytes = buffer.size() + 1;
  MemoryBuffer object(buffer.data(), buffer.size());
  CHECK(decoder.init(
      params,
      [object](uint8_t* out, int size, int whence, uint64_t timeoutMs) mutable
          -> int {
        if (out) { // see defs.h file
          // read mode
          return object.read(out, size);
        }
        // seek mode
        if (!timeoutMs) {
          // seek capability, yes - no
          return -1;
        }
        return object.seek(size, whence);
      },
      nullptr));
  runDecoder(decoder);
  decoder.shutdown();
}

TEST(SyncDecoder, TestMemoryBufferNoSeekableWithPartialRead) {
  SyncDecoder decoder;
  DecoderParameters params;
  params.timeoutMs = 10000;
  params.startOffset = 1000000;
  params.endOffset = 9000000;
  params.seekAccuracy = 10000;
  params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};

  FILE* f = fopen("pytorch/vision/test/assets/videos/R6llTwEh07w.mp4", "rb");
  CHECK(f != nullptr);
  fseek(f, 0, SEEK_END);
  std::vector<uint8_t> buffer(ftell(f));
  rewind(f);
  size_t s = fread(buffer.data(), 1, buffer.size(), f);
  TORCH_CHECK_EQ(buffer.size(), s);
  fclose(f);

  params.maxSeekableBytes = buffer.size() / 2;
  MemoryBuffer object(buffer.data(), buffer.size());
  CHECK(!decoder.init(
      params,
      [object](uint8_t* out, int size, int whence, uint64_t timeoutMs) mutable
          -> int {
        if (out) { // see defs.h file
          // read mode
          return object.read(out, size);
        }
        // seek mode
        if (!timeoutMs) {
          // seek capability, yes - no
          return -1;
        }
        return object.seek(size, whence);
      },
      nullptr));
}