Javascript/Node.js

Node.js - ffprobe로 미디어 파일 분석하기

Flashback 2025. 8. 6. 19:04
728x90
반응형

1. ffprobe란?

ffprobe로 미디어 파일이 담고 있는 영상, 음성, 자막 등의 정보를 확인할 수 있으며 해당 파일의 크기 등을 확인할 수 있다. 이렇게 얻은 정보를 바탕을 통해 ffmpeg으로 영상을 다른 확장자로 변환하거나 스트리밍 형식으로 변환할 수 있다.

Node.js에서 ffprobe를 사용하려면 ffmpeg을 다운로드 해야한다. https://ffmpeg.org/ 이 사이트에서 자신의 OS에 맞게 설치를 하거나 npm에 올라가 있는 @ffprobe-installer/ffprobe, @ffmpeg-installer/ffmpeg패키지를 설치하여 사용할 수도 있다.

npm ffmpeg: https://www.npmjs.com/package/@ffmpeg-installer/ffmpeg

npm ffprobe: https://www.npmjs.com/package/@ffprobe-installer/ffprobe

 

2. ffprobe 옵션

const ffprobeOptions = [
    '-loglevel', 'info',
    '-print_format', 'json',
    '-show_streams',
    '-show_format',
    `${path.join(__dirname, `${mp4DirName}/SampleVideo_1280x720_30mb.mp4`)}`
];
  • -loglevel: ffprobe를 실행했을 때, 나타날 로그의 로그 레벨을 설정한다. error, quiet, info 등이 있는데 error는 에러가 발생했을 때 로그 출력, quiet는 로그를 출력하지 않으며 info는 현재 진행 상황 등을 출력한다.
  • -print_format: 결과 값을 출력한 형태를 지정한다. 여기선 json으로 지정한다.
  • -show_streams: 입력 파일이 가지고 있는 영상, 음성, 자막 등의 미디어 스트림 정보를 출력하게 하는 옵션이다.
  • -show_format: 해당 미디어 파일의 파일 크기, 비트레이트와 재생 시간 등을 출력하게 하는 옵션이다.
  • path.join~: 분석할 미디어 파일의 경로를 지정한다.
const spawn = require('child_process').spawn;
const path = require('path');
const fs = require('fs');

const mp4DirName = 'original_videos'
const ffprobeOptions = [
    '-loglevel', 'error',
    '-print_format', 'json',
    '-show_streams',
    '-show_format',
    `${path.join(__dirname, `${mp4DirName}/SampleVideo_1280x720_30mb.mp4`)}`
];
const process = spawn('ffprobe', ffprobeOptions)
let output = '';

process.stdout.on('data', (data) => {
    output += data.toString();
});
process.stderr.on('data', (data) => {
    console.log('stderr: ', data.toString())
})
process.on('close', (code) => {
    if (code === 0) {
        output = JSON.parse(output)
        let videoStream = {}
        let audioStream = {}
        let mediaFormat = {}
        if(typeof output.streams !== 'undefined') {
            videoStream = output.streams.find(stream => stream.codec_type === 'video')
            audioStream = output.streams.find(stream => stream.codec_type === 'audio')
        }
        if(typeof output.format !== 'undefined') {
            mediaFormat = output.format
        }
        console.log('videoStream: ', videoStream)
        console.log('audioStream: ', audioStream)
        console.log('media format: ', mediaFormat)
    } else {
        console.log('error code: ', code)
    }
});

nodejs에서 ffmpeg, ffprobe를 사용하려면 spawn을 사용해야 한다. ffprobe는 Node.js가 아닌 외부 프로그램이기 때문에 spawn으로 외부 프로세스를 실행할 수 있게 해야 한다.

  • stdout.on(’data’): 표준 출력으로 현재 출력되는 데이터를 확인할 수 있다.
  • stderr.on(’data’): 표준 에러로 오류 또는 ffmpeg의 진행 상황을 확인할 수 있다.
  • process.on(’close’): spawn으로 실행한 프로세스가 종료되면 실행된다.

output의 streams는 -show_streams 옵션이 추가된 상태에서 확인할 수 있다. 이와 마찬가지로 output.format은 -show_format 옵션이 추가된 상태에서 확인할 수 있다.

 

3. video, audio, format 출력 값

// video stream
videoStream:  {
  index: 0,
  codec_name: 'h264',
  codec_long_name: 'H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10',
  profile: 'Main',
  codec_type: 'video',
  codec_tag_string: 'avc1',
  codec_tag: '0x31637661',
  width: 1280,
  height: 720,
  coded_width: 1280,
  coded_height: 720,
  has_b_frames: 0,
  sample_aspect_ratio: '1:1',
  display_aspect_ratio: '16:9',
  pix_fmt: 'yuv420p',
  level: 31,
  chroma_location: 'left',
  field_order: 'progressive',
  refs: 1,
  is_avc: 'true',
  nal_length_size: '4',
  id: '0x1',
  r_frame_rate: '25/1',
  avg_frame_rate: '25/1',
  time_base: '1/12800',
  start_pts: 0,
  start_time: '0.000000',
  duration_ts: 2186752,
  duration: '170.840000',
  bit_rate: '1086104',
  bits_per_raw_sample: '8',
  nb_frames: '4271',
  extradata_size: 38,
  disposition: {
    default: 1,
    dub: 0,
    original: 0,
    comment: 0,
    lyrics: 0,
    karaoke: 0,
    forced: 0,
    hearing_impaired: 0,
    visual_impaired: 0,
    clean_effects: 0,
    attached_pic: 0,
    timed_thumbnails: 0,
    non_diegetic: 0,
    captions: 0,
    descriptions: 0,
    metadata: 0,
    dependent: 0,
    still_image: 0,
    multilayer: 0
  },
  tags: {
    creation_time: '1970-01-01T00:00:00.000000Z',
    language: 'und',
    handler_name: 'VideoHandler',
    vendor_id: '[0][0][0][0]'
  }
}
// audio stream
audioStream:  {
  index: 1,
  codec_name: 'aac',
  codec_long_name: 'AAC (Advanced Audio Coding)',
  profile: 'LC',
  codec_type: 'audio',
  codec_tag_string: 'mp4a',
  codec_tag: '0x6134706d',
  sample_fmt: 'fltp',
  sample_rate: '48000',
  channels: 6,
  channel_layout: '5.1',
  bits_per_sample: 0,
  initial_padding: 0,
  id: '0x2',
  r_frame_rate: '0/0',
  avg_frame_rate: '0/0',
  time_base: '1/48000',
  start_pts: 0,
  start_time: '0.000000',
  duration_ts: 8201216,
  duration: '170.858667',
  bit_rate: '383933',
  nb_frames: '8009',
  extradata_size: 2,
  disposition: {
    default: 1,
    dub: 0,
    original: 0,
    comment: 0,
    lyrics: 0,
    karaoke: 0,
    forced: 0,
    hearing_impaired: 0,
    visual_impaired: 0,
    clean_effects: 0,
    attached_pic: 0,
    timed_thumbnails: 0,
    non_diegetic: 0,
    captions: 0,
    descriptions: 0,
    metadata: 0,
    dependent: 0,
    still_image: 0,
    multilayer: 0
  },
  tags: {
    creation_time: '1970-01-01T00:00:00.000000Z',
    language: 'und',
    handler_name: 'SoundHandler',
    vendor_id: '[0][0][0][0]'
  }
}

video와 audio정보는 위와 같이 출력된다. 핵심적인 내용으로 해당 미디어 스트림의 코덱명, 미디어 타입, 비트레이트, 재생시간과 video면 width, height 해상도, 프레임, audio면 샘플레이트 등을 확인할 수 있다. 이 정보를 바탕으로 여러 해상도로 다운 스케일링하여 스트리밍 형식으로 변환할 때 사용할 수 있다.

// format
media format:  {
  filename: '~\\\\original_videos\\\\SampleVideo_1280x720_30mb.mp4', // filename은 앞에 폴더 경로가 있는데 로컬 컴퓨터라 ~로 대체합니다.
  nb_streams: 2,
  nb_programs: 0,
  nb_stream_groups: 0,
  format_name: 'mov,mp4,m4a,3gp,3g2,mj2',
  format_long_name: 'QuickTime / MOV',
  start_time: '0.000000',
  duration: '170.858667',
  size: '31491130',
  bit_rate: '1474487',
  probe_score: 100,
  tags: {
    major_brand: 'isom',
    minor_version: '512',
    compatible_brands: 'isomiso2avc1mp41',
    creation_time: '1970-01-01T00:00:00.000000Z',
    encoder: 'Lavf53.24.2'
  }
}

format은 파일 크기, 재생 시간, 비트레이트 등을 확인할 수 있다.

 


참조 사이트:

https://ffmpeg.org/

 

FFmpeg

Converting video and audio has never been so easy. $ ffmpeg -i input.mp4 output.avi     News September 30th, 2024, FFmpeg 7.1 "Péter" FFmpeg 7.1 "Péter", a new major release, is now available! A full list of changes can be found in the release changelo

ffmpeg.org

 

https://www.npmjs.com/package/@ffprobe-installer/ffprobe

 

@ffprobe-installer/ffprobe

Platform independent binary installer of FFprobe for node projects. Latest version: 2.1.2, last published: 2 years ago. Start using @ffprobe-installer/ffprobe in your project by running `npm i @ffprobe-installer/ffprobe`. There are 104 other projects in th

www.npmjs.com

 

@ffmpeg-installer/ffmpeg - npm

 

@ffmpeg-installer/ffmpeg

Platform independent binary installer of FFmpeg for node projects. Latest version: 1.1.0, last published: 4 years ago. Start using @ffmpeg-installer/ffmpeg in your project by running `npm i @ffmpeg-installer/ffmpeg`. There are 331 other projects in the npm

www.npmjs.com

 

https://ffmpeg.org/ffprobe.html

 

ffprobe Documentation

Table of Contents ffprobe [options] input_url ffprobe gathers information from multimedia streams and prints it in human- and machine-readable fashion. For example it can be used to check the format of the container used by a multimedia stream and the form

ffmpeg.org

728x90
반응형