cutcutcodec 1.0.post3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of cutcutcodec might be problematic. Click here for more details.

Files changed (233) hide show
  1. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/__init__.py +6 -0
  2. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/__main__.py +38 -0
  3. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/c_build.py +33 -0
  4. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/__init__.py +3 -0
  5. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/__init__.py +3 -0
  6. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/_helper_properties.py +52 -0
  7. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/audio/__init__.py +3 -0
  8. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/audio/properties/__init__.py +3 -0
  9. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/audio/properties/duration.py +83 -0
  10. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/ffprobe.py +637 -0
  11. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/graph/__init__.py +3 -0
  12. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/graph/find.py +82 -0
  13. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/graph/time_backprop.py +68 -0
  14. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/stream/__init__.py +3 -0
  15. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/stream/rate_audio.py +239 -0
  16. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/stream/rate_video.py +97 -0
  17. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/stream/shape.py +107 -0
  18. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/stream/time_backprop.py +183 -0
  19. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/video/__init__.py +3 -0
  20. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/video/properties/__init__.py +3 -0
  21. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/video/properties/duration.py +162 -0
  22. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/video/properties/nb_frames.py +159 -0
  23. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/video/properties/rate.py +102 -0
  24. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/analysis/video/properties/timestamps.py +194 -0
  25. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/classes/__init__.py +3 -0
  26. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/classes/container.py +40 -0
  27. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/classes/encoder.py +152 -0
  28. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/classes/filter.py +33 -0
  29. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/classes/frame.py +127 -0
  30. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/classes/frame_audio.py +205 -0
  31. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/classes/frame_video.py +322 -0
  32. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/classes/layout.py +206 -0
  33. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/classes/meta_filter.py +41 -0
  34. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/classes/muxer.py +184 -0
  35. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/classes/node.py +164 -0
  36. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/classes/stream.py +182 -0
  37. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/classes/stream_audio.py +130 -0
  38. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/classes/stream_video.py +193 -0
  39. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/compilation/__init__.py +7 -0
  40. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/compilation/ast_to_file.py +125 -0
  41. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/compilation/export/__init__.py +6 -0
  42. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/compilation/export/compatibility.py +734 -0
  43. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/compilation/export/default.py +99 -0
  44. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/compilation/export/encodec.py +40 -0
  45. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/compilation/export/muxer.py +8 -0
  46. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/compilation/export/rate.py +133 -0
  47. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/compilation/graph_to_ast.py +477 -0
  48. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/compilation/graph_to_json.py +104 -0
  49. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/compilation/graph_to_tree.py +190 -0
  50. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/compilation/json_to_graph.py +114 -0
  51. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/compilation/parse.py +123 -0
  52. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/compilation/sympy_to_torch/__init__.py +15 -0
  53. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/compilation/sympy_to_torch/dynamic.py +544 -0
  54. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/compilation/sympy_to_torch/lambdify.py +612 -0
  55. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/compilation/sympy_to_torch/preprocess.py +698 -0
  56. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/compilation/sympy_to_torch/printer.py +926 -0
  57. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/compilation/tree_to_graph.py +168 -0
  58. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/edit/__init__.py +3 -0
  59. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/edit/decision/__init__.py +8 -0
  60. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/edit/operation/__init__.py +3 -0
  61. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/edit/operation/add.py +73 -0
  62. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/edit/operation/remove.py +476 -0
  63. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/exceptions.py +60 -0
  64. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/__init__.py +3 -0
  65. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/audio/__init__.py +3 -0
  66. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/audio/add.py +170 -0
  67. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/audio/cat.py +60 -0
  68. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/audio/cut.py +112 -0
  69. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/audio/delay.py +85 -0
  70. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/audio/equation.py +261 -0
  71. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/audio/fir.py +231 -0
  72. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/audio/identity.py +48 -0
  73. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/audio/resample.py +451 -0
  74. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/audio/subclip.py +91 -0
  75. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/cut.py +74 -0
  76. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/mix/__init__.py +3 -0
  77. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/mix/audio_cast.py +208 -0
  78. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/mix/video_cast.py +197 -0
  79. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/subclip.py +53 -0
  80. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/video/__init__.py +3 -0
  81. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/video/add.py +331 -0
  82. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/video/cat.py +60 -0
  83. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/video/cut.py +113 -0
  84. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/video/delay.py +84 -0
  85. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/video/equation.py +265 -0
  86. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/video/identity.py +48 -0
  87. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/video/pad.py +99 -0
  88. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/filters/video/subclip.py +91 -0
  89. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/generation/__init__.py +3 -0
  90. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/generation/audio/__init__.py +3 -0
  91. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/generation/audio/empty.py +73 -0
  92. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/generation/audio/equation.py +56 -0
  93. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/generation/audio/noise.py +243 -0
  94. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/generation/video/__init__.py +3 -0
  95. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/generation/video/c_fractal.cpython-312-x86_64-linux-gnu.so +0 -0
  96. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/generation/video/empty.py +69 -0
  97. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/generation/video/equation.py +109 -0
  98. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/generation/video/fractal/__init__.py +3 -0
  99. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/generation/video/fractal/fractal.c +116 -0
  100. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/generation/video/fractal/geometry.py +100 -0
  101. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/generation/video/fractal/mandelbrot.py +176 -0
  102. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/generation/video/noise.py +112 -0
  103. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/interfaces/__init__.py +3 -0
  104. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/interfaces/seedable.py +82 -0
  105. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/io/__init__.py +3 -0
  106. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/io/read_ffmpeg.py +904 -0
  107. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/io/read_svg.py +145 -0
  108. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/io/scheduler.py +356 -0
  109. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/io/write.py +340 -0
  110. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/opti/__init__.py +3 -0
  111. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/opti/cache/__init__.py +3 -0
  112. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/opti/cache/basic.py +35 -0
  113. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/opti/cache/clean/__init__.py +3 -0
  114. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/opti/cache/clean/graph.py +80 -0
  115. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/opti/cache/hashes/__init__.py +3 -0
  116. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/opti/cache/hashes/graph.py +81 -0
  117. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/opti/cache/singleton.py +47 -0
  118. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/opti/cuda/__init__.py +3 -0
  119. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/opti/factor/__init__.py +5 -0
  120. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/opti/factor/proba.py +189 -0
  121. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/opti/generalize/__init__.py +5 -0
  122. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/opti/generalize/delay_to_fir.py +88 -0
  123. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/opti/graph.py +17 -0
  124. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/opti/parallel/__init__.py +3 -0
  125. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/opti/parallel/buffer.py +90 -0
  126. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/core/opti/utils.py +34 -0
  127. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/examples/audio_5.1_narration.oga +0 -0
  128. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/examples/intro.webm +0 -0
  129. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/examples/logo.svg +13 -0
  130. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/examples/project.json +226 -0
  131. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/examples/video.mp4 +0 -0
  132. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/__init__.py +8 -0
  133. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/__main__.py +25 -0
  134. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/actions.py +63 -0
  135. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/app/__init__.py +3 -0
  136. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/app/app.py +248 -0
  137. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/base.py +50 -0
  138. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/__init__.py +3 -0
  139. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/all/__init__.py +3 -0
  140. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/all/container_input_ffmpeg.py +90 -0
  141. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/all/filter_audio_delay.py +9 -0
  142. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/all/filter_audio_equation.py +45 -0
  143. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/all/filter_audio_fir.py +58 -0
  144. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/all/filter_audio_subclip.py +9 -0
  145. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/all/filter_cut.py +82 -0
  146. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/all/filter_delay.py +20 -0
  147. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/all/filter_subclip.py +21 -0
  148. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/all/filter_video_delay.py +9 -0
  149. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/all/filter_video_equation.py +53 -0
  150. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/all/filter_video_subclip.py +9 -0
  151. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/all/generator_audio_equation.py +14 -0
  152. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/all/generator_audio_noise.py +19 -0
  153. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/all/generator_video_equation.py +13 -0
  154. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/all/generator_video_mandelbrot.py +60 -0
  155. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/all/generator_video_noise.py +18 -0
  156. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/base.py +99 -0
  157. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/default.py +27 -0
  158. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/documentation.py +47 -0
  159. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/general.py +71 -0
  160. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/interface.py +305 -0
  161. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/loader.py +41 -0
  162. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edit_node_state/main.py +62 -0
  163. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/edition_tabs.py +34 -0
  164. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/entry/__init__.py +3 -0
  165. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/entry/base.py +122 -0
  166. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/entry/filters.py +42 -0
  167. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/entry/generators.py +42 -0
  168. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/entry_tabs.py +46 -0
  169. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/export/__init__.py +3 -0
  170. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/export/_helper.py +54 -0
  171. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/export/container.py +226 -0
  172. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/export/doc.py +67 -0
  173. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/export/encodec.py +289 -0
  174. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/export/main.py +173 -0
  175. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/flowchart/__init__.py +3 -0
  176. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/flowchart/edge_properties.py +56 -0
  177. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/flowchart/main.py +280 -0
  178. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/flowchart/node.py +44 -0
  179. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/main.py +151 -0
  180. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/menu.py +21 -0
  181. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/preferences/__init__.py +3 -0
  182. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/preferences/audio_settings.py +183 -0
  183. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/preferences/main.py +41 -0
  184. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/preferences/video_settings.py +257 -0
  185. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/run.py +71 -0
  186. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/timeline/__init__.py +3 -0
  187. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/timeline/main.py +30 -0
  188. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/timeline/slider.py +286 -0
  189. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/timeline/track.py +97 -0
  190. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/timeline/view.py +90 -0
  191. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/toolbar.py +29 -0
  192. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/tools.py +23 -0
  193. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/video_preview/__init__.py +3 -0
  194. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/video_preview/audio_player.py +103 -0
  195. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/video_preview/control.py +96 -0
  196. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/video_preview/frame_extractor.py +254 -0
  197. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/gui/video_preview/main.py +115 -0
  198. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/__init__.py +8 -0
  199. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/__main__.py +27 -0
  200. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/coding_style.py +49 -0
  201. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/generation.py +52 -0
  202. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/install.py +72 -0
  203. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/run.py +58 -0
  204. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/abstract.py +215 -0
  205. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/audio_cast.py +35 -0
  206. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/audio_equation.py +71 -0
  207. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/c_memory.py +132 -0
  208. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/compatibility.py +27 -0
  209. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/compile.py +42 -0
  210. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/encoder.py +23 -0
  211. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/filter_cut.py +107 -0
  212. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/filter_delay.py +71 -0
  213. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/filter_empty.py +40 -0
  214. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/fir.py +143 -0
  215. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/hashes.py +23 -0
  216. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/initialisation.py +24 -0
  217. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/muxer.py +22 -0
  218. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/nan_snapshot.py +39 -0
  219. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/read.py +192 -0
  220. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/serialization_equality.py +50 -0
  221. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/snapshot_shape.py +21 -0
  222. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/sympy_to_torch.py +135 -0
  223. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/thread_safe.py +77 -0
  224. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/time_range.py +55 -0
  225. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/video_equation.py +77 -0
  226. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/testing/tests/write.py +95 -0
  227. cutcutcodec-1.0.post3.data/platlib/cutcutcodec/utils.py +40 -0
  228. cutcutcodec-1.0.post3.dist-info/LICENSE +7 -0
  229. cutcutcodec-1.0.post3.dist-info/METADATA +271 -0
  230. cutcutcodec-1.0.post3.dist-info/RECORD +233 -0
  231. cutcutcodec-1.0.post3.dist-info/WHEEL +5 -0
  232. cutcutcodec-1.0.post3.dist-info/entry_points.txt +6 -0
  233. cutcutcodec-1.0.post3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,904 @@
1
+ #!/usr/bin/env python3
2
+
3
+ """Decode the streams of a multimedia file based on ffmpeg.
4
+
5
+ Decodes video and audio. Images are not well decoded hear.
6
+ """
7
+
8
+ from fractions import Fraction
9
+ import logging
10
+ import math
11
+ import numbers
12
+ import pathlib
13
+ import threading
14
+ import typing
15
+
16
+ import av
17
+ import numpy as np
18
+ import torch
19
+
20
+ from cutcutcodec.core.analysis.audio.properties.duration import get_duration_audio
21
+ from cutcutcodec.core.analysis.ffprobe import _estimate_rate_ffmpeg
22
+ from cutcutcodec.core.analysis.ffprobe import get_streams_type
23
+ from cutcutcodec.core.classes.container import ContainerInput
24
+ from cutcutcodec.core.classes.frame_audio import FrameAudio
25
+ from cutcutcodec.core.classes.frame_video import FrameVideo
26
+ from cutcutcodec.core.classes.layout import Layout
27
+ from cutcutcodec.core.classes.stream import Stream
28
+ from cutcutcodec.core.classes.stream_audio import StreamAudio
29
+ from cutcutcodec.core.classes.stream_video import StreamVideo
30
+ from cutcutcodec.core.exceptions import MissingInformation, MissingStreamError, OutOfTimeRange
31
+ from cutcutcodec.core.filters.video.pad import pad_keep_ratio
32
+ from cutcutcodec.utils import get_project_root
33
+
34
+
35
+ class ContainerInputFFMPEG(ContainerInput):
36
+ """Allow to decode a multimedia file with ffmpeg.
37
+
38
+ Attributes
39
+ ----------
40
+ av_kwargs : dict[str]
41
+ The parameters passed to ``av.open``.
42
+ filename : pathlib.Path
43
+ The path to the physical file that contains the extracted video stream (readonly).
44
+
45
+ Notes
46
+ -----
47
+ In order to avoid the folowing error :
48
+ ``av.error.InvalidDataError: [Errno 1094995529] Invalid data found when processing input;
49
+ last error log: [libdav1d] Error parsing OBU data``
50
+ Which happens when reading a multi-stream file sparingly, The instances of
51
+ ``av.container.InputContainer`` are new for each stream.
52
+
53
+ Examples
54
+ --------
55
+ >>> import torch
56
+ >>> from cutcutcodec.core.io.read_ffmpeg import ContainerInputFFMPEG
57
+ >>> with ContainerInputFFMPEG("cutcutcodec/examples/intro.webm") as container:
58
+ ... for stream in container.out_streams:
59
+ ... if stream.type == "video":
60
+ ... stream.snapshot(0, (stream.height, stream.width)).shape
61
+ ... elif stream.type == "audio":
62
+ ... torch.round(stream.snapshot(0, rate=2, samples=3), decimals=5)
63
+ ...
64
+ (720, 1280, 3)
65
+ (360, 640, 3)
66
+ FrameAudio(0, 2, 'stereo', [[ nan, 0.1804 , -0.34765],
67
+ [ nan, -0.07236, 0.07893]])
68
+ FrameAudio(0, 2, 'mono', [[ nan, 0.06998, -0.24758]])
69
+ >>>
70
+ """
71
+
72
+ def __init__(self, filename: typing.Union[str, bytes, pathlib.Path], **av_kwargs):
73
+ """Initialise and create the class.
74
+
75
+ Parameters
76
+ ----------
77
+ filename : pathlike
78
+ Path to the file to be decoded.
79
+ **av_kwargs : dict
80
+ Directly transmitted to ``av.open``.
81
+
82
+ * ``"format" (str)``: Specific format to use. Defaults to autodect.
83
+ * ``"options" (dict)``: Options to pass to the container and all streams.
84
+ * ``"container_options" (dict)``: Options to pass to the container.
85
+ * ``"stream_options" (list)``: Options to pass to each stream.
86
+ * ``"metadata_encoding" (str)``: Encoding to use when reading or writing file metadata.
87
+ Defaults to "utf-8".
88
+ * ``"metadata_errors" (str)``: Specifies how to handle encoding errors;
89
+ behaves like str.encode parameter. Defaults to "strict".
90
+ * ``"buffer_size" (int)``: Size of buffer for Python input/output operations in bytes.
91
+ Honored only when file is a file-like object. Defaults to 32768 (32k).
92
+ * ``"timeout" (float or tuple)``: How many seconds to wait for data before giving up,
93
+ as a float, or a (open timeout, read timeout) tuple.
94
+ """
95
+ filename = pathlib.Path(filename)
96
+ assert filename.is_file(), filename
97
+
98
+ self._filename = filename
99
+ self._av_kwargs = av_kwargs # need for compilation
100
+ self._av_kwargs["options"] = self._av_kwargs.get("options", {})
101
+ self._av_kwargs["container_options"] = self._av_kwargs.get("container_options", {})
102
+
103
+ out_streams = [self._init_out_stream(s_t) for s_t in get_streams_type(filename)]
104
+ super().__init__(out_streams)
105
+
106
+ def __enter__(self):
107
+ """Make the object compatible with a context manager."""
108
+ return self
109
+
110
+ def __exit__(self, *_):
111
+ """Exit the context manager, close the stream watever happends."""
112
+ self.close()
113
+
114
+ def _getstate(self) -> dict:
115
+ return {
116
+ "filename": str(self.filename),
117
+ "av_kwargs": self.av_kwargs,
118
+ }
119
+
120
+ def _setstate(self, in_streams: typing.Iterable[Stream], state: dict) -> None:
121
+ keys = {"filename", "av_kwargs"}
122
+ assert state.keys() == keys, set(state)-keys
123
+ ContainerInputFFMPEG.__init__(self, state["filename"], **state["av_kwargs"])
124
+
125
+ def _init_out_stream(self, stream_type: str) -> Stream:
126
+ if (
127
+ stream_class := (
128
+ {"audio": _StreamAudioFFMPEG, "video": _StreamVideoFFMPEG}.get(stream_type, None)
129
+ )
130
+ ) is None:
131
+ raise ValueError(f"only 'audio' and 'video' stream is supproted, not {stream_type}")
132
+ return stream_class(self)
133
+
134
+ @classmethod
135
+ def default(cls):
136
+ """Provide a minimalist example of an instance of this node."""
137
+ return cls(get_project_root() / "examples" / "intro.webm")
138
+
139
+ def close(self):
140
+ """Close the file."""
141
+ for stream in self.out_streams:
142
+ stream.reset()
143
+
144
+ @property
145
+ def av_kwargs(self) -> dict[str]:
146
+ """Return the parameters passed to ``av.open``."""
147
+ return self._av_kwargs
148
+
149
+ @property
150
+ def filename(self) -> pathlib.Path:
151
+ """Return the path to the physical file that contains the extracted video stream."""
152
+ return self._filename
153
+
154
+
155
+ class _StreamFFMPEGBase(Stream):
156
+ """Factorise share methods between audio and video."""
157
+
158
+ is_time_continuous = False
159
+
160
+ def __init__(self, node: ContainerInputFFMPEG):
161
+ assert isinstance(node, ContainerInputFFMPEG), node.__class__.__name__
162
+ super().__init__(node)
163
+
164
+ self._av_container = None
165
+ self._duration = None
166
+ self._frame_iter = None
167
+ self._prec_frame = self._next_frame = None
168
+ self._rate = None # optimise about 100 ms par call
169
+
170
+ def _seek_backward(self, position: Fraction) -> None:
171
+ """Move backwards in the file.
172
+
173
+ This method guarantees to move before the required position.
174
+ If this is not possible, we move to the very beginning of the file.
175
+ After, we always have ``self.get_current_range()[0] <= position``.
176
+ """
177
+ if self.type == "audio":
178
+ dec = Fraction(self.av_container.streams[self.index].frame_size, self.rate)
179
+ elif self.type == "video":
180
+ dec = 1 / self.rate
181
+ else:
182
+ dec = 0
183
+ for pos in (position, position-10, 0):
184
+ stream = self.av_container.streams[self.index] # must be define in 'for' because reset
185
+ try:
186
+ self.av_container.seek(
187
+ max(0, math.floor((pos - 2*dec) / stream.time_base)),
188
+ backward=True, # if there is not a keyframe at the given offset
189
+ stream=stream
190
+ )
191
+ except av.error.PermissionError: # happens sometimes
192
+ self.reset()
193
+ break
194
+ self._prec_frame = self._next_frame = None # takes into account the new position
195
+
196
+ # verification and rough adjustment
197
+ try:
198
+ if self.get_current_range()[0] <= position:
199
+ break
200
+ except OutOfTimeRange: # if this exception is throw, reset is just done
201
+ continue
202
+ else:
203
+ self.reset()
204
+
205
+ def _seek_forward(self, position: Fraction) -> None:
206
+ """Move forwardwards in the file.
207
+
208
+ The displacement, if some cases, can be very approximate.
209
+ """
210
+ stream = self.av_container.streams[self.index]
211
+ if stream.type == "audio":
212
+ dec = Fraction(stream.frame_size, self.rate)
213
+ elif stream.type == "video":
214
+ dec = 1 / self.rate
215
+ else:
216
+ dec = 0
217
+ self.av_container.seek(
218
+ max(0, math.floor((position - dec) / stream.time_base)),
219
+ backward=True, # if there is not a keyframe at the given offset
220
+ stream=stream
221
+ )
222
+ self._prec_frame = self._next_frame = None # takes into account the new position
223
+
224
+ @property
225
+ def av_container(self) -> av.container.Container:
226
+ """Allow to read the file at the last moment."""
227
+ if self._av_container is None:
228
+ self._av_container = av.open(str(self.node.filename), "r", **self.node.av_kwargs)
229
+ self._av_container.streams[self.index].thread_type = "AUTO" # mit improve speed
230
+ return self._av_container
231
+
232
+ @property
233
+ def beginning(self) -> Fraction:
234
+ return Fraction(0)
235
+
236
+ @property
237
+ def frame_iter(self) -> typing.Iterable[av.audio.frame.AudioFrame]:
238
+ """Allow to read the file at the last moment."""
239
+ if self._frame_iter is None:
240
+ self._frame_iter = iter(self.av_container.decode(self.av_container.streams[self.index]))
241
+ return self._frame_iter
242
+
243
+ @property
244
+ def next_frame(self) -> typing.Union[None, av.audio.frame.AudioFrame]:
245
+ """Return the next frame if exists, None else."""
246
+ if self._next_frame is None:
247
+ self._prec_frame = self.prec_frame # iter if needed ("=" is for pylint W0104)
248
+ try:
249
+ self._next_frame = next(self.frame_iter)
250
+ except (StopIteration, av.error.EOFError):
251
+ self._next_frame = self._frame_iter = None
252
+ if self._duration is None: # facultative, it is just optimisation
253
+ t_start, t_end = frame_dates(self._prec_frame)
254
+ self._duration = t_start + Fraction(1, self.rate) if t_end is None else t_end
255
+ return self._next_frame
256
+
257
+ @property
258
+ def prec_frame(self) -> av.audio.frame.AudioFrame:
259
+ """Return the frame at the current position."""
260
+ if self._prec_frame is None:
261
+ try:
262
+ self._prec_frame = next(self.frame_iter)
263
+ except (StopIteration, av.error.EOFError) as err:
264
+ self.reset()
265
+ raise OutOfTimeRange("there is no frame left to read") from err
266
+ return self._prec_frame
267
+
268
+ @property
269
+ def rate(self) -> Fraction:
270
+ """Return the theorical image or sample frequency in the metadata."""
271
+ if self._rate is None:
272
+ self._rate = _estimate_rate_ffmpeg(self.node.filename, self.index)
273
+ return self._rate
274
+
275
+ def reset(self) -> None:
276
+ """Close the file and delete all internal state."""
277
+ if self._av_container is not None:
278
+ self._prec_frame = self._next_frame = None
279
+ self._frame_iter = None
280
+ self._av_container.close()
281
+ self._av_container = None
282
+
283
+
284
+ class _StreamAudioFFMPEG(StreamAudio, _StreamFFMPEGBase):
285
+ """Stream Audio from a file.
286
+
287
+ Attributes
288
+ ----------
289
+ duration : Fraction
290
+ The exact duration of the stream (readonly).
291
+ This date corresponds to the end of the last sample.
292
+ rate : int
293
+ The frequency in Hz of the samples (readonly).
294
+
295
+ Notes
296
+ -----
297
+ Should use ``ffmpegio.audio.read(file, sample_fmt='dbl')``.
298
+ """
299
+
300
+ def __init__(self, node: ContainerInputFFMPEG):
301
+ super().__init__(node)
302
+ self._duration = None
303
+ self._lock = threading.Lock()
304
+
305
+ def _snapshot(self, timestamp: Fraction, rate: int, samples: int) -> FrameAudio:
306
+ if timestamp < 0:
307
+ raise OutOfTimeRange(f"there is no audio frame at timestamp {timestamp} (need >= 0)")
308
+
309
+ # resample if needeed
310
+ if samples != 1 and rate != self.rate:
311
+ frame = self._snapshot(
312
+ timestamp,
313
+ rate=self.rate,
314
+ samples=math.floor(samples*Fraction(self.rate, rate))
315
+ )
316
+ indexs = torch.arange(samples, dtype=torch.int64)
317
+ indexs *= self.rate
318
+ indexs //= rate
319
+ frame = FrameAudio(timestamp, rate, frame.layout, frame[:, indexs])
320
+ return frame
321
+
322
+ # decode concerned frames
323
+ frames_and_dates: list[list[np.ndarray, Fraction, Fraction]] = [] # frame, start_t, end_t
324
+ end = timestamp + Fraction(samples, rate) # apparition of last sample
325
+ with self._lock:
326
+ self.seek(timestamp)
327
+ while True:
328
+ try:
329
+ frame = self.prec_frame
330
+ except OutOfTimeRange as err:
331
+ raise OutOfTimeRange(
332
+ f"stream start {self.beginning} and end {self.beginning + self.duration}, "
333
+ f"no stream at timestamp {timestamp} to {timestamp} + {samples}/{rate}"
334
+ ) from err
335
+ if frame.is_corrupt:
336
+ logging.warning("the frame at %f seconds is corrupted", frame.time)
337
+ continue
338
+ dates = frame_dates(frame)
339
+ frames_and_dates.append(
340
+ [ # the reshape is usefull only in some cases for debug in ffmpeg 4
341
+ frame.to_ndarray().reshape(-1, frame.samples, order="F"),
342
+ dates[0]-timestamp,
343
+ dates[1]-timestamp,
344
+ ]
345
+ )
346
+ if end <= dates[1]:
347
+ break
348
+ self._prec_frame, self._next_frame = self.next_frame, None # iter in stream
349
+
350
+ # correct the drift
351
+ drift_max = self.av_container.streams[self.index].time_base
352
+ drift_max = 2 if drift_max is None else math.ceil(drift_max*rate)
353
+ frames_and_dates = _fix_drift_fill_crop(frames_and_dates, drift_max, rate, samples)
354
+
355
+ # create the final frame
356
+ return FrameAudio(
357
+ timestamp,
358
+ rate,
359
+ self.layout,
360
+ (
361
+ np.concatenate([f for f, _, _ in frames_and_dates], axis=1)
362
+ if len(frames_and_dates) > 1 else frames_and_dates.pop()[0]
363
+ ),
364
+ )
365
+
366
+ @property
367
+ def duration(self) -> typing.Union[Fraction, float]:
368
+ """Return the exact duration in seconds.
369
+
370
+ Examples
371
+ --------
372
+ >>> from cutcutcodec.core.io.read_ffmpeg import ContainerInputFFMPEG
373
+ >>> with ContainerInputFFMPEG("cutcutcodec/examples/audio_5.1_narration.oga") as container:
374
+ ... (stream,) = container.out_streams
375
+ ... stream.duration
376
+ ...
377
+ Fraction(8, 1)
378
+ >>>
379
+ """
380
+ if self._duration is not None:
381
+ return self._duration
382
+ # seek approximative
383
+ rel_index = len(
384
+ [
385
+ None for i, s in enumerate(self.node.out_streams)
386
+ if i < self.index and s.type == "audio"
387
+ ]
388
+ )
389
+ with self._lock:
390
+ self.seek(get_duration_audio(self.node.filename, rel_index, accurate=False) - 10)
391
+ # decoding until reaching the last frame
392
+ while self.next_frame is not None:
393
+ self._prec_frame, self._next_frame = self.next_frame, None # iter in stream
394
+ # get the time of the last frame + the frame duration
395
+ self._duration = frame_dates(self._prec_frame)[1]
396
+ return self._duration
397
+
398
+ def get_current_range(self) -> tuple[Fraction, Fraction]:
399
+ """Return the time interval cover by the current frame."""
400
+ if (next_frame := self.next_frame) is None:
401
+ return frame_dates(self.prec_frame)
402
+ return frame_dates(self.prec_frame)[0], frame_dates(next_frame)[0]
403
+
404
+ @property
405
+ def layout(self) -> Layout:
406
+ """Return the signification of each channels in this audio stream.
407
+
408
+ Examples
409
+ --------
410
+ >>> from cutcutcodec.core.io.read_ffmpeg import ContainerInputFFMPEG
411
+ >>> with ContainerInputFFMPEG("cutcutcodec/examples/audio_5.1_narration.oga") as container:
412
+ ... (stream,) = container.out_streams
413
+ ... stream.layout
414
+ ...
415
+ Layout('5.1')
416
+ >>>
417
+ """
418
+ return Layout(self.av_container.streams[self.index].layout.name)
419
+
420
+ @property
421
+ def rate(self) -> int:
422
+ """Return the theorical image or sample frequency in the metadata."""
423
+ return int(super().rate)
424
+
425
+ def seek(self, position: Fraction) -> None:
426
+ """Move into the file until reaching the frame at this position.
427
+
428
+ If you are already well placed, this has no effect.
429
+ Allows backward even a little bit, but only jump forward if the jump is big enough.
430
+
431
+ Parameters
432
+ ----------
433
+ position : fraction.Fraction
434
+ The target position such as ``self.prec_frame.time <= position < self.next_frame.time``.
435
+ This position is expressed in seconds.
436
+
437
+ Raises
438
+ ------
439
+ OutOfTimeRange
440
+ If the required position is out of the definition range.
441
+
442
+ Examples
443
+ --------
444
+ >>> from fractions import Fraction
445
+ >>> from cutcutcodec.core.io.read_ffmpeg import ContainerInputFFMPEG
446
+ >>> with ContainerInputFFMPEG("cutcutcodec/examples/audio_5.1_narration.oga") as container:
447
+ ... (stream,) = container.out_streams
448
+ ... stream.seek(Fraction(7))
449
+ ... stream.get_current_range()
450
+ ... stream.seek(Fraction(5))
451
+ ... stream.get_current_range()
452
+ ...
453
+ (Fraction(872, 125), Fraction(876, 125))
454
+ (Fraction(624, 125), Fraction(628, 125))
455
+ >>>
456
+ """
457
+ assert isinstance(position, Fraction), position.__class__.__name__
458
+
459
+ # case need to seek
460
+ if position > self.get_current_range()[1] + 10: # forward if jump more 10 seconds
461
+ self._seek_forward(position) # very approximative
462
+ if position < self.get_current_range()[0]:
463
+ self._seek_backward(position) # guaranteed to be before
464
+
465
+ # fine adjustment
466
+ while self.get_current_range()[1] <= position:
467
+ self._prec_frame, self._next_frame = self.next_frame, None # iter in stream
468
+
469
+
470
+ class _StreamVideoFFMPEG(StreamVideo, _StreamFFMPEGBase):
471
+ """Stream Video from a file.
472
+
473
+ Attributes
474
+ ----------
475
+ height : int
476
+ The dimension i (vertical) of the encoded frames in pxl (readonly).
477
+ duration : Fraction
478
+ The exact duration of the complete stream (readonly).
479
+ the time include the duration of the last frame.
480
+ width : int
481
+ The dimension j (horizontal) of the encoded frames in pxl (readonly).
482
+ """
483
+
484
+ is_space_continuous = False
485
+
486
+ def __init__(self, node: ContainerInputFFMPEG):
487
+ super().__init__(node)
488
+ self._duration = None
489
+ self._key_times = None
490
+ self._lock = threading.Lock()
491
+
492
+ def _snapshot(self, timestamp: Fraction, mask: torch.Tensor) -> torch.Tensor:
493
+ if timestamp < 0:
494
+ raise OutOfTimeRange(f"there is no audio frame at timestamp {timestamp} (need >= 0)")
495
+
496
+ # find the shape for keeping proportion
497
+ wdst_hsrc, hdst_wsrc = mask.shape[1] * self.height, mask.shape[0] * self.width
498
+ padding_required = True
499
+ if wdst_hsrc == hdst_wsrc: # if the proportion is the same
500
+ height, width = mask.shape
501
+ padding_required = False
502
+ elif wdst_hsrc > hdst_wsrc: # need horizontal padding
503
+ height, width = (mask.shape[0], round(hdst_wsrc/self.height)) # keep height unchanged
504
+ else:
505
+ height, width = (round(wdst_hsrc/self.width), mask.shape[1]) # keep width unchanged
506
+
507
+ # decode the frame and convert into numpy array
508
+ with self._lock:
509
+ self.seek(timestamp) # adjust position
510
+ frame_av = self.prec_frame
511
+ frame_np = frame_av.to_ndarray(
512
+ width=width, # reshape is alltimes required for non-squared pixels
513
+ height=height, # av is able to squeeze reshape if the shape is the same
514
+ format="bgr24",
515
+ dst_colorspace=av.video.reformatter.Colorspace.DEFAULT,
516
+ interpolation=(
517
+ av.video.reformatter.Interpolation.AREA if ( # for shirking
518
+ height < self.av_container.streams[self.index].coded_height
519
+ or width < self.av_container.streams[self.index].coded_width
520
+ ) else av.video.reformatter.Interpolation.BICUBIC # for enlarge
521
+ ),
522
+ )
523
+
524
+ # final thread-safe operations
525
+ if padding_required:
526
+ frame_np = pad_keep_ratio(frame_np, mask.shape)
527
+ return FrameVideo(frame_dates(frame_av)[0], frame_np)
528
+
529
+ @property
530
+ def duration(self) -> typing.Union[Fraction, float]:
531
+ """Return the exact duration in seconds.
532
+
533
+ Examples
534
+ --------
535
+ >>> from cutcutcodec.core.io.read_ffmpeg import ContainerInputFFMPEG
536
+ >>> with ContainerInputFFMPEG("cutcutcodec/examples/video.mp4") as container:
537
+ ... (stream,) = container.out_streams
538
+ ... stream.duration
539
+ ...
540
+ Fraction(16, 1)
541
+ >>>
542
+ """
543
+ if self._duration is not None:
544
+ return self._duration
545
+ with self._lock:
546
+ # jump if need
547
+ key_times = self.get_key_times()
548
+ key_time = key_times[-2] if len(key_times) >= 2 else Fraction(0)
549
+
550
+ # print("avant seek", self.get_current_range())
551
+ self.seek(key_time) # sometimes self.reset() corrects the bug
552
+ # decoding until reaching the last frame
553
+ while self.next_frame is not None:
554
+ self._prec_frame, self._next_frame = self.next_frame, None # iter in stream
555
+ # get the time of the last frame + the frame duration
556
+ self._duration = frame_dates(self._prec_frame)[0] + 1/self.rate
557
+ return self._duration
558
+
559
+ def get_key_times(self) -> np.ndarray[Fraction]:
560
+ """Allow to read the file at the last moment.
561
+
562
+ Examples
563
+ --------
564
+ >>> from cutcutcodec.core.io.read_ffmpeg import ContainerInputFFMPEG
565
+ >>> with ContainerInputFFMPEG("cutcutcodec/examples/video.mp4") as container:
566
+ ... (stream,) = container.out_streams
567
+ ... stream.get_key_times()
568
+ ...
569
+ array([Fraction(0, 1), Fraction(10, 1)], dtype=object)
570
+ >>>
571
+ """
572
+ if self._key_times is None:
573
+ try:
574
+ self._key_times = np.fromiter(
575
+ (
576
+ frame_dates(frame)[0] for frame in _extract_key_frames(
577
+ self.av_container.streams[self.index]
578
+ )
579
+ ),
580
+ dtype=object,
581
+ )
582
+ except MissingInformation as err:
583
+ raise MissingInformation("the timestamp is not known for all keyframes") from err
584
+ if len(self._key_times) == 0:
585
+ raise MissingStreamError(
586
+ f"can not decode any frames of {self.node.filename} stream {self.index}"
587
+ )
588
+ return self._key_times
589
+
590
+ def get_current_range(self) -> tuple[Fraction, Fraction]:
591
+ """Return the time interval cover by the current frame."""
592
+ start_time = frame_dates(self.prec_frame)[0]
593
+ if (next_frame := self.next_frame) is None:
594
+ return start_time, start_time + 1/self.rate
595
+ return start_time, frame_dates(next_frame)[0]
596
+
597
+ @property
598
+ def height(self) -> int:
599
+ """Return the vertical size of the native frame in pxl."""
600
+ if (ratio := Fraction(self.av_container.streams[self.index].sample_aspect_ratio or 1)) < 1:
601
+ return int(self.av_container.streams[self.index].height / ratio)
602
+ return self.av_container.streams[self.index].height
603
+
604
+ def seek(self, position: Fraction) -> None:
605
+ """Move into the file until reaching the frame at this accurate position.
606
+
607
+ If you are already well placed, this has no effect.
608
+ Allows backward even a little bit, but only jump forward if the jump is big enough.
609
+
610
+ Parameters
611
+ ----------
612
+ position : fraction.Fraction
613
+ The target position such as ``self.prec_frame.time <= position < self.next_frame.time``.
614
+ This position is expressed in seconds.
615
+
616
+ Raises
617
+ ------
618
+ OutOfTimeRange
619
+ If the required position is out of the definition range.
620
+
621
+ Examples
622
+ --------
623
+ >>> from fractions import Fraction
624
+ >>> from cutcutcodec.core.io.read_ffmpeg import ContainerInputFFMPEG
625
+ >>> with ContainerInputFFMPEG("cutcutcodec/examples/video.mp4") as container:
626
+ ... (stream,) = container.out_streams
627
+ ... stream.seek(Fraction(15))
628
+ ... stream.get_current_range()
629
+ ... stream.seek(Fraction(5))
630
+ ... stream.get_current_range()
631
+ ...
632
+ (Fraction(15, 1), Fraction(376, 25))
633
+ (Fraction(5, 1), Fraction(126, 25))
634
+ >>>
635
+ """
636
+ assert isinstance(position, Fraction), position.__class__.__name__
637
+
638
+ # case need to seek
639
+ if position > self.get_current_range()[1] + 100/self.rate: # if jump more than 100 frames
640
+ self._seek_forward(position) # very approximative
641
+ if position < self.get_current_range()[0]:
642
+ self._seek_backward(position) # guaranteed to be before
643
+
644
+ # fine adjustment
645
+ while position >= self.get_current_range()[1]:
646
+ self._prec_frame, self._next_frame = self.next_frame, None # iter in stream
647
+
648
+ # # check asked seek position is not bigger than the duration
649
+ # if position > self.get_current_range()[0]:
650
+ # raise OutOfTimeRange(
651
+ # f"stream start {self.beginning} and end {self.beginning + self.duration}, "
652
+ # f"no frame at timestamp {position}"
653
+ # )
654
+
655
+ @property
656
+ def width(self) -> int:
657
+ """Return the horizontal size of the native frame in pxl."""
658
+ if (ratio := Fraction(self.av_container.streams[self.index].sample_aspect_ratio or 1)) > 1:
659
+ return int(self.av_container.streams[self.index].width * ratio)
660
+ return self.av_container.streams[self.index].width
661
+
662
+
663
+ def _convert_audio_samples(audio_samples: np.ndarray[numbers.Real]) -> torch.Tensor:
664
+ """Convert sound samples into float between -1 and 1.
665
+
666
+ Minimizes copying and reallocations.
667
+ The values are not clamped.
668
+
669
+ Examples
670
+ --------
671
+ >>> import numpy as np
672
+ >>> from cutcutcodec.core.io.read_ffmpeg import _convert_audio_samples
673
+ >>> _convert_audio_samples(np.array([-1.5, -1.0, -.5, .5, 1.0, 1.5], dtype=np.float64))
674
+ tensor([-1.5000, -1.0000, -0.5000, 0.5000, 1.0000, 1.5000],
675
+ dtype=torch.float64)
676
+ >>> _convert_audio_samples(np.array([-1.5, -1.0, -.5, .5, 1.0, 1.5], dtype=np.float32))
677
+ tensor([-1.5000, -1.0000, -0.5000, 0.5000, 1.0000, 1.5000])
678
+ >>> _convert_audio_samples(np.array([-1.5, -1.0, -.5, .5, 1.0, 1.5], dtype=np.float16))
679
+ tensor([-1.5000, -1.0000, -0.5000, 0.5000, 1.0000, 1.5000],
680
+ dtype=torch.float16)
681
+ >>> _convert_audio_samples(
682
+ ... np.array([-2147483648, -1073741824, 1073741824, 2147483647], dtype=np.int32)
683
+ ... )
684
+ tensor([-1.0000, -0.5000, 0.5000, 1.0000], dtype=torch.float64)
685
+ >>> _convert_audio_samples(np.array([-32768, -16384, 16384, 32767], dtype=np.int16))
686
+ tensor([-1.0000, -0.5000, 0.5000, 1.0000], dtype=torch.float64)
687
+ >>> _convert_audio_samples(np.array([0, 64, 192, 255], dtype=np.uint8))
688
+ tensor([-1.0000, -0.4980, 0.5059, 1.0000], dtype=torch.float64)
689
+ >>>
690
+ """
691
+ assert isinstance(audio_samples, np.ndarray), audio_samples.__class__.__name__
692
+ audio_samples = torch.from_numpy(audio_samples)
693
+ if not audio_samples.dtype.is_floating_point:
694
+ iinfo = torch.iinfo(audio_samples.dtype)
695
+ audio_samples = audio_samples.to(dtype=torch.float64)
696
+ audio_samples -= .5*float(iinfo.min + iinfo.max)
697
+ audio_samples /= .5*float(iinfo.max - iinfo.min)
698
+ return audio_samples
699
+
700
+
701
+ def _extract_key_frames(av_stream: av.video.stream.VideoStream):
702
+ """Extract the list of key frames.
703
+
704
+ Examples
705
+ --------
706
+ >>> import av
707
+ >>> from cutcutcodec.core.io.read_ffmpeg import _extract_key_frames
708
+ >>> with av.open("cutcutcodec/examples/video.mp4") as av_container:
709
+ ... key_frames = list(_extract_key_frames(av_container.streams.video[0]))
710
+ ...
711
+ >>> [f.time for f in key_frames]
712
+ [0.0, 10.0]
713
+ >>>
714
+ """
715
+ assert isinstance(av_stream, av.video.stream.VideoStream), av_stream.__class__.__name__
716
+ av_stream.container.seek(0, backward=True, any_frame=False, stream=av_stream)
717
+ av_stream.codec_context.skip_frame = "NONKEY"
718
+ yield from av_stream.container.decode(av_stream)
719
+ av_stream.container.seek(0, backward=True, any_frame=False, stream=av_stream)
720
+ av_stream.codec_context.skip_frame = "DEFAULT"
721
+
722
+
723
+ def _fix_drift_fill_crop(
724
+ frames_and_dates: list[list[np.ndarray, Fraction, Fraction]],
725
+ drift_max: int,
726
+ rate: int,
727
+ samples: int,
728
+ ) -> list[list[np.ndarray, Fraction, Fraction]]:
729
+ """Slightly shift the audio frames, fill the gap and crop the end.
730
+
731
+ After this function, it is possible to concatenate the frames.
732
+ The gap are filled with the 'nan' value.
733
+
734
+ Parameters
735
+ ----------
736
+ frames_and_dates : list[list[np.ndarray, Fraction, Fraction]]
737
+ The frame data as a numpy array of shape (channels, samples).
738
+ The frames are considered to be all of the same dtype and same
739
+ number of channels.
740
+ The relative date of start and end of each frames.
741
+ The first date of the first sample has to be close to 0.
742
+ All the frames are assumed to be in a monotonic order.
743
+ drift_max : int
744
+ The maximum authorized translation (number of samples).
745
+ rate : int
746
+ The samplerate.
747
+ samples : int
748
+ The final index. In the case where there is a hole at the beginning or at the very end,
749
+ this makes it possible to translate the entirety of the frames by a maximum value of
750
+ `drift_max`/2 in order to fill the hole.
751
+ The last frame can be cropped to reach the exact number of requiered samples.
752
+ The gaps can be filled to reach the exact number of requiered samples.
753
+
754
+ Returns
755
+ -------
756
+ new_frames_and_dates
757
+ Same as input but with somme correction and contiguous frames.
758
+
759
+ Examples
760
+ --------
761
+ >>> from fractions import Fraction
762
+ >>> from pprint import pprint
763
+ >>> import numpy as np
764
+ >>> from cutcutcodec.core.io.read_ffmpeg import _fix_drift_fill_crop
765
+ >>> frames_and_dates = [
766
+ ... [np.zeros((2, 10)), Fraction(1), Fraction(6)], # start after 0 -> padding
767
+ ... [np.ones((2, 10)), Fraction(5), Fraction(10)], # light overlap -> shift
768
+ ... [np.zeros((2, 10)), Fraction(15), Fraction(20)], # big gap -> padding
769
+ ... [np.ones((2, 10)), Fraction(21), Fraction(26)], # light gap -> shift
770
+ ... [np.zeros((2, 10)), Fraction(23), Fraction(28)], # big overlap -> crop
771
+ ... ]
772
+ >>> pprint(_fix_drift_fill_crop(frames_and_dates, drift_max=2, rate=2, samples=60))
773
+ [(array([[nan, nan],
774
+ [nan, nan]]), Fraction(0, 1), Fraction(1, 1)),
775
+ [array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
776
+ [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]),
777
+ Fraction(1, 1),
778
+ Fraction(6, 1)],
779
+ [array([[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
780
+ [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]]),
781
+ Fraction(6, 1),
782
+ Fraction(11, 1)],
783
+ (array([[nan, nan, nan, nan, nan, nan, nan, nan],
784
+ [nan, nan, nan, nan, nan, nan, nan, nan]]),
785
+ Fraction(11, 1),
786
+ Fraction(15, 1)),
787
+ [array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
788
+ [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]),
789
+ Fraction(15, 1),
790
+ Fraction(20, 1)],
791
+ [array([[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
792
+ [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]]),
793
+ Fraction(20, 1),
794
+ Fraction(25, 1)],
795
+ [array([[0., 0., 0., 0., 0., 0.],
796
+ [0., 0., 0., 0., 0., 0.]]),
797
+ Fraction(25, 1),
798
+ Fraction(28, 1)],
799
+ (array([[nan, nan, nan, nan],
800
+ [nan, nan, nan, nan]]),
801
+ Fraction(28, 1),
802
+ Fraction(30, 1))]
803
+ >>>
804
+ """
805
+ dtype = frames_and_dates[0][0].dtype.type
806
+ nbr_channels = frames_and_dates[0][0].shape[0]
807
+
808
+ # drift each slices for perfect concatenation
809
+ for index in range(1, len(frames_and_dates)):
810
+ drift = frames_and_dates[index][1] - frames_and_dates[index-1][2]
811
+ if rate * abs(drift) <= drift_max:
812
+ frames_and_dates[index][1] -= drift
813
+ frames_and_dates[index][2] -= drift
814
+
815
+ # fill the gaps or crop the overlaps
816
+ frames_and_dates.insert(0, [None, None, Fraction(0)]) # fake reference frame
817
+ new_frames_and_dates = []
818
+ for index in range(1, len(frames_and_dates)):
819
+ drift = frames_and_dates[index][1] - frames_and_dates[index-1][2]
820
+ if drift > 0: # case padding
821
+ logging.warning("audio frame drift of %f seconds detected", float(drift))
822
+ nbr_samples = round(drift * rate)
823
+ new_frames_and_dates.append((
824
+ np.full((nbr_channels, nbr_samples), np.nan, dtype=dtype),
825
+ frames_and_dates[index][1] - Fraction(nbr_samples, rate),
826
+ frames_and_dates[index][1],
827
+ ))
828
+ elif drift < 0: # case overlap
829
+ logging.warning("audio frame overlap of %f seconds detected", float(-drift))
830
+ nbr_samples = round(-drift * rate)
831
+ frames_and_dates[index][0] = frames_and_dates[index][0][:, nbr_samples:]
832
+ frames_and_dates[index][1] += Fraction(nbr_samples, rate)
833
+ new_frames_and_dates.append(frames_and_dates[index])
834
+ frames_and_dates = new_frames_and_dates
835
+
836
+ # reach the exact number of samples
837
+ nbr_missing_samples = samples - sum(f.shape[1] for f, _, _ in frames_and_dates)
838
+ if nbr_missing_samples > 0: # case padding at the last end
839
+ frames_and_dates.append((
840
+ np.full((nbr_channels, nbr_missing_samples), np.nan, dtype=dtype),
841
+ frames_and_dates[-1][2],
842
+ frames_and_dates[-1][2] + Fraction(nbr_missing_samples, rate),
843
+ ))
844
+ elif nbr_missing_samples < 0: # case croping at the last end
845
+ nbr_samples = frames_and_dates[-1][0].shape[1] + nbr_missing_samples
846
+ frames_and_dates[-1][0] = frames_and_dates[-1][0][:, :nbr_samples]
847
+ frames_and_dates[-1][2] += Fraction(nbr_missing_samples, rate)
848
+
849
+ return frames_and_dates
850
+
851
+
852
+ def frame_dates(frame: av.frame.Frame) -> tuple[Fraction, typing.Union[None, Fraction]]:
853
+ """Return the accurate time interval of the given frame.
854
+
855
+ Parameters
856
+ ----------
857
+ frame : av.frame.Frame
858
+ The audio or video frame witch we extract the timing information.
859
+
860
+ Returns
861
+ -------
862
+ t_start : Fraction
863
+ The display time of the frame. for audio frame, it corressponds to
864
+ the time of the first sample.
865
+ t_end : Fraction or None
866
+ For audio frame only, the time to switch off the last sample. Return None for video frame.
867
+
868
+ Examples
869
+ --------
870
+ >>> import av
871
+ >>> from cutcutcodec.core.io.read_ffmpeg import frame_dates
872
+ >>> with av.open("cutcutcodec/examples/video.mp4") as av_container:
873
+ ... frame_dates(next(av_container.decode(av_container.streams.video[0])))
874
+ ... frame_dates(next(av_container.decode(av_container.streams.video[0])))
875
+ ...
876
+ (Fraction(0, 1), None)
877
+ (Fraction(1, 25), None)
878
+ >>> with av.open("cutcutcodec/examples/audio_5.1_narration.oga") as av_container:
879
+ ... frame_dates(next(av_container.decode(av_container.streams.audio[0])))
880
+ ... frame_dates(next(av_container.decode(av_container.streams.audio[0])))
881
+ ...
882
+ (Fraction(0, 1), Fraction(4, 125))
883
+ (Fraction(4, 125), Fraction(8, 125))
884
+ >>>
885
+
886
+ Notes
887
+ -----
888
+ For audio frame, include the duration of the last sample.
889
+ For video frame, the duration of the frame is unknown.
890
+ """
891
+ assert isinstance(frame, av.frame.Frame), frame.__class__.__name__
892
+
893
+ if (time_base := frame.time_base) is None:
894
+ start_time = Fraction(frame.time)
895
+ elif (pts := frame.pts) is not None:
896
+ start_time = pts * time_base
897
+ elif (dts := frame.dts) is not None:
898
+ start_time = dts * time_base
899
+ else:
900
+ raise MissingInformation(f"unable to catch the time of the frame {frame}")
901
+ if isinstance(frame, av.audio.frame.AudioFrame):
902
+ stop_time = start_time + Fraction(frame.samples, frame.rate)
903
+ return start_time, stop_time
904
+ return start_time, None