Если нравится наш проект, пожалуйста, поддержите любой приемлимой суммой чтобы помочь оплачивать хостинг. Спасибо!
Навигация  🇷🇺RU | 🇬🇧EN

Новые комментарии

Последние файлы

Пожертвования
[ Через Yoo.Money ]
(бывшие Яндекс.Деньги) 410011494554572

Contact us if you wish
PayPal or BitCoin donation

Наши друзья

Файловый архив

This software and its source code (if available) are licensed under the Apache-2.0 license (unless otherwise specified) which DOES NOT APPLY to any third-party code (such as zlib for example) and borrowed Assembler code (ripped code from other software executable files).


/* dvbang2ogv.c
 * ANSI C / C89, Visual Studio 2008 friendly
 * License: MIT, Copyright 2026 Lumis
 * v1.5 uses stdint.h
 *
 * Converts proprietary "DV!!" .dv container into .ogv (OGM).
 * Video: MPEG-4 Part 2 (VOP start code 00 00 01 B6) kept byte-exact.
 * Audio: Ogg/Vorbis stream bytes kept byte-exact (no re-encode).
 *
 * Container format (as reverse engineered):
 *
 *  dvf_head (0x4C bytes, little-endian u32 fields):
 *    magic     = "DV!!" (0x21215644 LE)
 *    width     = hdr[4]
 *    height    = hdr[5]
 *    frames2   = hdr[7]  (count of items/frames)
 *    channels  = hdr[8]  (0 no audio, 2 stereo)
 *    asize1st  = hdr[9]  (used bytes in preroll area; rest is zero padding)
 *
 *  then: item table: frames2 * 0x14 bytes:
 *    fsize: total packet bytes, with keyframe flag in bit31
 *    vsize: video bytes inside packet
 *    zero1
 *    dsize: audio bytes inside packet (in many files dsize == total - vsize)
 *    zero2
 *
 *  then: preroll audio region of 0xC000 bytes may exist (often padded with zeros);
 *        only first asize1st bytes are meaningful audio bytes.
 *
 *  then: frames2 packets of (fsize & 0x7fffffff) bytes.
 *        packet layout:
 *            video[vsize] + blob[blob_size] + audio[audio_size]
 *
 *  where:
 *        tail      = total - vsize
 *        audio_size= min(dsize, tail)   <-- critical fix (53-99.dv needs this)
 *        blob_size = tail - audio_size
 *
 * OGV/OGM mux:
 *  - Copy Vorbis BOS page unchanged (byte-exact)
 *  - Create OGM video BOS page (stream_header, subtype "XVID")
 *  - Create OGM video comment page
 *  - Copy remaining Vorbis header pages unchanged (until 3 Vorbis packets end)
 *  - Interleave:
 *        at = audio_page.granule / sample_rate
 *        emit video frames while ((v_i+1)/fps) <= at + (0.5/fps)
 *        then copy audio page
 *    Finally flush remaining video frames.
 *
 * Determinism:
 *  - video serial hardcoded to 0xC0DEC0DE (xor if equals audio serial).
 *
 * Build (small-ish EXE):
 *  cl /O1 /Os /GL /GS- /Gy /GR- /EHsc- /MD dvbang2ogv.c /link /LTCG /OPT:REF /OPT:ICF /SUBSYSTEM:CONSOLE,5.01
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* ----- Standard integer types where available ----- */
#if defined(_MSC_VER) && (_MSC_VER < 1600)
typedef unsigned char       uint8_t;
typedef unsigned short      uint16_t;
typedef unsigned int        uint32_t;
typedef unsigned __int64    uint64_t;
#else
#include <stdint.h>
#endif

#ifdef _MSC_VER
#ifndef snprintf
#define snprintf _snprintf
#endif
#endif

#define MAGIC_DV_LE         0x21215644UL /* "DV!!" LE */
#define PREROLL_BLOCK_SIZE  0xC000UL
#define VIDEO_SERIAL_FIXED  0xC0DEC0DEUL

static void die(const char* msg) { fprintf(stderr, "ERROR: %s\n", msg); exit(2); }
static void die2(const char* msg, const char* more) { fprintf(stderr, "ERROR: %s%s\n", msg, more ? more : ""); exit(2); }

/* LE helpers */
static uint32_t rd32le(const uint8_t* p){ return (uint32_t)p[0] | ((uint32_t)p[1]<<8) | ((uint32_t)p[2]<<16) | ((uint32_t)p[3]<<24); }
static uint64_t rd64le(const uint8_t* p){
  uint64_t v=0;
  v |= (uint64_t)p[0];
  v |= (uint64_t)p[1]<<8;
  v |= (uint64_t)p[2]<<16;
  v |= (uint64_t)p[3]<<24;
  v |= (uint64_t)p[4]<<32;
  v |= (uint64_t)p[5]<<40;
  v |= (uint64_t)p[6]<<48;
  v |= (uint64_t)p[7]<<56;
  return v;
}
static void wr32le(uint8_t* p, uint32_t v){ p[0]=(uint8_t)v; p[1]=(uint8_t)(v>>8); p[2]=(uint8_t)(v>>16); p[3]=(uint8_t)(v>>24); }
static void wr64le(uint8_t* p, uint64_t v){
  p[0]=(uint8_t)v; p[1]=(uint8_t)(v>>8); p[2]=(uint8_t)(v>>16); p[3]=(uint8_t)(v>>24);
  p[4]=(uint8_t)(v>>32); p[5]=(uint8_t)(v>>40); p[6]=(uint8_t)(v>>48); p[7]=(uint8_t)(v>>56);
}

/* Buf */
typedef struct Buf { uint8_t* p; uint32_t len; uint32_t cap; } Buf;
static void buf_init(Buf* b){ b->p=0; b->len=0; b->cap=0; }
static void buf_reserve(Buf* b, uint32_t need){
  uint32_t ncap; uint8_t* np;
  if (need <= b->cap) return;
  ncap = b->cap ? (b->cap + (b->cap>>1) + 64) : 256;
  if (ncap < need) ncap = need;
  np = (uint8_t*)realloc(b->p, (size_t)ncap);
  if (!np) die("Out of memory");
  b->p=np; b->cap=ncap;
}
static void buf_append(Buf* b, const uint8_t* data, uint32_t n){
  if (!n) return;
  buf_reserve(b, b->len + n);
  memcpy(b->p + b->len, data, (size_t)n);
  b->len += n;
}
static void buf_append_u8(Buf* b, uint8_t v){
  buf_reserve(b, b->len + 1);
  b->p[b->len++] = v;
}
static void buf_free(Buf* b){ if (b->p) free(b->p); b->p=0; b->len=0; b->cap=0; }

/* Read file */
static uint8_t* read_file_all(const char* path, uint32_t* out_len){
  FILE* f; long sz; uint8_t* data; size_t got;
  f = fopen(path, "rb"); if (!f) return 0;
  fseek(f, 0, SEEK_END); sz = ftell(f);
  if (sz < 0) { fclose(f); return 0; }
  fseek(f, 0, SEEK_SET);
  data = (uint8_t*)malloc((size_t)sz);
  if (!data) { fclose(f); return 0; }
  got = (sz>0) ? fread(data, 1, (size_t)sz, f) : 0;
  fclose(f);
  if ((long)got != sz) { free(data); return 0; }
  *out_len = (uint32_t)sz;
  return data;
}

/* Ogg CRC */
static uint32_t CRC_TABLE[256];
static void crc_table_init(void){
  uint32_t poly=0x04C11DB7UL, i, j, r;
  for (i=0;i<256;i++){
    r = i<<24;
    for (j=0;j<8;j++){
      if (r & 0x80000000UL) r = (r<<1) ^ poly;
      else r <<= 1;
    }
    CRC_TABLE[i]=r;
  }
}
static uint32_t ogg_crc(const uint8_t* page, uint32_t len){
  uint32_t crc=0, i;
  for (i=0;i<len;i++){
    uint8_t b=page[i];
    crc = (crc<<8) ^ CRC_TABLE[((crc>>24) ^ b) & 0xFF];
  }
  return crc;
}

/* Ogg page writer */
static void ogg_build_page_raw(Buf* out,
                               const uint8_t* segs, uint32_t seg_count,
                               const uint8_t* body, uint32_t body_len,
                               uint32_t serial, uint32_t seq,
                               uint64_t granule, uint8_t header_type)
{
  uint8_t hdr[27];
  Buf page;
  uint32_t crc;

  memset(hdr, 0, sizeof(hdr));
  hdr[0]='O'; hdr[1]='g'; hdr[2]='g'; hdr[3]='S';
  hdr[4]=0;
  hdr[5]=header_type;
  wr64le(hdr+6, granule);
  wr32le(hdr+14, serial);
  wr32le(hdr+18, seq);
  wr32le(hdr+22, 0);
  hdr[26]=(uint8_t)seg_count;

  buf_init(&page);
  buf_append(&page, hdr, 27);
  buf_append(&page, segs, seg_count);
  buf_append(&page, body, body_len);

  crc = ogg_crc(page.p, page.len);
  wr32le(page.p + 22, crc);

  buf_append(out, page.p, page.len);
  buf_free(&page);
}

/* Packet->pages splitting (fixes 255 segments limit) */
static void ogg_write_packet_split(Buf* out,
                                   const uint8_t* pkt, uint32_t pkt_len,
                                   uint32_t serial, uint32_t* io_seq,
                                   uint64_t granule_last,
                                   uint8_t header_type_first,
                                   uint8_t header_type_last)
{
  uint32_t pos=0, seq=*io_seq;
  const uint32_t max_body = 255UL*255UL;

  while (pos < pkt_len){
    uint32_t rem = pkt_len - pos;

    if (rem <= max_body){
      uint8_t segs[255]; uint32_t seg_count=0; uint32_t n=rem; uint8_t ht;
      while (n >= 255){ segs[seg_count++] = 255; n -= 255; }
      segs[seg_count++] = (uint8_t)n;

      ht = (pos==0) ? (uint8_t)(header_type_first | header_type_last)
                    : (uint8_t)(0x01 | header_type_last);

      ogg_build_page_raw(out, segs, seg_count, pkt + pos, rem, serial, seq, granule_last, ht);
      seq++;
      break;
    } else {
      uint8_t segs_full[255]; uint32_t i; uint8_t ht;
      for (i=0;i<255;i++) segs_full[i]=255;
      ht = (pos==0) ? header_type_first : 0x01;
      ogg_build_page_raw(out, segs_full, 255, pkt + pos, max_body, serial, seq, 0, ht);
      seq++;
      pos += max_body;
    }
  }

  *io_seq = seq;
}

/* Ogg page parse (audio only, for timestamps + raw copy) */
typedef struct OggPage {
  uint8_t  header_type;
  uint64_t granule;
  uint32_t serial;
  uint32_t seq;
  uint8_t* segtable; uint32_t segtable_len;
  uint8_t* body;     uint32_t body_len;
  uint8_t* bytes;    uint32_t bytes_len;
} OggPage;

static OggPage* ogg_parse_pages(const uint8_t* data, uint32_t len, uint32_t* out_count){
  OggPage* pages; uint32_t cap=64, count=0, i=0;
  pages = (OggPage*)calloc((size_t)cap, sizeof(OggPage));
  if (!pages) die("Out of memory");

  while (1){
    uint32_t j,k,seg_off,body_off,body_len,end; int found; uint8_t nseg;

    found=0;
    for (j=i; j+4<=len; j++){
      if (data[j]=='O' && data[j+1]=='g' && data[j+2]=='g' && data[j+3]=='S'){ found=1; break; }
    }
    if (!found) break;
    if (j+27 > len) break;

    nseg = data[j+26];
    seg_off = j+27;
    body_off = seg_off + (uint32_t)nseg;
    if (body_off > len) break;

    body_len=0;
    for (k=0;k<(uint32_t)nseg;k++) body_len += data[seg_off+k];
    end = body_off + body_len;
    if (end > len) break;

    if (count >= cap){
      OggPage* np;
      cap = cap + cap/2 + 32;
      np = (OggPage*)realloc(pages, (size_t)cap*sizeof(OggPage));
      if (!np) die("Out of memory");
      pages=np;
      memset(pages+count, 0, (size_t)(cap-count)*sizeof(OggPage));
    }

    pages[count].header_type = data[j+5];
    pages[count].granule = rd64le(data + j + 6);
    pages[count].serial  = rd32le(data + j + 14);
    pages[count].seq     = rd32le(data + j + 18);

    pages[count].segtable_len = (uint32_t)nseg;
    pages[count].segtable = (uint8_t*)malloc((size_t)nseg);
    pages[count].body = (uint8_t*)malloc((size_t)body_len);
    pages[count].bytes_len = end - j;
    pages[count].bytes = (uint8_t*)malloc((size_t)pages[count].bytes_len);
    if (!pages[count].segtable || !pages[count].body || !pages[count].bytes) die("Out of memory");

    memcpy(pages[count].segtable, data + seg_off, (size_t)nseg);
    memcpy(pages[count].body, data + body_off, (size_t)body_len);
    memcpy(pages[count].bytes, data + j, (size_t)pages[count].bytes_len);
    pages[count].body_len = body_len;

    count++;
    i = end;
  }

  *out_count = count;
  return pages;
}

static void ogg_free_pages(OggPage* pages, uint32_t count){
  uint32_t i;
  if (!pages) return;
  for (i=0;i<count;i++){
    if (pages[i].segtable) free(pages[i].segtable);
    if (pages[i].body) free(pages[i].body);
    if (pages[i].bytes) free(pages[i].bytes);
  }
  free(pages);
}

/* Vorbis sample rate detection */
static uint32_t vorbis_detect_sample_rate(const OggPage* pages, uint32_t count){
  Buf cur; uint32_t i,sidx;
  buf_init(&cur);

  for (i=0;i<count;i++){
    uint32_t off=0;
    for (sidx=0;sidx<pages[i].segtable_len;sidx++){
      uint8_t s = pages[i].segtable[sidx];
      buf_append(&cur, pages[i].body + off, (uint32_t)s);
      off += (uint32_t)s;

      if (s < 255){
        if (cur.len >= 16 &&
            cur.p[0]==0x01 &&
            cur.p[1]=='v' && cur.p[2]=='o' && cur.p[3]=='r' &&
            cur.p[4]=='b' && cur.p[5]=='i' && cur.p[6]=='s')
        {
          uint32_t sr = rd32le(cur.p + 12);
          buf_free(&cur);
          return sr;
        }
        cur.len = 0;
      }
    }
  }

  buf_free(&cur);
  return 0;
}

static uint32_t vorbis_header_end_page_index(const OggPage* pages, uint32_t count){
  uint32_t pkt=0,i,s;
  for (i=0;i<count;i++){
    for (s=0;s<pages[i].segtable_len;s++){
      if (pages[i].segtable[s] < 255){
        pkt++;
        if (pkt >= 3) return i;
      }
    }
  }
  return count ? (count-1) : 0;
}

/* DV extraction */
typedef struct FrameMeta { uint8_t key; } FrameMeta;

static void dv_extract(const uint8_t* dv, uint32_t dv_len,
                       uint32_t* out_w, uint32_t* out_h,
                       uint32_t* out_frames, uint32_t* out_channels,
                       uint8_t** out_video_es, uint32_t* out_video_es_len,
                       uint8_t** out_audio_ogg, uint32_t* out_audio_ogg_len,
                       FrameMeta** out_meta)
{
  uint32_t w, h, frames2, channels, asize1st;
  uint32_t table_off, table_len, preroll_off;
  uint32_t i;
  uint64_t sum_total;
  uint32_t data_off_with_preroll, data_off_no_preroll, data_off;
  int has_preroll;

  Buf video, audio;
  FrameMeta* meta;
  uint32_t pos;

  if (dv_len < 0x4C) die("Input too small for DV!! header");
  if (rd32le(dv + 0) != MAGIC_DV_LE) die("Bad DV!! signature");

  w        = rd32le(dv + 16);
  h        = rd32le(dv + 20);
  frames2  = rd32le(dv + 28);
  channels = rd32le(dv + 32);
  asize1st = rd32le(dv + 36);

  table_off = 0x4C;
  table_len = frames2 * 0x14UL;
  preroll_off = table_off + table_len;

  if (dv_len < preroll_off) die("Truncated: frame table");

  sum_total = 0;
  for (i=0;i<frames2;i++){
    uint32_t base = table_off + i * 0x14UL;
    uint32_t fsize = rd32le(dv + base + 0);
    sum_total += (uint64_t)(fsize & 0x7FFFFFFFUL);
  }

  data_off_no_preroll   = preroll_off;
  data_off_with_preroll = preroll_off + PREROLL_BLOCK_SIZE;

  if ((uint64_t)data_off_with_preroll + sum_total == (uint64_t)dv_len) has_preroll = 1;
  else if ((uint64_t)data_off_no_preroll + sum_total == (uint64_t)dv_len) has_preroll = 0;
  else {
    if (data_off_with_preroll < dv_len && (uint64_t)data_off_with_preroll + sum_total < (uint64_t)dv_len) {
      fprintf(stderr, "WARNING: size mismatch; assuming preroll block present.\n");
      has_preroll = 1;
    } else if ((uint64_t)data_off_no_preroll + sum_total < (uint64_t)dv_len) {
      fprintf(stderr, "WARNING: size mismatch; assuming no preroll block.\n");
      has_preroll = 0;
    } else {
      die("Cannot determine payload offset (size mismatch too large)");
    }
  }

  data_off = has_preroll ? data_off_with_preroll : data_off_no_preroll;

  if (channels == 0) asize1st = 0;
  else {
    if (asize1st == 0xFFFFFFFFUL) asize1st = 0;
    if (asize1st > PREROLL_BLOCK_SIZE) {
      fprintf(stderr, "WARNING: asize1st > 0xC000; clamping.\n");
      asize1st = PREROLL_BLOCK_SIZE;
    }
  }

  buf_init(&video);
  buf_init(&audio);

  if (channels != 0 && has_preroll && asize1st) {
    if (preroll_off + asize1st > dv_len) die("Truncated: preroll audio");
    buf_append(&audio, dv + preroll_off, asize1st);
  }

  meta = (FrameMeta*)calloc((size_t)frames2, sizeof(FrameMeta));
  if (!meta) die("Out of memory");

  pos = data_off;
  for (i=0;i<frames2;i++){
    uint32_t base = table_off + i * 0x14UL;
    uint32_t fsize = rd32le(dv + base + 0);
    uint32_t vsize = rd32le(dv + base + 4);
    uint32_t dsize = rd32le(dv + base + 12);
    uint32_t total = (fsize & 0x7FFFFFFFUL);
    const uint8_t* pkt = dv + pos;

    meta[i].key = (uint8_t)((fsize & 0x80000000UL) ? 1 : 0);

    if ((uint64_t)pos + (uint64_t)total > (uint64_t)dv_len) die("Truncated: frame data");

    if (channels == 0) {
      if (total) buf_append(&video, pkt, total);
      pos += total;
      continue;
    }

    if (total < vsize) die("Corrupt item: total < vsize");

    /* Strict packet layout:
     *   video[vsize] + audio[min(dsize, total-vsize)] + padding
     */
    if (vsize) buf_append(&video, pkt, vsize);

    if (total > vsize) {
      uint32_t tail = total - vsize;
      uint32_t audio_size = (dsize <= tail) ? dsize : tail;
      /* uint32_t padding_size = tail - audio_size; */

      if (audio_size) {
        buf_append(&audio, pkt + vsize, audio_size);
      }
      /* padding is skipped */
    }

    pos += total;
  }

  *out_w = w; *out_h = h;
  *out_frames = frames2;
  *out_channels = channels;
  *out_video_es = video.p; *out_video_es_len = video.len;
  *out_audio_ogg = audio.p; *out_audio_ogg_len = audio.len;
  *out_meta = meta;
}

/* MPEG-4 VOP split */
typedef struct Span { uint8_t* p; uint32_t len; } Span;

static Span* mpeg4_split_vop_frames(const uint8_t* es, uint32_t es_len, uint32_t* out_count){
  uint32_t* idxs; uint32_t cap=1024, count=0, i;
  Span* frames;
  uint32_t header_len; uint8_t* header=0;

  idxs = (uint32_t*)malloc((size_t)cap*sizeof(uint32_t));
  if (!idxs) die("Out of memory");

  i=0;
  while (i+4 <= es_len){
    uint32_t j; int found=0;
    for (j=i; j+4<=es_len; j++){
      if (es[j]==0x00 && es[j+1]==0x00 && es[j+2]==0x01 && es[j+3]==0xB6){ found=1; break; }
    }
    if (!found) break;
    if (count >= cap){
      uint32_t* np;
      cap = cap + cap/2 + 256;
      np = (uint32_t*)realloc(idxs, (size_t)cap*sizeof(uint32_t));
      if (!np) die("Out of memory");
      idxs=np;
    }
    idxs[count++] = j;
    i = j + 4;
  }

  if (count==0){ free(idxs); die("No MPEG-4 VOP start codes found"); }

  header_len = idxs[0];
  if (header_len){
    header = (uint8_t*)malloc((size_t)header_len);
    if (!header) die("Out of memory");
    memcpy(header, es, (size_t)header_len);
  }

  frames = (Span*)calloc((size_t)count, sizeof(Span));
  if (!frames) die("Out of memory");

  for (i=0;i<count;i++){
    uint32_t start=idxs[i];
    uint32_t end=(i+1<count)?idxs[i+1]:es_len;
    uint32_t flen=end-start;

    if (i==0 && header_len){
      uint32_t total=header_len+flen;
      frames[i].p=(uint8_t*)malloc((size_t)total);
      if (!frames[i].p) die("Out of memory");
      memcpy(frames[i].p, header, (size_t)header_len);
      memcpy(frames[i].p+header_len, es+start, (size_t)flen);
      frames[i].len=total;
    } else {
      frames[i].p=(uint8_t*)malloc((size_t)flen);
      if (!frames[i].p) die("Out of memory");
      memcpy(frames[i].p, es+start, (size_t)flen);
      frames[i].len=flen;
    }
  }

  if (header) free(header);
  free(idxs);
  *out_count=count;
  return frames;
}

static void free_frames(Span* frames, uint32_t count){
  uint32_t i;
  if (!frames) return;
  for (i=0;i<count;i++) if (frames[i].p) free(frames[i].p);
  free(frames);
}

/* OGM packet builders */
static void ogm_build_stream_header_video(uint8_t out52[52], int w, int h, int fps){
  double tu_d; uint64_t time_unit;
  memset(out52, 0, 52);
  memcpy(out52 + 0, "video", 5);
  memcpy(out52 + 8, "XVID", 4);
  wr32le(out52 + 12, 52);
  tu_d = 10000000.0 / (double)fps;
  time_unit = (uint64_t)(tu_d + 0.5);
  wr64le(out52 + 16, time_unit);
  wr64le(out52 + 24, (uint64_t)1);
  wr32le(out52 + 32, 1);
  wr32le(out52 + 36, 0);
  wr32le(out52 + 44, (uint32_t)w);
  wr32le(out52 + 48, (uint32_t)h);
}
static void ogm_make_video_header_pkt(Buf* pkt, int w, int h, int fps){
  uint8_t sh[52];
  buf_init(pkt);
  ogm_build_stream_header_video(sh, w, h, fps);
  buf_append_u8(pkt, 0x01);
  buf_append(pkt, sh, 52);
}
static void ogm_make_video_comment_pkt(Buf* pkt){
  const char* vendor="dvbang";
  uint32_t vlen=(uint32_t)strlen(vendor);
  uint8_t tmp[4];
  buf_init(pkt);
  buf_append_u8(pkt, 0x03);
  wr32le(tmp, vlen); buf_append(pkt, tmp, 4);
  buf_append(pkt, (const uint8_t*)vendor, vlen);
  wr32le(tmp, 0); buf_append(pkt, tmp, 4);
}
static void ogm_make_video_data_pkt(Buf* pkt, const uint8_t* frame, uint32_t frame_len, uint8_t is_key){
  uint8_t flags = (uint8_t)(0x80 | (is_key ? 0x08 : 0x00));
  buf_init(pkt);
  buf_append_u8(pkt, flags);
  buf_append_u8(pkt, 1);
  buf_append_u8(pkt, 0);
  buf_append(pkt, frame, frame_len);
}

/* mux */
static void mux_ogv(const char* out_path,
                    const OggPage* audio_pages, uint32_t audio_page_count,
                    uint32_t sample_rate,
                    int w, int h, int fps,
                    const Span* frames, const FrameMeta* meta, uint32_t frame_count,
                    int has_audio)
{
  FILE* fo;
  Buf out, pkt;
  uint32_t video_serial = VIDEO_SERIAL_FIXED;
  uint32_t vseq = 0;
  uint32_t v_i = 0;

  buf_init(&out);

  if (has_audio) {
    uint32_t audio_serial, hdr_end, ai;
    double fps_d, half_frame;

    if (audio_page_count == 0) die("No audio pages");
    audio_serial = audio_pages[0].serial;
    if (video_serial == audio_serial) video_serial ^= 0xFFFFFFFFUL;

    hdr_end = vorbis_header_end_page_index(audio_pages, audio_page_count);

    buf_append(&out, audio_pages[0].bytes, audio_pages[0].bytes_len);

    ogm_make_video_header_pkt(&pkt, w, h, fps);
    ogg_write_packet_split(&out, pkt.p, pkt.len, video_serial, &vseq, (uint64_t)0, (uint8_t)0x02, (uint8_t)0x00);
    buf_free(&pkt);

    ogm_make_video_comment_pkt(&pkt);
    ogg_write_packet_split(&out, pkt.p, pkt.len, video_serial, &vseq, (uint64_t)0, (uint8_t)0x00, (uint8_t)0x00);
    buf_free(&pkt);

    for (ai=1; ai<=hdr_end && ai<audio_page_count; ai++){
      buf_append(&out, audio_pages[ai].bytes, audio_pages[ai].bytes_len);
    }

    fps_d = (double)fps;
    half_frame = 0.5 / fps_d;

    for (ai=hdr_end+1; ai<audio_page_count; ai++){
      double at = 0.0;
      if (sample_rate) at = (double)audio_pages[ai].granule / (double)sample_rate;

      while (v_i < frame_count){
        double vt_next = (double)(v_i + 1) / fps_d;
        if (vt_next <= at + half_frame){
          uint8_t eos = (uint8_t)((v_i + 1 == frame_count) ? 0x04 : 0x00);
          uint64_t gran = (uint64_t)(v_i + 1);
          uint8_t is_key = meta ? meta[v_i].key : 1;

          ogm_make_video_data_pkt(&pkt, frames[v_i].p, frames[v_i].len, is_key);
          ogg_write_packet_split(&out, pkt.p, pkt.len, video_serial, &vseq, gran, (uint8_t)0x00, eos);
          buf_free(&pkt);

          v_i++;
        } else break;
      }

      buf_append(&out, audio_pages[ai].bytes, audio_pages[ai].bytes_len);
    }
  } else {
    ogm_make_video_header_pkt(&pkt, w, h, fps);
    ogg_write_packet_split(&out, pkt.p, pkt.len, video_serial, &vseq, (uint64_t)0, (uint8_t)0x02, (uint8_t)0x00);
    buf_free(&pkt);

    ogm_make_video_comment_pkt(&pkt);
    ogg_write_packet_split(&out, pkt.p, pkt.len, video_serial, &vseq, (uint64_t)0, (uint8_t)0x00, (uint8_t)0x00);
    buf_free(&pkt);
  }

  while (v_i < frame_count){
    uint8_t eos = (uint8_t)((v_i + 1 == frame_count) ? 0x04 : 0x00);
    uint64_t gran = (uint64_t)(v_i + 1);
    uint8_t is_key = meta ? meta[v_i].key : 1;

    ogm_make_video_data_pkt(&pkt, frames[v_i].p, frames[v_i].len, is_key);
    ogg_write_packet_split(&out, pkt.p, pkt.len, video_serial, &vseq, gran, (uint8_t)0x00, eos);
    buf_free(&pkt);

    v_i++;
  }

  fo = fopen(out_path, "wb");
  if (!fo) die("Cannot open output file");
  if (out.len && fwrite(out.p, 1, (size_t)out.len, fo) != (size_t)out.len){
    fclose(fo);
    die("Write failed");
  }
  fclose(fo);

  buf_free(&out);
}

/* CLI */
static int streq(const char* a, const char* b){ return strcmp(a,b)==0; }
static void usage(const char* exe){
  fprintf(stderr,
    "Copyright 2026 Lumis\n"
        "https://www.ctpax-x.org/\n"
        "https://www.forum.ctpax-x.org/index.php?showtopic=326\n"
	"License: MIT\n\n"
    "Usage:\n  %s <input.dv> [output.ogv] [--fps N] [--validate]\n\n"
    "Options:\n"
    "  --fps N      set fps (default 25)\n"
    "  --validate   run ffmpeg decode test (optional; ffmpeg must be in PATH)\n"
    "  -h,--help    show help\n", exe);
}
static void make_default_out(const char* in, char* out, uint32_t outsz){
  const char* dot = strrchr(in, '.');
  uint32_t n;
  if (!dot){ snprintf(out, outsz, "%s.ogv", in); return; }
  n = (uint32_t)(dot - in);
  if (n + 5 >= outsz) die("Output path too long");
  memcpy(out, in, (size_t)n);
  memcpy(out + n, ".ogv", 5);
}

int main(int argc, char** argv){
  const char* in_path=0;
  const char* out_arg=0;
  char out_path[1024];
  int fps=25;
  int validate=0;

  int i, positional=0;

  uint8_t* dv; uint32_t dv_len;

  uint32_t w,h,frames2,channels;
  uint8_t* video_es; uint32_t video_es_len;
  uint8_t* audio_ogg; uint32_t audio_ogg_len;
  FrameMeta* meta;

  Span* frames; uint32_t frame_count;

  OggPage* audio_pages=0; uint32_t audio_page_count=0;
  uint32_t sample_rate=0;

  if (argc < 2){ usage(argv[0]); return 2; }

  for (i=1;i<argc;i++){
    const char* a = argv[i];
    if (streq(a,"-h") || streq(a,"--help")){ usage(argv[0]); return 0; }
    if (streq(a,"--validate")){ validate=1; continue; }
    if (streq(a,"--fps")){
      if (i+1>=argc){ fprintf(stderr,"Missing value for --fps\n\n"); usage(argv[0]); return 2; }
      fps = atoi(argv[++i]);
      if (fps<=0 || fps>240){ fprintf(stderr,"Invalid fps: %d\n", fps); return 2; }
      continue;
    }
    if (a[0]=='-'){ fprintf(stderr,"Unknown option: %s\n\n", a); usage(argv[0]); return 2; }
    if (positional==0){ in_path=a; positional++; continue; }
    if (positional==1){ out_arg=a; positional++; continue; }
    fprintf(stderr,"Too many arguments\n\n"); usage(argv[0]); return 2;
  }

  if (!in_path){ usage(argv[0]); return 2; }

  if (out_arg){
    strncpy(out_path, out_arg, sizeof(out_path)-1);
    out_path[sizeof(out_path)-1]=0;
  } else {
    make_default_out(in_path, out_path, (uint32_t)sizeof(out_path));
  }

  crc_table_init();

  dv = read_file_all(in_path, &dv_len);
  if (!dv) die2("Cannot read input file: ", in_path);

  w=h=frames2=channels=0;
  video_es=0; video_es_len=0;
  audio_ogg=0; audio_ogg_len=0;
  meta=0;

  dv_extract(dv, dv_len, &w,&h, &frames2,&channels,
             &video_es,&video_es_len,
             &audio_ogg,&audio_ogg_len,
             &meta);

  frames = mpeg4_split_vop_frames(video_es, video_es_len, &frame_count);

  if (channels != 0){
    audio_pages = ogg_parse_pages(audio_ogg, audio_ogg_len, &audio_page_count);
    if (!audio_pages || audio_page_count==0) die("Audio parse failed: no Ogg pages found");
    sample_rate = vorbis_detect_sample_rate(audio_pages, audio_page_count);
    if (!sample_rate){
      fprintf(stderr,"WARNING: could not detect Vorbis sample rate; assuming 44100.\n");
      sample_rate = 44100;
    }
  }

  mux_ogv(out_path,
          audio_pages, audio_page_count, sample_rate,
          (int)w, (int)h, fps,
          frames, meta, frame_count,
          (channels != 0));

  printf("ogv: %s\n", out_path);
  printf("video: MPEG-4 Part 2 (%ux%u, frames=%u, fps=%d)\n", w, h, frame_count, fps);
  if (channels != 0) printf("audio: Vorbis (sr=%u, pages=%u)\n", sample_rate, audio_page_count);
  else printf("audio: none\n");

  if (validate){
    char cmd[1400];
    int rc;
    snprintf(cmd, sizeof(cmd), "ffmpeg -hide_banner -loglevel error -i \"%s\" -f null -", out_path);
    rc = system(cmd);
    if (rc != 0) fprintf(stderr,"WARNING: ffmpeg validation failed (ffmpeg missing or decode errors).\n");
  }

  if (dv) free(dv);
  if (video_es) free(video_es);
  if (audio_ogg) free(audio_ogg);
  if (audio_pages) ogg_free_pages(audio_pages, audio_page_count);
  if (frames) free_frames(frames, frame_count);
  if (meta) free(meta);

  return 0;
}
    © CTPAX-X 2006-2026 | engine version 2.7
Based on original site design by Blade

 

 

 
При копировании материалов ссылка на сайт WWW.CTPAX-X.ORG обязательна!
Использование материалов влечёт безоговорочное принятие правил сайта.
Количество запросов к БД: 7 | Страница сгенерирована за 0.015108 сек.