test_video_reader.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  1. import collections
  2. import math
  3. import os
  4. from fractions import Fraction
  5. import numpy as np
  6. import pytest
  7. import torch
  8. import torchvision.io as io
  9. from common_utils import assert_equal
  10. from numpy.random import randint
  11. from pytest import approx
  12. from torchvision import set_video_backend
  13. from torchvision.io import _HAS_VIDEO_OPT
  14. try:
  15. import av
  16. # Do a version test too
  17. io.video._check_av_available()
  18. except ImportError:
  19. av = None
  20. VIDEO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets", "videos")
  21. CheckerConfig = [
  22. "duration",
  23. "video_fps",
  24. "audio_sample_rate",
  25. # We find for some videos (e.g. HMDB51 videos), the decoded audio frames and pts are
  26. # slightly different between TorchVision decoder and PyAv decoder. So omit it during check
  27. "check_aframes",
  28. "check_aframe_pts",
  29. ]
  30. GroundTruth = collections.namedtuple("GroundTruth", " ".join(CheckerConfig))
  31. all_check_config = GroundTruth(
  32. duration=0,
  33. video_fps=0,
  34. audio_sample_rate=0,
  35. check_aframes=True,
  36. check_aframe_pts=True,
  37. )
  38. test_videos = {
  39. "RATRACE_wave_f_nm_np1_fr_goo_37.avi": GroundTruth(
  40. duration=2.0,
  41. video_fps=30.0,
  42. audio_sample_rate=None,
  43. check_aframes=True,
  44. check_aframe_pts=True,
  45. ),
  46. "SchoolRulesHowTheyHelpUs_wave_f_nm_np1_ba_med_0.avi": GroundTruth(
  47. duration=2.0,
  48. video_fps=30.0,
  49. audio_sample_rate=None,
  50. check_aframes=True,
  51. check_aframe_pts=True,
  52. ),
  53. "TrumanShow_wave_f_nm_np1_fr_med_26.avi": GroundTruth(
  54. duration=2.0,
  55. video_fps=30.0,
  56. audio_sample_rate=None,
  57. check_aframes=True,
  58. check_aframe_pts=True,
  59. ),
  60. "v_SoccerJuggling_g23_c01.avi": GroundTruth(
  61. duration=8.0,
  62. video_fps=29.97,
  63. audio_sample_rate=None,
  64. check_aframes=True,
  65. check_aframe_pts=True,
  66. ),
  67. "v_SoccerJuggling_g24_c01.avi": GroundTruth(
  68. duration=8.0,
  69. video_fps=29.97,
  70. audio_sample_rate=None,
  71. check_aframes=True,
  72. check_aframe_pts=True,
  73. ),
  74. "R6llTwEh07w.mp4": GroundTruth(
  75. duration=10.0,
  76. video_fps=30.0,
  77. audio_sample_rate=44100,
  78. # PyAv miss one audio frame at the beginning (pts=0)
  79. check_aframes=False,
  80. check_aframe_pts=False,
  81. ),
  82. "SOX5yA1l24A.mp4": GroundTruth(
  83. duration=11.0,
  84. video_fps=29.97,
  85. audio_sample_rate=48000,
  86. # PyAv miss one audio frame at the beginning (pts=0)
  87. check_aframes=False,
  88. check_aframe_pts=False,
  89. ),
  90. "WUzgd7C1pWA.mp4": GroundTruth(
  91. duration=11.0,
  92. video_fps=29.97,
  93. audio_sample_rate=48000,
  94. # PyAv miss one audio frame at the beginning (pts=0)
  95. check_aframes=False,
  96. check_aframe_pts=False,
  97. ),
  98. }
  99. DecoderResult = collections.namedtuple("DecoderResult", "vframes vframe_pts vtimebase aframes aframe_pts atimebase")
  100. # av_seek_frame is imprecise so seek to a timestamp earlier by a margin
  101. # The unit of margin is second
  102. SEEK_FRAME_MARGIN = 0.25
  103. def _read_from_stream(container, start_pts, end_pts, stream, stream_name, buffer_size=4):
  104. """
  105. Args:
  106. container: pyav container
  107. start_pts/end_pts: the starting/ending Presentation TimeStamp where
  108. frames are read
  109. stream: pyav stream
  110. stream_name: a dictionary of streams. For example, {"video": 0} means
  111. video stream at stream index 0
  112. buffer_size: pts of frames decoded by PyAv is not guaranteed to be in
  113. ascending order. We need to decode more frames even when we meet end
  114. pts
  115. """
  116. # seeking in the stream is imprecise. Thus, seek to an earlier PTS by a margin
  117. margin = 1
  118. seek_offset = max(start_pts - margin, 0)
  119. container.seek(seek_offset, any_frame=False, backward=True, stream=stream)
  120. frames = {}
  121. buffer_count = 0
  122. for frame in container.decode(**stream_name):
  123. if frame.pts < start_pts:
  124. continue
  125. if frame.pts <= end_pts:
  126. frames[frame.pts] = frame
  127. else:
  128. buffer_count += 1
  129. if buffer_count >= buffer_size:
  130. break
  131. result = [frames[pts] for pts in sorted(frames)]
  132. return result
  133. def _get_timebase_by_av_module(full_path):
  134. container = av.open(full_path)
  135. video_time_base = container.streams.video[0].time_base
  136. if container.streams.audio:
  137. audio_time_base = container.streams.audio[0].time_base
  138. else:
  139. audio_time_base = None
  140. return video_time_base, audio_time_base
  141. def _fraction_to_tensor(fraction):
  142. ret = torch.zeros([2], dtype=torch.int32)
  143. ret[0] = fraction.numerator
  144. ret[1] = fraction.denominator
  145. return ret
  146. def _decode_frames_by_av_module(
  147. full_path,
  148. video_start_pts=0,
  149. video_end_pts=None,
  150. audio_start_pts=0,
  151. audio_end_pts=None,
  152. ):
  153. """
  154. Use PyAv to decode video frames. This provides a reference for our decoder
  155. to compare the decoding results.
  156. Input arguments:
  157. full_path: video file path
  158. video_start_pts/video_end_pts: the starting/ending Presentation TimeStamp where
  159. frames are read
  160. """
  161. if video_end_pts is None:
  162. video_end_pts = float("inf")
  163. if audio_end_pts is None:
  164. audio_end_pts = float("inf")
  165. container = av.open(full_path)
  166. video_frames = []
  167. vtimebase = torch.zeros([0], dtype=torch.int32)
  168. if container.streams.video:
  169. video_frames = _read_from_stream(
  170. container,
  171. video_start_pts,
  172. video_end_pts,
  173. container.streams.video[0],
  174. {"video": 0},
  175. )
  176. # container.streams.video[0].average_rate is not a reliable estimator of
  177. # frame rate. It can be wrong for certain codec, such as VP80
  178. # So we do not return video fps here
  179. vtimebase = _fraction_to_tensor(container.streams.video[0].time_base)
  180. audio_frames = []
  181. atimebase = torch.zeros([0], dtype=torch.int32)
  182. if container.streams.audio:
  183. audio_frames = _read_from_stream(
  184. container,
  185. audio_start_pts,
  186. audio_end_pts,
  187. container.streams.audio[0],
  188. {"audio": 0},
  189. )
  190. atimebase = _fraction_to_tensor(container.streams.audio[0].time_base)
  191. container.close()
  192. vframes = [frame.to_rgb().to_ndarray() for frame in video_frames]
  193. vframes = torch.as_tensor(np.stack(vframes))
  194. vframe_pts = torch.tensor([frame.pts for frame in video_frames], dtype=torch.int64)
  195. aframes = [frame.to_ndarray() for frame in audio_frames]
  196. if aframes:
  197. aframes = np.transpose(np.concatenate(aframes, axis=1))
  198. aframes = torch.as_tensor(aframes)
  199. else:
  200. aframes = torch.empty((1, 0), dtype=torch.float32)
  201. aframe_pts = torch.tensor([audio_frame.pts for audio_frame in audio_frames], dtype=torch.int64)
  202. return DecoderResult(
  203. vframes=vframes,
  204. vframe_pts=vframe_pts,
  205. vtimebase=vtimebase,
  206. aframes=aframes,
  207. aframe_pts=aframe_pts,
  208. atimebase=atimebase,
  209. )
  210. def _pts_convert(pts, timebase_from, timebase_to, round_func=math.floor):
  211. """convert pts between different time bases
  212. Args:
  213. pts: presentation timestamp, float
  214. timebase_from: original timebase. Fraction
  215. timebase_to: new timebase. Fraction
  216. round_func: rounding function.
  217. """
  218. new_pts = Fraction(pts, 1) * timebase_from / timebase_to
  219. return int(round_func(new_pts))
  220. def _get_video_tensor(video_dir, video_file):
  221. """open a video file, and represent the video data by a PT tensor"""
  222. full_path = os.path.join(video_dir, video_file)
  223. assert os.path.exists(full_path), "File not found: %s" % full_path
  224. with open(full_path, "rb") as fp:
  225. video_tensor = torch.frombuffer(fp.read(), dtype=torch.uint8)
  226. return full_path, video_tensor
  227. @pytest.mark.skipif(av is None, reason="PyAV unavailable")
  228. @pytest.mark.skipif(_HAS_VIDEO_OPT is False, reason="Didn't compile with ffmpeg")
  229. class TestVideoReader:
  230. def check_separate_decoding_result(self, tv_result, config):
  231. """check the decoding results from TorchVision decoder"""
  232. (
  233. vframes,
  234. vframe_pts,
  235. vtimebase,
  236. vfps,
  237. vduration,
  238. aframes,
  239. aframe_pts,
  240. atimebase,
  241. asample_rate,
  242. aduration,
  243. ) = tv_result
  244. video_duration = vduration.item() * Fraction(vtimebase[0].item(), vtimebase[1].item())
  245. assert video_duration == approx(config.duration, abs=0.5)
  246. assert vfps.item() == approx(config.video_fps, abs=0.5)
  247. if asample_rate.numel() > 0:
  248. assert asample_rate.item() == config.audio_sample_rate
  249. audio_duration = aduration.item() * Fraction(atimebase[0].item(), atimebase[1].item())
  250. assert audio_duration == approx(config.duration, abs=0.5)
  251. # check if pts of video frames are sorted in ascending order
  252. for i in range(len(vframe_pts) - 1):
  253. assert vframe_pts[i] < vframe_pts[i + 1]
  254. if len(aframe_pts) > 1:
  255. # check if pts of audio frames are sorted in ascending order
  256. for i in range(len(aframe_pts) - 1):
  257. assert aframe_pts[i] < aframe_pts[i + 1]
  258. def check_probe_result(self, result, config):
  259. vtimebase, vfps, vduration, atimebase, asample_rate, aduration = result
  260. video_duration = vduration.item() * Fraction(vtimebase[0].item(), vtimebase[1].item())
  261. assert video_duration == approx(config.duration, abs=0.5)
  262. assert vfps.item() == approx(config.video_fps, abs=0.5)
  263. if asample_rate.numel() > 0:
  264. assert asample_rate.item() == config.audio_sample_rate
  265. audio_duration = aduration.item() * Fraction(atimebase[0].item(), atimebase[1].item())
  266. assert audio_duration == approx(config.duration, abs=0.5)
  267. def check_meta_result(self, result, config):
  268. assert result.video_duration == approx(config.duration, abs=0.5)
  269. assert result.video_fps == approx(config.video_fps, abs=0.5)
  270. if result.has_audio > 0:
  271. assert result.audio_sample_rate == config.audio_sample_rate
  272. assert result.audio_duration == approx(config.duration, abs=0.5)
  273. def compare_decoding_result(self, tv_result, ref_result, config=all_check_config):
  274. """
  275. Compare decoding results from two sources.
  276. Args:
  277. tv_result: decoding results from TorchVision decoder
  278. ref_result: reference decoding results which can be from either PyAv
  279. decoder or TorchVision decoder with getPtsOnly = 1
  280. config: config of decoding results checker
  281. """
  282. (
  283. vframes,
  284. vframe_pts,
  285. vtimebase,
  286. _vfps,
  287. _vduration,
  288. aframes,
  289. aframe_pts,
  290. atimebase,
  291. _asample_rate,
  292. _aduration,
  293. ) = tv_result
  294. if isinstance(ref_result, list):
  295. # the ref_result is from new video_reader decoder
  296. ref_result = DecoderResult(
  297. vframes=ref_result[0],
  298. vframe_pts=ref_result[1],
  299. vtimebase=ref_result[2],
  300. aframes=ref_result[5],
  301. aframe_pts=ref_result[6],
  302. atimebase=ref_result[7],
  303. )
  304. if vframes.numel() > 0 and ref_result.vframes.numel() > 0:
  305. mean_delta = torch.mean(torch.abs(vframes.float() - ref_result.vframes.float()))
  306. assert mean_delta == approx(0.0, abs=8.0)
  307. mean_delta = torch.mean(torch.abs(vframe_pts.float() - ref_result.vframe_pts.float()))
  308. assert mean_delta == approx(0.0, abs=1.0)
  309. assert_equal(vtimebase, ref_result.vtimebase)
  310. if config.check_aframes and aframes.numel() > 0 and ref_result.aframes.numel() > 0:
  311. """Audio stream is available and audio frame is required to return
  312. from decoder"""
  313. assert_equal(aframes, ref_result.aframes)
  314. if config.check_aframe_pts and aframe_pts.numel() > 0 and ref_result.aframe_pts.numel() > 0:
  315. """Audio stream is available"""
  316. assert_equal(aframe_pts, ref_result.aframe_pts)
  317. assert_equal(atimebase, ref_result.atimebase)
  318. @pytest.mark.parametrize("test_video", test_videos.keys())
  319. def test_stress_test_read_video_from_file(self, test_video):
  320. pytest.skip(
  321. "This stress test will iteratively decode the same set of videos."
  322. "It helps to detect memory leak but it takes lots of time to run."
  323. "By default, it is disabled"
  324. )
  325. num_iter = 10000
  326. # video related
  327. width, height, min_dimension, max_dimension = 0, 0, 0, 0
  328. video_start_pts, video_end_pts = 0, -1
  329. video_timebase_num, video_timebase_den = 0, 1
  330. # audio related
  331. samples, channels = 0, 0
  332. audio_start_pts, audio_end_pts = 0, -1
  333. audio_timebase_num, audio_timebase_den = 0, 1
  334. for _i in range(num_iter):
  335. full_path = os.path.join(VIDEO_DIR, test_video)
  336. # pass 1: decode all frames using new decoder
  337. torch.ops.video_reader.read_video_from_file(
  338. full_path,
  339. SEEK_FRAME_MARGIN,
  340. 0, # getPtsOnly
  341. 1, # readVideoStream
  342. width,
  343. height,
  344. min_dimension,
  345. max_dimension,
  346. video_start_pts,
  347. video_end_pts,
  348. video_timebase_num,
  349. video_timebase_den,
  350. 1, # readAudioStream
  351. samples,
  352. channels,
  353. audio_start_pts,
  354. audio_end_pts,
  355. audio_timebase_num,
  356. audio_timebase_den,
  357. )
  358. @pytest.mark.parametrize("test_video,config", test_videos.items())
  359. def test_read_video_from_file(self, test_video, config):
  360. """
  361. Test the case when decoder starts with a video file to decode frames.
  362. """
  363. # video related
  364. width, height, min_dimension, max_dimension = 0, 0, 0, 0
  365. video_start_pts, video_end_pts = 0, -1
  366. video_timebase_num, video_timebase_den = 0, 1
  367. # audio related
  368. samples, channels = 0, 0
  369. audio_start_pts, audio_end_pts = 0, -1
  370. audio_timebase_num, audio_timebase_den = 0, 1
  371. full_path = os.path.join(VIDEO_DIR, test_video)
  372. # pass 1: decode all frames using new decoder
  373. tv_result = torch.ops.video_reader.read_video_from_file(
  374. full_path,
  375. SEEK_FRAME_MARGIN,
  376. 0, # getPtsOnly
  377. 1, # readVideoStream
  378. width,
  379. height,
  380. min_dimension,
  381. max_dimension,
  382. video_start_pts,
  383. video_end_pts,
  384. video_timebase_num,
  385. video_timebase_den,
  386. 1, # readAudioStream
  387. samples,
  388. channels,
  389. audio_start_pts,
  390. audio_end_pts,
  391. audio_timebase_num,
  392. audio_timebase_den,
  393. )
  394. # pass 2: decode all frames using av
  395. pyav_result = _decode_frames_by_av_module(full_path)
  396. # check results from TorchVision decoder
  397. self.check_separate_decoding_result(tv_result, config)
  398. # compare decoding results
  399. self.compare_decoding_result(tv_result, pyav_result, config)
  400. @pytest.mark.parametrize("test_video,config", test_videos.items())
  401. @pytest.mark.parametrize("read_video_stream,read_audio_stream", [(1, 0), (0, 1)])
  402. def test_read_video_from_file_read_single_stream_only(
  403. self, test_video, config, read_video_stream, read_audio_stream
  404. ):
  405. """
  406. Test the case when decoder starts with a video file to decode frames, and
  407. only reads video stream and ignores audio stream
  408. """
  409. # video related
  410. width, height, min_dimension, max_dimension = 0, 0, 0, 0
  411. video_start_pts, video_end_pts = 0, -1
  412. video_timebase_num, video_timebase_den = 0, 1
  413. # audio related
  414. samples, channels = 0, 0
  415. audio_start_pts, audio_end_pts = 0, -1
  416. audio_timebase_num, audio_timebase_den = 0, 1
  417. full_path = os.path.join(VIDEO_DIR, test_video)
  418. # decode all frames using new decoder
  419. tv_result = torch.ops.video_reader.read_video_from_file(
  420. full_path,
  421. SEEK_FRAME_MARGIN,
  422. 0, # getPtsOnly
  423. read_video_stream,
  424. width,
  425. height,
  426. min_dimension,
  427. max_dimension,
  428. video_start_pts,
  429. video_end_pts,
  430. video_timebase_num,
  431. video_timebase_den,
  432. read_audio_stream,
  433. samples,
  434. channels,
  435. audio_start_pts,
  436. audio_end_pts,
  437. audio_timebase_num,
  438. audio_timebase_den,
  439. )
  440. (
  441. vframes,
  442. vframe_pts,
  443. vtimebase,
  444. vfps,
  445. vduration,
  446. aframes,
  447. aframe_pts,
  448. atimebase,
  449. asample_rate,
  450. aduration,
  451. ) = tv_result
  452. assert (vframes.numel() > 0) is bool(read_video_stream)
  453. assert (vframe_pts.numel() > 0) is bool(read_video_stream)
  454. assert (vtimebase.numel() > 0) is bool(read_video_stream)
  455. assert (vfps.numel() > 0) is bool(read_video_stream)
  456. expect_audio_data = read_audio_stream == 1 and config.audio_sample_rate is not None
  457. assert (aframes.numel() > 0) is bool(expect_audio_data)
  458. assert (aframe_pts.numel() > 0) is bool(expect_audio_data)
  459. assert (atimebase.numel() > 0) is bool(expect_audio_data)
  460. assert (asample_rate.numel() > 0) is bool(expect_audio_data)
  461. @pytest.mark.parametrize("test_video", test_videos.keys())
  462. def test_read_video_from_file_rescale_min_dimension(self, test_video):
  463. """
  464. Test the case when decoder starts with a video file to decode frames, and
  465. video min dimension between height and width is set.
  466. """
  467. # video related
  468. width, height, min_dimension, max_dimension = 0, 0, 128, 0
  469. video_start_pts, video_end_pts = 0, -1
  470. video_timebase_num, video_timebase_den = 0, 1
  471. # audio related
  472. samples, channels = 0, 0
  473. audio_start_pts, audio_end_pts = 0, -1
  474. audio_timebase_num, audio_timebase_den = 0, 1
  475. full_path = os.path.join(VIDEO_DIR, test_video)
  476. tv_result = torch.ops.video_reader.read_video_from_file(
  477. full_path,
  478. SEEK_FRAME_MARGIN,
  479. 0, # getPtsOnly
  480. 1, # readVideoStream
  481. width,
  482. height,
  483. min_dimension,
  484. max_dimension,
  485. video_start_pts,
  486. video_end_pts,
  487. video_timebase_num,
  488. video_timebase_den,
  489. 1, # readAudioStream
  490. samples,
  491. channels,
  492. audio_start_pts,
  493. audio_end_pts,
  494. audio_timebase_num,
  495. audio_timebase_den,
  496. )
  497. assert min_dimension == min(tv_result[0].size(1), tv_result[0].size(2))
  498. @pytest.mark.parametrize("test_video", test_videos.keys())
  499. def test_read_video_from_file_rescale_max_dimension(self, test_video):
  500. """
  501. Test the case when decoder starts with a video file to decode frames, and
  502. video min dimension between height and width is set.
  503. """
  504. # video related
  505. width, height, min_dimension, max_dimension = 0, 0, 0, 85
  506. video_start_pts, video_end_pts = 0, -1
  507. video_timebase_num, video_timebase_den = 0, 1
  508. # audio related
  509. samples, channels = 0, 0
  510. audio_start_pts, audio_end_pts = 0, -1
  511. audio_timebase_num, audio_timebase_den = 0, 1
  512. full_path = os.path.join(VIDEO_DIR, test_video)
  513. tv_result = torch.ops.video_reader.read_video_from_file(
  514. full_path,
  515. SEEK_FRAME_MARGIN,
  516. 0, # getPtsOnly
  517. 1, # readVideoStream
  518. width,
  519. height,
  520. min_dimension,
  521. max_dimension,
  522. video_start_pts,
  523. video_end_pts,
  524. video_timebase_num,
  525. video_timebase_den,
  526. 1, # readAudioStream
  527. samples,
  528. channels,
  529. audio_start_pts,
  530. audio_end_pts,
  531. audio_timebase_num,
  532. audio_timebase_den,
  533. )
  534. assert max_dimension == max(tv_result[0].size(1), tv_result[0].size(2))
  535. @pytest.mark.parametrize("test_video", test_videos.keys())
  536. def test_read_video_from_file_rescale_both_min_max_dimension(self, test_video):
  537. """
  538. Test the case when decoder starts with a video file to decode frames, and
  539. video min dimension between height and width is set.
  540. """
  541. # video related
  542. width, height, min_dimension, max_dimension = 0, 0, 64, 85
  543. video_start_pts, video_end_pts = 0, -1
  544. video_timebase_num, video_timebase_den = 0, 1
  545. # audio related
  546. samples, channels = 0, 0
  547. audio_start_pts, audio_end_pts = 0, -1
  548. audio_timebase_num, audio_timebase_den = 0, 1
  549. full_path = os.path.join(VIDEO_DIR, test_video)
  550. tv_result = torch.ops.video_reader.read_video_from_file(
  551. full_path,
  552. SEEK_FRAME_MARGIN,
  553. 0, # getPtsOnly
  554. 1, # readVideoStream
  555. width,
  556. height,
  557. min_dimension,
  558. max_dimension,
  559. video_start_pts,
  560. video_end_pts,
  561. video_timebase_num,
  562. video_timebase_den,
  563. 1, # readAudioStream
  564. samples,
  565. channels,
  566. audio_start_pts,
  567. audio_end_pts,
  568. audio_timebase_num,
  569. audio_timebase_den,
  570. )
  571. assert min_dimension == min(tv_result[0].size(1), tv_result[0].size(2))
  572. assert max_dimension == max(tv_result[0].size(1), tv_result[0].size(2))
  573. @pytest.mark.parametrize("test_video", test_videos.keys())
  574. def test_read_video_from_file_rescale_width(self, test_video):
  575. """
  576. Test the case when decoder starts with a video file to decode frames, and
  577. video width is set.
  578. """
  579. # video related
  580. width, height, min_dimension, max_dimension = 256, 0, 0, 0
  581. video_start_pts, video_end_pts = 0, -1
  582. video_timebase_num, video_timebase_den = 0, 1
  583. # audio related
  584. samples, channels = 0, 0
  585. audio_start_pts, audio_end_pts = 0, -1
  586. audio_timebase_num, audio_timebase_den = 0, 1
  587. full_path = os.path.join(VIDEO_DIR, test_video)
  588. tv_result = torch.ops.video_reader.read_video_from_file(
  589. full_path,
  590. SEEK_FRAME_MARGIN,
  591. 0, # getPtsOnly
  592. 1, # readVideoStream
  593. width,
  594. height,
  595. min_dimension,
  596. max_dimension,
  597. video_start_pts,
  598. video_end_pts,
  599. video_timebase_num,
  600. video_timebase_den,
  601. 1, # readAudioStream
  602. samples,
  603. channels,
  604. audio_start_pts,
  605. audio_end_pts,
  606. audio_timebase_num,
  607. audio_timebase_den,
  608. )
  609. assert tv_result[0].size(2) == width
  610. @pytest.mark.parametrize("test_video", test_videos.keys())
  611. def test_read_video_from_file_rescale_height(self, test_video):
  612. """
  613. Test the case when decoder starts with a video file to decode frames, and
  614. video height is set.
  615. """
  616. # video related
  617. width, height, min_dimension, max_dimension = 0, 224, 0, 0
  618. video_start_pts, video_end_pts = 0, -1
  619. video_timebase_num, video_timebase_den = 0, 1
  620. # audio related
  621. samples, channels = 0, 0
  622. audio_start_pts, audio_end_pts = 0, -1
  623. audio_timebase_num, audio_timebase_den = 0, 1
  624. full_path = os.path.join(VIDEO_DIR, test_video)
  625. tv_result = torch.ops.video_reader.read_video_from_file(
  626. full_path,
  627. SEEK_FRAME_MARGIN,
  628. 0, # getPtsOnly
  629. 1, # readVideoStream
  630. width,
  631. height,
  632. min_dimension,
  633. max_dimension,
  634. video_start_pts,
  635. video_end_pts,
  636. video_timebase_num,
  637. video_timebase_den,
  638. 1, # readAudioStream
  639. samples,
  640. channels,
  641. audio_start_pts,
  642. audio_end_pts,
  643. audio_timebase_num,
  644. audio_timebase_den,
  645. )
  646. assert tv_result[0].size(1) == height
  647. @pytest.mark.parametrize("test_video", test_videos.keys())
  648. def test_read_video_from_file_rescale_width_and_height(self, test_video):
  649. """
  650. Test the case when decoder starts with a video file to decode frames, and
  651. both video height and width are set.
  652. """
  653. # video related
  654. width, height, min_dimension, max_dimension = 320, 240, 0, 0
  655. video_start_pts, video_end_pts = 0, -1
  656. video_timebase_num, video_timebase_den = 0, 1
  657. # audio related
  658. samples, channels = 0, 0
  659. audio_start_pts, audio_end_pts = 0, -1
  660. audio_timebase_num, audio_timebase_den = 0, 1
  661. full_path = os.path.join(VIDEO_DIR, test_video)
  662. tv_result = torch.ops.video_reader.read_video_from_file(
  663. full_path,
  664. SEEK_FRAME_MARGIN,
  665. 0, # getPtsOnly
  666. 1, # readVideoStream
  667. width,
  668. height,
  669. min_dimension,
  670. max_dimension,
  671. video_start_pts,
  672. video_end_pts,
  673. video_timebase_num,
  674. video_timebase_den,
  675. 1, # readAudioStream
  676. samples,
  677. channels,
  678. audio_start_pts,
  679. audio_end_pts,
  680. audio_timebase_num,
  681. audio_timebase_den,
  682. )
  683. assert tv_result[0].size(1) == height
  684. assert tv_result[0].size(2) == width
  685. @pytest.mark.parametrize("test_video", test_videos.keys())
  686. @pytest.mark.parametrize("samples", [9600, 96000])
  687. def test_read_video_from_file_audio_resampling(self, test_video, samples):
  688. """
  689. Test the case when decoder starts with a video file to decode frames, and
  690. audio waveform are resampled
  691. """
  692. # video related
  693. width, height, min_dimension, max_dimension = 0, 0, 0, 0
  694. video_start_pts, video_end_pts = 0, -1
  695. video_timebase_num, video_timebase_den = 0, 1
  696. # audio related
  697. channels = 0
  698. audio_start_pts, audio_end_pts = 0, -1
  699. audio_timebase_num, audio_timebase_den = 0, 1
  700. full_path = os.path.join(VIDEO_DIR, test_video)
  701. tv_result = torch.ops.video_reader.read_video_from_file(
  702. full_path,
  703. SEEK_FRAME_MARGIN,
  704. 0, # getPtsOnly
  705. 1, # readVideoStream
  706. width,
  707. height,
  708. min_dimension,
  709. max_dimension,
  710. video_start_pts,
  711. video_end_pts,
  712. video_timebase_num,
  713. video_timebase_den,
  714. 1, # readAudioStream
  715. samples,
  716. channels,
  717. audio_start_pts,
  718. audio_end_pts,
  719. audio_timebase_num,
  720. audio_timebase_den,
  721. )
  722. (
  723. vframes,
  724. vframe_pts,
  725. vtimebase,
  726. vfps,
  727. vduration,
  728. aframes,
  729. aframe_pts,
  730. atimebase,
  731. asample_rate,
  732. aduration,
  733. ) = tv_result
  734. if aframes.numel() > 0:
  735. assert samples == asample_rate.item()
  736. assert 1 == aframes.size(1)
  737. # when audio stream is found
  738. duration = float(aframe_pts[-1]) * float(atimebase[0]) / float(atimebase[1])
  739. assert aframes.size(0) == approx(int(duration * asample_rate.item()), abs=0.1 * asample_rate.item())
  740. @pytest.mark.parametrize("test_video,config", test_videos.items())
  741. def test_compare_read_video_from_memory_and_file(self, test_video, config):
  742. """
  743. Test the case when video is already in memory, and decoder reads data in memory
  744. """
  745. # video related
  746. width, height, min_dimension, max_dimension = 0, 0, 0, 0
  747. video_start_pts, video_end_pts = 0, -1
  748. video_timebase_num, video_timebase_den = 0, 1
  749. # audio related
  750. samples, channels = 0, 0
  751. audio_start_pts, audio_end_pts = 0, -1
  752. audio_timebase_num, audio_timebase_den = 0, 1
  753. full_path, video_tensor = _get_video_tensor(VIDEO_DIR, test_video)
  754. # pass 1: decode all frames using cpp decoder
  755. tv_result_memory = torch.ops.video_reader.read_video_from_memory(
  756. video_tensor,
  757. SEEK_FRAME_MARGIN,
  758. 0, # getPtsOnly
  759. 1, # readVideoStream
  760. width,
  761. height,
  762. min_dimension,
  763. max_dimension,
  764. video_start_pts,
  765. video_end_pts,
  766. video_timebase_num,
  767. video_timebase_den,
  768. 1, # readAudioStream
  769. samples,
  770. channels,
  771. audio_start_pts,
  772. audio_end_pts,
  773. audio_timebase_num,
  774. audio_timebase_den,
  775. )
  776. self.check_separate_decoding_result(tv_result_memory, config)
  777. # pass 2: decode all frames from file
  778. tv_result_file = torch.ops.video_reader.read_video_from_file(
  779. full_path,
  780. SEEK_FRAME_MARGIN,
  781. 0, # getPtsOnly
  782. 1, # readVideoStream
  783. width,
  784. height,
  785. min_dimension,
  786. max_dimension,
  787. video_start_pts,
  788. video_end_pts,
  789. video_timebase_num,
  790. video_timebase_den,
  791. 1, # readAudioStream
  792. samples,
  793. channels,
  794. audio_start_pts,
  795. audio_end_pts,
  796. audio_timebase_num,
  797. audio_timebase_den,
  798. )
  799. self.check_separate_decoding_result(tv_result_file, config)
  800. # finally, compare results decoded from memory and file
  801. self.compare_decoding_result(tv_result_memory, tv_result_file)
  802. @pytest.mark.parametrize("test_video,config", test_videos.items())
  803. def test_read_video_from_memory(self, test_video, config):
  804. """
  805. Test the case when video is already in memory, and decoder reads data in memory
  806. """
  807. # video related
  808. width, height, min_dimension, max_dimension = 0, 0, 0, 0
  809. video_start_pts, video_end_pts = 0, -1
  810. video_timebase_num, video_timebase_den = 0, 1
  811. # audio related
  812. samples, channels = 0, 0
  813. audio_start_pts, audio_end_pts = 0, -1
  814. audio_timebase_num, audio_timebase_den = 0, 1
  815. full_path, video_tensor = _get_video_tensor(VIDEO_DIR, test_video)
  816. # pass 1: decode all frames using cpp decoder
  817. tv_result = torch.ops.video_reader.read_video_from_memory(
  818. video_tensor,
  819. SEEK_FRAME_MARGIN,
  820. 0, # getPtsOnly
  821. 1, # readVideoStream
  822. width,
  823. height,
  824. min_dimension,
  825. max_dimension,
  826. video_start_pts,
  827. video_end_pts,
  828. video_timebase_num,
  829. video_timebase_den,
  830. 1, # readAudioStream
  831. samples,
  832. channels,
  833. audio_start_pts,
  834. audio_end_pts,
  835. audio_timebase_num,
  836. audio_timebase_den,
  837. )
  838. # pass 2: decode all frames using av
  839. pyav_result = _decode_frames_by_av_module(full_path)
  840. self.check_separate_decoding_result(tv_result, config)
  841. self.compare_decoding_result(tv_result, pyav_result, config)
  842. @pytest.mark.parametrize("test_video,config", test_videos.items())
  843. def test_read_video_from_memory_get_pts_only(self, test_video, config):
  844. """
  845. Test the case when video is already in memory, and decoder reads data in memory.
  846. Compare frame pts between decoding for pts only and full decoding
  847. for both pts and frame data
  848. """
  849. # video related
  850. width, height, min_dimension, max_dimension = 0, 0, 0, 0
  851. video_start_pts, video_end_pts = 0, -1
  852. video_timebase_num, video_timebase_den = 0, 1
  853. # audio related
  854. samples, channels = 0, 0
  855. audio_start_pts, audio_end_pts = 0, -1
  856. audio_timebase_num, audio_timebase_den = 0, 1
  857. _, video_tensor = _get_video_tensor(VIDEO_DIR, test_video)
  858. # pass 1: decode all frames using cpp decoder
  859. tv_result = torch.ops.video_reader.read_video_from_memory(
  860. video_tensor,
  861. SEEK_FRAME_MARGIN,
  862. 0, # getPtsOnly
  863. 1, # readVideoStream
  864. width,
  865. height,
  866. min_dimension,
  867. max_dimension,
  868. video_start_pts,
  869. video_end_pts,
  870. video_timebase_num,
  871. video_timebase_den,
  872. 1, # readAudioStream
  873. samples,
  874. channels,
  875. audio_start_pts,
  876. audio_end_pts,
  877. audio_timebase_num,
  878. audio_timebase_den,
  879. )
  880. assert abs(config.video_fps - tv_result[3].item()) < 0.01
  881. # pass 2: decode all frames to get PTS only using cpp decoder
  882. tv_result_pts_only = torch.ops.video_reader.read_video_from_memory(
  883. video_tensor,
  884. SEEK_FRAME_MARGIN,
  885. 1, # getPtsOnly
  886. 1, # readVideoStream
  887. width,
  888. height,
  889. min_dimension,
  890. max_dimension,
  891. video_start_pts,
  892. video_end_pts,
  893. video_timebase_num,
  894. video_timebase_den,
  895. 1, # readAudioStream
  896. samples,
  897. channels,
  898. audio_start_pts,
  899. audio_end_pts,
  900. audio_timebase_num,
  901. audio_timebase_den,
  902. )
  903. assert not tv_result_pts_only[0].numel()
  904. assert not tv_result_pts_only[5].numel()
  905. self.compare_decoding_result(tv_result, tv_result_pts_only)
  906. @pytest.mark.parametrize("test_video,config", test_videos.items())
  907. @pytest.mark.parametrize("num_frames", [4, 8, 16, 32, 64, 128])
  908. def test_read_video_in_range_from_memory(self, test_video, config, num_frames):
  909. """
  910. Test the case when video is already in memory, and decoder reads data in memory.
  911. In addition, decoder takes meaningful start- and end PTS as input, and decode
  912. frames within that interval
  913. """
  914. full_path, video_tensor = _get_video_tensor(VIDEO_DIR, test_video)
  915. # video related
  916. width, height, min_dimension, max_dimension = 0, 0, 0, 0
  917. video_start_pts, video_end_pts = 0, -1
  918. video_timebase_num, video_timebase_den = 0, 1
  919. # audio related
  920. samples, channels = 0, 0
  921. audio_start_pts, audio_end_pts = 0, -1
  922. audio_timebase_num, audio_timebase_den = 0, 1
  923. # pass 1: decode all frames using new decoder
  924. tv_result = torch.ops.video_reader.read_video_from_memory(
  925. video_tensor,
  926. SEEK_FRAME_MARGIN,
  927. 0, # getPtsOnly
  928. 1, # readVideoStream
  929. width,
  930. height,
  931. min_dimension,
  932. max_dimension,
  933. video_start_pts,
  934. video_end_pts,
  935. video_timebase_num,
  936. video_timebase_den,
  937. 1, # readAudioStream
  938. samples,
  939. channels,
  940. audio_start_pts,
  941. audio_end_pts,
  942. audio_timebase_num,
  943. audio_timebase_den,
  944. )
  945. (
  946. vframes,
  947. vframe_pts,
  948. vtimebase,
  949. vfps,
  950. vduration,
  951. aframes,
  952. aframe_pts,
  953. atimebase,
  954. asample_rate,
  955. aduration,
  956. ) = tv_result
  957. assert abs(config.video_fps - vfps.item()) < 0.01
  958. start_pts_ind_max = vframe_pts.size(0) - num_frames
  959. if start_pts_ind_max <= 0:
  960. return
  961. # randomly pick start pts
  962. start_pts_ind = randint(0, start_pts_ind_max)
  963. end_pts_ind = start_pts_ind + num_frames - 1
  964. video_start_pts = vframe_pts[start_pts_ind]
  965. video_end_pts = vframe_pts[end_pts_ind]
  966. video_timebase_num, video_timebase_den = vtimebase[0], vtimebase[1]
  967. if len(atimebase) > 0:
  968. # when audio stream is available
  969. audio_timebase_num, audio_timebase_den = atimebase[0], atimebase[1]
  970. audio_start_pts = _pts_convert(
  971. video_start_pts.item(),
  972. Fraction(video_timebase_num.item(), video_timebase_den.item()),
  973. Fraction(audio_timebase_num.item(), audio_timebase_den.item()),
  974. math.floor,
  975. )
  976. audio_end_pts = _pts_convert(
  977. video_end_pts.item(),
  978. Fraction(video_timebase_num.item(), video_timebase_den.item()),
  979. Fraction(audio_timebase_num.item(), audio_timebase_den.item()),
  980. math.ceil,
  981. )
  982. # pass 2: decode frames in the randomly generated range
  983. tv_result = torch.ops.video_reader.read_video_from_memory(
  984. video_tensor,
  985. SEEK_FRAME_MARGIN,
  986. 0, # getPtsOnly
  987. 1, # readVideoStream
  988. width,
  989. height,
  990. min_dimension,
  991. max_dimension,
  992. video_start_pts,
  993. video_end_pts,
  994. video_timebase_num,
  995. video_timebase_den,
  996. 1, # readAudioStream
  997. samples,
  998. channels,
  999. audio_start_pts,
  1000. audio_end_pts,
  1001. audio_timebase_num,
  1002. audio_timebase_den,
  1003. )
  1004. # pass 3: decode frames in range using PyAv
  1005. video_timebase_av, audio_timebase_av = _get_timebase_by_av_module(full_path)
  1006. video_start_pts_av = _pts_convert(
  1007. video_start_pts.item(),
  1008. Fraction(video_timebase_num.item(), video_timebase_den.item()),
  1009. Fraction(video_timebase_av.numerator, video_timebase_av.denominator),
  1010. math.floor,
  1011. )
  1012. video_end_pts_av = _pts_convert(
  1013. video_end_pts.item(),
  1014. Fraction(video_timebase_num.item(), video_timebase_den.item()),
  1015. Fraction(video_timebase_av.numerator, video_timebase_av.denominator),
  1016. math.ceil,
  1017. )
  1018. if audio_timebase_av:
  1019. audio_start_pts = _pts_convert(
  1020. video_start_pts.item(),
  1021. Fraction(video_timebase_num.item(), video_timebase_den.item()),
  1022. Fraction(audio_timebase_av.numerator, audio_timebase_av.denominator),
  1023. math.floor,
  1024. )
  1025. audio_end_pts = _pts_convert(
  1026. video_end_pts.item(),
  1027. Fraction(video_timebase_num.item(), video_timebase_den.item()),
  1028. Fraction(audio_timebase_av.numerator, audio_timebase_av.denominator),
  1029. math.ceil,
  1030. )
  1031. pyav_result = _decode_frames_by_av_module(
  1032. full_path,
  1033. video_start_pts_av,
  1034. video_end_pts_av,
  1035. audio_start_pts,
  1036. audio_end_pts,
  1037. )
  1038. assert tv_result[0].size(0) == num_frames
  1039. if pyav_result.vframes.size(0) == num_frames:
  1040. # if PyAv decodes a different number of video frames, skip
  1041. # comparing the decoding results between Torchvision video reader
  1042. # and PyAv
  1043. self.compare_decoding_result(tv_result, pyav_result, config)
  1044. @pytest.mark.parametrize("test_video,config", test_videos.items())
  1045. def test_probe_video_from_file(self, test_video, config):
  1046. """
  1047. Test the case when decoder probes a video file
  1048. """
  1049. full_path = os.path.join(VIDEO_DIR, test_video)
  1050. probe_result = torch.ops.video_reader.probe_video_from_file(full_path)
  1051. self.check_probe_result(probe_result, config)
  1052. @pytest.mark.parametrize("test_video,config", test_videos.items())
  1053. def test_probe_video_from_memory(self, test_video, config):
  1054. """
  1055. Test the case when decoder probes a video in memory
  1056. """
  1057. _, video_tensor = _get_video_tensor(VIDEO_DIR, test_video)
  1058. probe_result = torch.ops.video_reader.probe_video_from_memory(video_tensor)
  1059. self.check_probe_result(probe_result, config)
  1060. @pytest.mark.parametrize("test_video,config", test_videos.items())
  1061. def test_probe_video_from_memory_script(self, test_video, config):
  1062. scripted_fun = torch.jit.script(io._probe_video_from_memory)
  1063. assert scripted_fun is not None
  1064. _, video_tensor = _get_video_tensor(VIDEO_DIR, test_video)
  1065. probe_result = scripted_fun(video_tensor)
  1066. self.check_meta_result(probe_result, config)
  1067. @pytest.mark.parametrize("test_video", test_videos.keys())
  1068. def test_read_video_from_memory_scripted(self, test_video):
  1069. """
  1070. Test the case when video is already in memory, and decoder reads data in memory
  1071. """
  1072. # video related
  1073. width, height, min_dimension, max_dimension = 0, 0, 0, 0
  1074. video_start_pts, video_end_pts = 0, -1
  1075. video_timebase_num, video_timebase_den = 0, 1
  1076. # audio related
  1077. samples, channels = 0, 0
  1078. audio_start_pts, audio_end_pts = 0, -1
  1079. audio_timebase_num, audio_timebase_den = 0, 1
  1080. scripted_fun = torch.jit.script(io._read_video_from_memory)
  1081. assert scripted_fun is not None
  1082. _, video_tensor = _get_video_tensor(VIDEO_DIR, test_video)
  1083. # decode all frames using cpp decoder
  1084. scripted_fun(
  1085. video_tensor,
  1086. SEEK_FRAME_MARGIN,
  1087. 1, # readVideoStream
  1088. width,
  1089. height,
  1090. min_dimension,
  1091. max_dimension,
  1092. [video_start_pts, video_end_pts],
  1093. video_timebase_num,
  1094. video_timebase_den,
  1095. 1, # readAudioStream
  1096. samples,
  1097. channels,
  1098. [audio_start_pts, audio_end_pts],
  1099. audio_timebase_num,
  1100. audio_timebase_den,
  1101. )
  1102. # FUTURE: check value of video / audio frames
  1103. def test_invalid_file(self):
  1104. set_video_backend("video_reader")
  1105. with pytest.raises(RuntimeError):
  1106. io.read_video("foo.mp4")
  1107. set_video_backend("pyav")
  1108. with pytest.raises(RuntimeError):
  1109. io.read_video("foo.mp4")
  1110. @pytest.mark.parametrize("test_video", test_videos.keys())
  1111. @pytest.mark.parametrize("backend", ["video_reader", "pyav"])
  1112. @pytest.mark.parametrize("start_offset", [0, 500])
  1113. @pytest.mark.parametrize("end_offset", [3000, None])
  1114. def test_audio_present_pts(self, test_video, backend, start_offset, end_offset):
  1115. """Test if audio frames are returned with pts unit."""
  1116. full_path = os.path.join(VIDEO_DIR, test_video)
  1117. container = av.open(full_path)
  1118. if container.streams.audio:
  1119. set_video_backend(backend)
  1120. _, audio, _ = io.read_video(full_path, start_offset, end_offset, pts_unit="pts")
  1121. assert all([dimension > 0 for dimension in audio.shape[:2]])
  1122. @pytest.mark.parametrize("test_video", test_videos.keys())
  1123. @pytest.mark.parametrize("backend", ["video_reader", "pyav"])
  1124. @pytest.mark.parametrize("start_offset", [0, 0.1])
  1125. @pytest.mark.parametrize("end_offset", [0.3, None])
  1126. def test_audio_present_sec(self, test_video, backend, start_offset, end_offset):
  1127. """Test if audio frames are returned with sec unit."""
  1128. full_path = os.path.join(VIDEO_DIR, test_video)
  1129. container = av.open(full_path)
  1130. if container.streams.audio:
  1131. set_video_backend(backend)
  1132. _, audio, _ = io.read_video(full_path, start_offset, end_offset, pts_unit="sec")
  1133. assert all([dimension > 0 for dimension in audio.shape[:2]])
  1134. if __name__ == "__main__":
  1135. pytest.main([__file__])