File size: 17,002 Bytes
87fae93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a6035e
87fae93
9a6035e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87fae93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a6035e
 
 
 
 
87fae93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Create Video!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pip install opencv-python opencv-python-headless  # If you do not need GUI features\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Creating the demo\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import subprocess\n",
    "import logging\n",
    "from glob import glob\n",
    "import re\n",
    "\n",
    "# Configure logging\n",
    "logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\n",
    "logger = logging.getLogger(__name__)\n",
    "\n",
    "def create_near_lossless_h265_video(input_folder, output_file, fps=30, frames_per_image=3, crf=10):\n",
    "    if not os.path.exists(input_folder):\n",
    "        logger.error(f\"Input folder '{input_folder}' does not exist.\")\n",
    "        return\n",
    "\n",
    "    png_files = sorted(glob(os.path.join(input_folder, '*.png')))\n",
    "    if not png_files:\n",
    "        logger.error(f\"No PNG files found in {input_folder}\")\n",
    "        return\n",
    "\n",
    "    num_images = len(png_files)\n",
    "    logger.info(f\"Found {num_images} PNG files.\")\n",
    "\n",
    "    # Calculate expected duration\n",
    "    expected_duration = (num_images * frames_per_image) / fps\n",
    "    logger.info(f\"Expected duration: {expected_duration:.2f} seconds\")\n",
    "\n",
    "    # FFmpeg command for near-lossless 10-bit H.265 encoding\n",
    "    ffmpeg_command = [\n",
    "        'ffmpeg',\n",
    "        '-framerate', f'{1/(frames_per_image/fps)}',  # Input framerate\n",
    "        '-i', os.path.join(input_folder, '%*.png'),   # Input pattern for all PNG files\n",
    "        '-fps_mode', 'vfr',\n",
    "        '-pix_fmt', 'yuv420p10le',  # 10-bit pixel format\n",
    "        '-c:v', 'libx265',          # Use libx265 encoder\n",
    "        '-preset', 'slow',      # Slowest preset for best compression efficiency\n",
    "        '-crf', str(crf),           # Constant Rate Factor (0-51, lower is higher quality)\n",
    "        '-profile:v', 'main10',     # 10-bit profile\n",
    "        '-x265-params', f\"log-level=error:keyint={2*fps}:min-keyint={fps}:scenecut=0\",  # Ensure consistent encoding\n",
    "        '-tag:v', 'hvc1',\n",
    "        '-y',\n",
    "        output_file\n",
    "    ]\n",
    "\n",
    "    try:\n",
    "        logger.info(\"Starting near-lossless 10-bit video creation...\")\n",
    "        process = subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)\n",
    "        \n",
    "        encoding_speed = None\n",
    "        \n",
    "        for line in process.stderr:\n",
    "            print(line, end='')  # Print FFmpeg output in real-time\n",
    "            \n",
    "            speed_match = re.search(r'speed=\\s*([\\d.]+)x', line)\n",
    "            if speed_match:\n",
    "                encoding_speed = float(speed_match.group(1))\n",
    "        \n",
    "        process.wait()\n",
    "        \n",
    "        if encoding_speed:\n",
    "            logger.info(f\"Encoding speed: {encoding_speed:.2f}x\")\n",
    "        \n",
    "        if process.returncode == 0:\n",
    "            logger.info(f\"Video created successfully: {output_file}\")\n",
    "            \n",
    "            probe_command = ['ffprobe', '-v', 'error', '-show_entries', 'stream=codec_name,width,height,duration,bit_rate,profile', '-of', 'default=noprint_wrappers=1', output_file]\n",
    "            probe_result = subprocess.run(probe_command, capture_output=True, text=True)\n",
    "            logger.info(f\"Video properties:\\n{probe_result.stdout}\")\n",
    "            \n",
    "            duration_command = ['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', output_file]\n",
    "            duration_result = subprocess.run(duration_command, capture_output=True, text=True)\n",
    "            actual_duration = float(duration_result.stdout.strip())\n",
    "            logger.info(f\"Actual video duration: {actual_duration:.2f} seconds\")\n",
    "            if abs(actual_duration - expected_duration) > 1:\n",
    "                logger.warning(f\"Video duration mismatch. Expected: {expected_duration:.2f}, Actual: {actual_duration:.2f}\")\n",
    "            else:\n",
    "                logger.info(\"Video duration check passed.\")\n",
    "        else:\n",
    "            logger.error(f\"Error during video creation. FFmpeg returned code {process.returncode}\")\n",
    "\n",
    "    except subprocess.CalledProcessError as e:\n",
    "        logger.error(f\"Error during video creation: {e}\")\n",
    "        logger.error(f\"FFmpeg error output:\\n{e.stderr}\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    input_folder = 'train'\n",
    "    output_file = 'near_lossless_output.mp4'\n",
    "    fps = 30\n",
    "    frames_per_image = 3\n",
    "    crf = 18  # Very low CRF for near-lossless quality (0 is lossless, but often overkill)\n",
    "\n",
    "    create_near_lossless_h265_video(input_folder, output_file, fps, frames_per_image, crf)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Transfer File"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-08-12 22:25:58,907 - INFO - Found 1000 PNG files.\n",
      "2024-08-12 22:25:58,908 - INFO - Expected duration: 50.00 seconds\n",
      "2024-08-12 22:25:58,909 - INFO - Using ProRes codec (near-lossless)\n",
      "2024-08-12 22:25:58,909 - INFO - Starting high-quality video creation with prores codec...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ffmpeg version 7.0.2 Copyright (c) 2000-2024 the FFmpeg developers\n",
      "  built with Apple clang version 15.0.0 (clang-1500.3.9.4)\n",
      "  configuration: --prefix=/opt/homebrew/Cellar/ffmpeg/7.0.2 --enable-shared --enable-pthreads --enable-version3 --cc=clang --host-cflags= --host-ldflags='-Wl,-ld_classic' --enable-ffplay --enable-gnutls --enable-gpl --enable-libaom --enable-libaribb24 --enable-libbluray --enable-libdav1d --enable-libharfbuzz --enable-libjxl --enable-libmp3lame --enable-libopus --enable-librav1e --enable-librist --enable-librubberband --enable-libsnappy --enable-libsrt --enable-libssh --enable-libsvtav1 --enable-libtesseract --enable-libtheora --enable-libvidstab --enable-libvmaf --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libxvid --enable-lzma --enable-libfontconfig --enable-libfreetype --enable-frei0r --enable-libass --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libspeex --enable-libsoxr --enable-libzmq --enable-libzimg --disable-libjack --disable-indev=jack --enable-videotoolbox --enable-audiotoolbox --enable-neon\n",
      "  libavutil      59.  8.100 / 59.  8.100\n",
      "  libavcodec     61.  3.100 / 61.  3.100\n",
      "  libavformat    61.  1.100 / 61.  1.100\n",
      "  libavdevice    61.  1.100 / 61.  1.100\n",
      "  libavfilter    10.  1.100 / 10.  1.100\n",
      "  libswscale      8.  1.100 /  8.  1.100\n",
      "  libswresample   5.  1.100 /  5.  1.100\n",
      "  libpostproc    58.  1.100 / 58.  1.100\n",
      "[image2 @ 0x13d61ef40] Pattern type 'glob_sequence' is deprecated: use pattern_type 'glob' instead\n",
      "Input #0, image2, from 'train/%*.png':\n",
      "  Duration: 00:00:50.00, start: 0.000000, bitrate: N/A\n",
      "  Stream #0:0: Video: png, rgb24(pc, gbr/unknown/unknown), 768x1024, 20 fps, 20 tbr, 20 tbn\n",
      "Stream mapping:\n",
      "  Stream #0:0 -> #0:0 (png (native) -> prores (prores_ks))\n",
      "Press [q] to stop, [?] for help\n",
      "Output #0, mov, to 'high_quality_output.mov':\n",
      "  Metadata:\n",
      "    encoder         : Lavf61.1.100\n",
      "  Stream #0:0: Video: prores (Proxy) (apco / 0x6F637061), yuv444p10le(progressive), 768x1024, q=2-31, 200 kb/s, 20 fps, 10240 tbn\n",
      "      Metadata:\n",
      "        encoder         : Lavc61.3.100 prores_ks\n",
      "frame=   56 fps=0.0 q=-0.0 size=    7936KiB time=00:00:02.80 bitrate=23218.6kbits/s speed=5.56x    \n",
      "frame=  125 fps=124 q=-0.0 size=   17664KiB time=00:00:06.25 bitrate=23152.6kbits/s speed=6.19x    \n",
      "frame=  199 fps=131 q=-0.0 size=   28416KiB time=00:00:09.95 bitrate=23395.4kbits/s speed=6.57x    \n",
      "frame=  278 fps=138 q=-0.0 size=   39936KiB time=00:00:13.90 bitrate=23536.4kbits/s speed=6.88x    \n",
      "frame=  352 fps=139 q=-0.0 size=   50944KiB time=00:00:17.60 bitrate=23712.1kbits/s speed=6.97x    \n",
      "frame=  419 fps=138 q=-0.0 size=   60416KiB time=00:00:20.95 bitrate=23624.3kbits/s speed=6.92x    \n",
      "frame=  485 fps=137 q=-0.0 size=   70144KiB time=00:00:24.25 bitrate=23695.7kbits/s speed=6.87x    \n",
      "frame=  561 fps=139 q=-0.0 size=   81152KiB time=00:00:28.05 bitrate=23700.4kbits/s speed=6.96x    \n",
      "frame=  631 fps=139 q=-0.0 size=   91136KiB time=00:00:31.55 bitrate=23663.6kbits/s speed=6.96x    \n",
      "frame=  711 fps=141 q=-0.0 size=  102912KiB time=00:00:35.55 bitrate=23714.6kbits/s speed=7.06x    \n",
      "frame=  784 fps=141 q=-0.0 size=  113408KiB time=00:00:39.20 bitrate=23700.0kbits/s speed=7.07x    \n",
      "frame=  864 fps=143 q=-0.0 size=  124928KiB time=00:00:43.20 bitrate=23690.1kbits/s speed=7.14x    \n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-08-12 22:26:05,979 - INFO - Encoding speed: 7.3100x\n",
      "2024-08-12 22:26:05,980 - INFO - Video created successfully: high_quality_output.mov\n",
      "2024-08-12 22:26:06,034 - INFO - Video properties:\n",
      "codec_name=prores\n",
      "width=768\n",
      "height=1024\n",
      "duration=50.000000\n",
      "bit_rate=23781117\n",
      "\n",
      "2024-08-12 22:26:06,076 - INFO - Actual video duration: 50.00 seconds\n",
      "2024-08-12 22:26:06,076 - INFO - Video duration check passed.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "frame=  944 fps=144 q=-0.0 size=  136704KiB time=00:00:47.20 bitrate=23726.3kbits/s speed= 7.2x    \n",
      "[out#0/mov @ 0x13d70efa0] video:145148KiB audio:0KiB subtitle:0KiB other streams:0KiB global headers:0KiB muxing overhead: 0.004134%\n",
      "frame= 1000 fps=146 q=-0.0 Lsize=  145154KiB time=00:00:50.00 bitrate=23782.1kbits/s speed=7.31x    \n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import subprocess\n",
    "import logging\n",
    "from glob import glob\n",
    "import re\n",
    "\n",
    "# Configure logging\n",
    "logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\n",
    "logger = logging.getLogger(__name__)\n",
    "\n",
    "def create_high_quality_video(input_folder, output_file, fps=60, frames_per_image=3, codec='ffv1'):\n",
    "    if not os.path.exists(input_folder):\n",
    "        logger.error(f\"Input folder '{input_folder}' does not exist.\")\n",
    "        return\n",
    "\n",
    "    png_files = sorted(glob(os.path.join(input_folder, '*.png')))\n",
    "    if not png_files:\n",
    "        logger.error(f\"No PNG files found in {input_folder}\")\n",
    "        return\n",
    "\n",
    "    num_images = len(png_files)\n",
    "    logger.info(f\"Found {num_images} PNG files.\")\n",
    "\n",
    "    # Calculate expected duration\n",
    "    expected_duration = (num_images * frames_per_image) / fps\n",
    "    logger.info(f\"Expected duration: {expected_duration:.2f} seconds\")\n",
    "\n",
    "    # Base FFmpeg command\n",
    "    ffmpeg_command = [\n",
    "        'ffmpeg',\n",
    "        '-framerate', f'{1/(frames_per_image/fps)}',  # Input framerate\n",
    "        '-i', os.path.join(input_folder, '%*.png'),   # Input pattern for all PNG files\n",
    "        '-fps_mode', 'vfr',\n",
    "    ]\n",
    "\n",
    "    # Codec-specific settings\n",
    "    if codec == 'ffv1':\n",
    "        output_file = output_file.rsplit('.', 1)[0] + '.mkv'  # FFV1 is typically used with MKV container\n",
    "        ffmpeg_command.extend([\n",
    "            '-c:v', 'ffv1',\n",
    "            '-level', '3',\n",
    "            '-coder', '1',\n",
    "            '-context', '1',\n",
    "            '-g', '1',\n",
    "            '-slices', '24',\n",
    "            '-slicecrc', '1'\n",
    "        ])\n",
    "        logger.info(\"Using FFV1 codec (lossless)\")\n",
    "    elif codec == 'prores':\n",
    "        output_file = output_file.rsplit('.', 1)[0] + '.mov'  # ProRes is typically used with MOV container\n",
    "        ffmpeg_command.extend([\n",
    "    '-c:v', 'prores_ks',\n",
    "    '-profile:v', 'proxy',  # Use ProRes 422 Proxy profile\n",
    "    '-qscale:v', '11'  # Adjust quality scale; higher values mean lower quality. 11 is typical for proxy quality.\n",
    "])\n",
    "\n",
    "        logger.info(\"Using ProRes codec (near-lossless)\")\n",
    "    else:\n",
    "        logger.error(f\"Unsupported codec: {codec}\")\n",
    "        return\n",
    "\n",
    "    ffmpeg_command.extend(['-y', output_file])\n",
    "\n",
    "    try:\n",
    "        logger.info(f\"Starting high-quality video creation with {codec} codec...\")\n",
    "        process = subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)\n",
    "        \n",
    "        encoding_speed = None\n",
    "        \n",
    "        for line in process.stderr:\n",
    "            print(line, end='')  # Print FFmpeg output in real-time\n",
    "            \n",
    "            speed_match = re.search(r'speed=\\s*([\\d.]+)x', line)\n",
    "            if speed_match:\n",
    "                encoding_speed = float(speed_match.group(1))\n",
    "        \n",
    "        process.wait()\n",
    "        \n",
    "        if encoding_speed:\n",
    "            logger.info(f\"Encoding speed: {encoding_speed:.4f}x\")\n",
    "        \n",
    "        if process.returncode == 0:\n",
    "            logger.info(f\"Video created successfully: {output_file}\")\n",
    "            \n",
    "            probe_command = ['ffprobe', '-v', 'error', '-show_entries', 'stream=codec_name,width,height,duration,bit_rate', '-of', 'default=noprint_wrappers=1', output_file]\n",
    "            probe_result = subprocess.run(probe_command, capture_output=True, text=True)\n",
    "            logger.info(f\"Video properties:\\n{probe_result.stdout}\")\n",
    "            \n",
    "            duration_command = ['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', output_file]\n",
    "            duration_result = subprocess.run(duration_command, capture_output=True, text=True)\n",
    "            actual_duration = float(duration_result.stdout.strip())\n",
    "            logger.info(f\"Actual video duration: {actual_duration:.2f} seconds\")\n",
    "            if abs(actual_duration - expected_duration) > 1:\n",
    "                logger.warning(f\"Video duration mismatch. Expected: {expected_duration:.2f}, Actual: {actual_duration:.2f}\")\n",
    "            else:\n",
    "                logger.info(\"Video duration check passed.\")\n",
    "        else:\n",
    "            logger.error(f\"Error during video creation. FFmpeg returned code {process.returncode}\")\n",
    "\n",
    "    except subprocess.CalledProcessError as e:\n",
    "        logger.error(f\"Error during video creation: {e}\")\n",
    "        logger.error(f\"FFmpeg error output:\\n{e.stderr}\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    input_folder = 'train'\n",
    "    output_file = 'high_quality_output.mp4'\n",
    "    fps = 60\n",
    "    frames_per_image = 3\n",
    "    codec = 'prores'  # Options: 'ffv1' (lossless) or 'prores' (near-lossless)\n",
    "\n",
    "    create_high_quality_video(input_folder, output_file, fps, frames_per_image, codec)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}