ts2mp4 0.3.2

A library and CLI tool for converting MPEG-TS files to MP4 format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
<!doctype html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>TS to MP4 Converter</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      body {
        font-family:
          -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
          Cantarell, sans-serif;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        min-height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 20px;
      }

      .container {
        background: white;
        border-radius: 20px;
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        padding: 40px;
        max-width: 600px;
        width: 100%;
      }

      h1 {
        color: #333;
        margin-bottom: 10px;
        font-size: 28px;
      }

      .subtitle {
        color: #666;
        margin-bottom: 30px;
        font-size: 14px;
      }

      .upload-area {
        border: 2px dashed #667eea;
        border-radius: 10px;
        padding: 40px;
        text-align: center;
        background: #f8f9ff;
        transition: all 0.3s ease;
        cursor: pointer;
      }

      .upload-area:hover {
        border-color: #764ba2;
        background: #f0f2ff;
      }

      .upload-area.dragover {
        border-color: #764ba2;
        background: #e8eaff;
        transform: scale(1.02);
      }

      .upload-icon {
        font-size: 48px;
        margin-bottom: 15px;
      }

      .upload-text {
        color: #667eea;
        font-weight: 500;
        margin-bottom: 10px;
      }

      .upload-hint {
        color: #999;
        font-size: 12px;
      }

      input[type="file"] {
        display: none;
      }

      .file-info {
        background: #f8f9ff;
        border-radius: 10px;
        padding: 20px;
        margin-top: 20px;
        display: none;
      }

      .file-info.show {
        display: block;
      }

      .file-name {
        color: #333;
        font-weight: 500;
        margin-bottom: 5px;
        word-break: break-all;
      }

      .file-size {
        color: #666;
        font-size: 14px;
      }

      .thumbnail-preview {
        margin-top: 20px;
        padding: 20px;
        background: #f8f9ff;
        border-radius: 10px;
        display: none;
        text-align: center;
      }

      .thumbnail-preview.show {
        display: block;
      }

      .thumbnail-preview h3 {
        color: #333;
        font-size: 16px;
        margin-bottom: 15px;
      }

      .thumbnail-canvas {
        max-width: 100%;
        height: auto;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        background: #000;
      }

      .thumbnail-actions {
        margin-top: 15px;
        display: flex;
        gap: 10px;
        justify-content: center;
      }

      .thumbnail-btn {
        padding: 10px 20px;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        background: #667eea;
        color: white;
        transition: all 0.2s ease;
      }

      .thumbnail-btn:hover {
        background: #5568d3;
        transform: translateY(-1px);
      }

      .button-group {
        display: flex;
        gap: 10px;
        margin-top: 20px;
      }

      button {
        flex: 1;
        padding: 12px 24px;
        border: none;
        border-radius: 8px;
        font-size: 16px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s ease;
      }

      .convert-btn {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
      }

      .convert-btn:hover:not(:disabled) {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
      }

      .convert-btn:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }

      .clear-btn {
        background: #e0e0e0;
        color: #666;
      }

      .clear-btn:hover {
        background: #d0d0d0;
      }

      .progress {
        margin-top: 20px;
        display: none;
      }

      .progress.show {
        display: block;
      }

      .progress-bar {
        width: 100%;
        height: 8px;
        background: #e0e0e0;
        border-radius: 4px;
        overflow: hidden;
      }

      .progress-fill {
        height: 100%;
        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
        width: 0%;
        transition: width 0.3s ease;
      }

      .progress-text {
        text-align: center;
        margin-top: 10px;
        color: #666;
        font-size: 14px;
      }

      .status {
        margin-top: 20px;
        padding: 15px;
        border-radius: 8px;
        display: none;
        font-size: 14px;
      }

      .status.show {
        display: block;
      }

      .status.success {
        background: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
      }

      .status.error {
        background: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
      }

      .status.info {
        background: #d1ecf1;
        color: #0c5460;
        border: 1px solid #bee5eb;
      }

      .footer {
        margin-top: 30px;
        text-align: center;
        color: #999;
        font-size: 12px;
      }

      .footer a {
        color: #667eea;
        text-decoration: none;
      }

      .footer a:hover {
        text-decoration: underline;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <h1>🎬 TS/MP4 Converter</h1>
      <p class="subtitle">
        Convert TS to MP4 or reset MP4 timestamps in your browser
      </p>

      <div class="upload-area" id="uploadArea">
        <div class="upload-icon">📁</div>
        <div class="upload-text">Click to select or drag & drop file</div>
        <div class="upload-hint">Supports .ts and .mp4 files</div>
        <input type="file" id="fileInput" accept=".ts,.mp4" />
      </div>

      <div class="file-info" id="fileInfo">
        <div class="file-name" id="fileName"></div>
        <div class="file-size" id="fileSize"></div>
      </div>

      <div class="thumbnail-preview" id="thumbnailPreview">
        <h3>📸 Thumbnail Preview</h3>
        <canvas id="thumbnailCanvas" class="thumbnail-canvas"></canvas>
        <div class="thumbnail-actions">
          <button class="thumbnail-btn" id="downloadThumbnailBtn">
            💾 Download as JPEG
          </button>
        </div>
      </div>

      <div class="button-group">
        <button class="convert-btn" id="convertBtn" disabled>
          Convert to MP4
        </button>
        <button class="clear-btn" id="clearBtn">Clear</button>
      </div>

      <div class="progress" id="progress">
        <div class="progress-bar">
          <div class="progress-fill" id="progressFill"></div>
        </div>
        <div class="progress-text" id="progressText">Processing...</div>
      </div>

      <div class="status" id="status"></div>

      <div class="footer">
        <p>
          Powered by WebAssembly |
          <a href="https://github.com/aciddust/ts2mp4" target="_blank"
            >GitHub</a
          >
        </p>
      </div>
    </div>

    <script type="module">
      import init, {
        convert_ts_to_mp4_wasm,
        reset_mp4_timestamps_wasm,
        extract_thumbnail_from_ts_wasm,
      } from "./ts2mp4.js";

      let selectedFile = null;
      let thumbnailH264Data = null;

      const uploadArea = document.getElementById("uploadArea");
      const fileInput = document.getElementById("fileInput");
      const fileInfo = document.getElementById("fileInfo");
      const fileName = document.getElementById("fileName");
      const fileSize = document.getElementById("fileSize");
      const thumbnailPreview = document.getElementById("thumbnailPreview");
      const thumbnailCanvas = document.getElementById("thumbnailCanvas");
      const downloadThumbnailBtn = document.getElementById(
        "downloadThumbnailBtn",
      );
      const convertBtn = document.getElementById("convertBtn");
      const clearBtn = document.getElementById("clearBtn");
      const progress = document.getElementById("progress");
      const progressFill = document.getElementById("progressFill");
      const progressText = document.getElementById("progressText");
      const status = document.getElementById("status");

      // Initialize WASM
      async function initialize() {
        try {
          await init();
          console.log("WASM initialized successfully");
        } catch (error) {
          console.error("Failed to initialize WASM:", error);
          showStatus(
            "Failed to initialize converter. Please refresh the page.",
            "error",
          );
        }
      }

      // Format file size
      function formatFileSize(bytes) {
        if (bytes === 0) return "0 Bytes";
        const k = 1024;
        const sizes = ["Bytes", "KB", "MB", "GB"];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return (
          Math.round((bytes / Math.pow(k, i)) * 100) / 100 + " " + sizes[i]
        );
      }

      // Show status message
      function showStatus(message, type = "success") {
        status.textContent = message;
        status.className = `status show ${type}`;
      }

      // Hide status message
      function hideStatus() {
        status.className = "status";
      }

      // Extract and display thumbnail
      async function extractAndShowThumbnail(file) {
        try {
          showStatus("Extracting thumbnail...", "info");

          const arrayBuffer = await file.arrayBuffer();
          const tsData = new Uint8Array(arrayBuffer);

          // Extract H.264 thumbnail
          thumbnailH264Data = extract_thumbnail_from_ts_wasm(tsData);

          // Check if WebCodecs API is available
          if (!window.VideoDecoder) {
            throw new Error("WebCodecs API not supported in this browser");
          }

          // Decode H.264 using WebCodecs API
          let decodedFrame = null;
          const decoder = new VideoDecoder({
            output: (frame) => {
              decodedFrame = frame;
            },
            error: (e) => {
              console.error("VideoDecoder error:", e);
            },
          });

          // Configure decoder for H.264
          decoder.configure({
            codec: "avc1.42E01E", // H.264 Baseline Profile
            optimizeForLatency: true,
          });

          // Decode the H.264 data
          const chunk = new EncodedVideoChunk({
            type: "key",
            timestamp: 0,
            data: thumbnailH264Data,
          });

          decoder.decode(chunk);
          await decoder.flush();

          if (!decodedFrame) {
            throw new Error("Failed to decode frame");
          }

          // Draw to canvas
          const ctx = thumbnailCanvas.getContext("2d");
          thumbnailCanvas.width = decodedFrame.displayWidth;
          thumbnailCanvas.height = decodedFrame.displayHeight;
          ctx.drawImage(decodedFrame, 0, 0);

          // Clean up
          decodedFrame.close();
          decoder.close();

          // Show thumbnail preview
          thumbnailPreview.classList.add("show");
          hideStatus();
        } catch (error) {
          console.error("Thumbnail extraction failed:", error);
          showStatus(
            "Thumbnail extraction failed. You can still convert to MP4.",
            "error",
          );
          setTimeout(hideStatus, 3000);
        }
      }

      // Handle file selection
      async function handleFileSelect(file) {
        if (!file) return;

        const fileName = file.name.toLowerCase();
        const isTS = fileName.endsWith(".ts");
        const isMP4 = fileName.endsWith(".mp4");

        if (!isTS && !isMP4) {
          showStatus("Please select a valid .ts or .mp4 file", "error");
          return;
        }

        selectedFile = file;
        fileName.textContent = `📄 ${file.name}`;
        fileSize.textContent = `Size: ${formatFileSize(file.size)}`;
        fileInfo.classList.add("show");
        convertBtn.disabled = false;

        // Extract and show thumbnail (only for TS files)
        if (isTS) {
          await extractAndShowThumbnail(file);
        } else {
          // MP4 파일은 썸네일 추출 안 함
          thumbnailPreview.classList.remove("show");
        }
      }

      // Download thumbnail as JPEG
      function downloadThumbnailAsJPEG() {
        if (!thumbnailCanvas) return;

        thumbnailCanvas.toBlob(
          (blob) => {
            const url = URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = url;
            a.download = selectedFile.name.replace(/\.ts$/i, "_thumbnail.jpg");
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);

            showStatus("Thumbnail downloaded!", "success");
            setTimeout(hideStatus, 2000);
          },
          "image/jpeg",
          0.9,
        );
      }

      // Clear selection
      function clearSelection() {
        selectedFile = null;
        thumbnailH264Data = null;
        fileInput.value = "";
        fileInfo.classList.remove("show");
        thumbnailPreview.classList.remove("show");
        convertBtn.disabled = true;
        progress.classList.remove("show");
        hideStatus();
      }

      // Download file
      function downloadFile(data, filename) {
        const blob = new Blob([data], { type: "video/mp4" });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      }

      // Convert file
      async function convertFile() {
        if (!selectedFile) return;

        convertBtn.disabled = true;
        clearBtn.disabled = true;
        progress.classList.add("show");
        progressFill.style.width = "0%";
        progressText.textContent = `Reading file...`;
        hideStatus();

        try {
          // Read file
          const arrayBuffer = await selectedFile.arrayBuffer();
          progressFill.style.width = "30%";

          // Convert to Uint8Array
          const fileData = new Uint8Array(arrayBuffer);

          const fileName = selectedFile.name.toLowerCase();
          let mp4Data;
          let outputFileName;

          if (fileName.endsWith(".ts")) {
            // TS to MP4 conversion
            progressText.textContent = `Converting TS to MP4...`;
            mp4Data = convert_ts_to_mp4_wasm(fileData);
            outputFileName = selectedFile.name.replace(/\.ts$/i, ".mp4");
          } else if (fileName.endsWith(".mp4")) {
            // MP4 timestamp reset
            progressText.textContent = `Resetting MP4 timestamps...`;
            mp4Data = reset_mp4_timestamps_wasm(fileData);
            outputFileName = selectedFile.name.replace(/\.mp4$/i, "_fixed.mp4");
          } else {
            throw new Error("Unsupported file type");
          }

          progressFill.style.width = "90%";
          progressText.textContent = `Preparing download...`;

          // Download result
          downloadFile(mp4Data, outputFileName);

          progressFill.style.width = "100%";
          progressText.textContent = `Complete!`;
          showStatus(`Successfully converted to ${outputFileName}`, "success");
        } catch (error) {
          console.error("Conversion error:", error);
          showStatus(`Conversion failed: ${error.message}`, "error");
        } finally {
          convertBtn.disabled = false;
          clearBtn.disabled = false;
          setTimeout(() => {
            progress.classList.remove("show");
          }, 2000);
        }
      }

      // Event listeners
      uploadArea.addEventListener("click", () => fileInput.click());

      fileInput.addEventListener("change", (e) => {
        handleFileSelect(e.target.files[0]);
      });

      // Drag and drop
      uploadArea.addEventListener("dragover", (e) => {
        e.preventDefault();
        uploadArea.classList.add("dragover");
      });

      uploadArea.addEventListener("dragleave", () => {
        uploadArea.classList.remove("dragover");
      });

      uploadArea.addEventListener("drop", (e) => {
        e.preventDefault();
        uploadArea.classList.remove("dragover");
        handleFileSelect(e.dataTransfer.files[0]);
      });

      convertBtn.addEventListener("click", convertFile);
      clearBtn.addEventListener("click", clearSelection);
      downloadThumbnailBtn.addEventListener("click", downloadThumbnailAsJPEG);

      // Initialize on load
      initialize();
    </script>
  </body>
</html>