728x90

출처 : UltraStar Deluxe
Flamefire / Usdx
Re: XE3 + FireMonkeyでScanlineプロパティが消えた?
Bitmap의 Pixel에 접근(TBitmap.Map, TBitmapData)
FFmpeg으로 미디어 스트림 열기 (ver 0.1)
千 Line 으로 비디오플레이어 만들기 1
네이버 건강 서비스 - hello world NHN 개발자 블로그
FMX.Types.TBitmap.Unmap

FireMonkey에서 FFMpeg를 이용해서 이미지 챕쳐 하는 부분을 구현했습니다.
기존에 데이터는 Bitmap의 픽셀단위로 복사해서 구현했는데,
TImageControl 컴포넌트의 Bitamp.TBitmapData에 바로 데이터를 쓰도록 하는 방법을 찾아서,
기존 코드에 불필요한 부분을 제거하고 다시 구현했습니다.

FireMonkey에서 FFMpeg 사용하는 부분도 간단하게 정리했습니다..

파일 포맷과 코덱을 라이브러리 등록

av_register_all();

동영상 파일 읽기

errnum := avformat_open_input(@fFormatContext, Edit1.Text, nil, nil);

스트림 정보 조회

errnum := avformat_find_stream_info(fFormatContext, nil);

비디오, 오디오 스트림 Index 찾기

  for i := 0 to fFormatContext.nb_streams-1 do
  begin
    Stream := PPAVStream(PtrUInt(fFormatContext.streams) + i * Sizeof(pointer))^;

    if (Stream.codec.codec_type = CODEC_TYPE_VIDEO) and
       (FirstVideoStream < 0) then
    begin
      FirstVideoStream := i;
    end;

    if (Stream.codec.codec_type = CODEC_TYPE_AUDIO) and
       (FirstAudioStream < 0) then
    begin
      FirstAudioStream := i;
    end;
  end;

Codec 찾기

fCodec := avcodec_find_decoder(fCodecContext^.codec_id);

Codec 열기

errnum := avcodec_open2(fCodecContext, fCodec, nil);

동영상 정보 출력

  Memo1.Lines.Add('Found a matching Codec: '+ fCodecContext^.Codec.Name + sLineBreak +
    sLineBreak +
    '  Width = '+inttostr(fCodecContext^.width) +
    ', Height='+inttostr(fCodecContext^.height) + sLineBreak +
    '  Aspect    : '+inttostr(fCodecContext^.sample_aspect_ratio.num) + '/' +
                     inttostr(fCodecContext^.sample_aspect_ratio.den) + sLineBreak +
    '  Framerate : '+inttostr(fCodecContext^.time_base.num) + '/' +
                     inttostr(fCodecContext^.time_base.den));

Bitmap 객체 생성, TBitmapData

    ImageControl1.Bitmap := TBitmap.Create(fCodecContext^.width, fCodecContext^.Height);
    ImageControl1.Bitmap.Map(TMapAccess.maWrite, FBmpData);

AVPicture 구조체에 TImageControl.Bitmap의 버퍼와 연결

  errnum := avpicture_fill(PAVPicture(fAVFrameRGB), FBmpData.Data, PIXEL_FMT_FFMPEG,
      fCodecContext^.width, fCodecContext^.height);

파일에서 데이터를 읽기

errnum := av_read_frame(fFormatContext, AVPacket);

디코딩된 YUV 데이터 얻기

avcodec_decode_video2(fCodecContext, fAVFrame, frameFinished, @AVPacket);

색상 공간 변환

errnum := sws_scale(fSwScaleContext, @fAVFrame.data, @fAVFrame.linesize,
                0, fCodecContext^.Height,
                @fAVFrameRGB.data, @fAVFrameRGB.linesize);

Finalizes the customizing session of the current bitmap.

ImageControl1.Bitmap.Unmap(FBmpData);

Mac

Windows

Android

 

728x90
728x90

출처 : [FFmpeg]FFmpegをVisualStudioでコンパイル→デバッグする
Guide : How to compile ffmpeg under Windows7 and VS2012
msinttypes(ISO C9x compliant stdint.h and inttypes.h for Microsoft Visual Studio)
libav/c99-to-c89
FFmpeg 소스 빌드
FFMPEG build for Windows & VS2010 (ffmpeg 빌드)
the MinGW + MSYS environment

MinGW설치

mingw-get-setup.exe 다운로드

Path 추가

C:\MinGW\bin
C:\MinGW\msys\1.0\bin

Git 설치

http://msysgit.github.io/

Path 추가

C:\Program Files (x86)\Git\bin

yasm 설치 다운로드

vsyasm-1.2.0-win64.zip 파일을 받아 압축을 풀고,
vsyasm.exe 파일을 C:\MinGW\msys\1.0\bin 폴더에 복사

C:\MinGW\msys\1.0\msys.bat 수정

call "C:/Program Files (x86)/Microsoft Visual Studio 10.0/VC/vcvarsall.bat"
set path=C:/MinGW/bin;C:/MinGW/msys/1.0/bin;%path%

link.exe 이름 변경

D:\MinGW\msys\1.0\bin\link.exe와 msvc의 link.exe 이름이 동일해서
D:\MinGW\msys\1.0\bin\link.exe 파일명을 변경해야 컴파일 가능 (-> _link.exe)

pkg-config 설치 glib_2.28.1-1_win32.zip pkg-config_0.23-3_win32.zip

c99-to-c89 https://github.com/libav/c99-to-c89/downloads, ftp://ftp.videolan.org/pub/contrib/c99-to-c89/1.0.1/win32/


MSYS Shell 실행

C:\MinGW\msys\1.0\msys.bat 

 FFmpeg 소스 빌드

 

 - 작성중 -


728x90
728x90

다운로드

http://old-releases.ubuntu.com/releases/oneiric/

NDK 다운로드

http://developer.android.com/tools/sdk/ndk/index.html

SSH 서버 설치
http://pirtaja.tistory.com/9

$ sudo apt-get install openssh-server
$ sudo /etc/init.d/ssh restart

jdk 1.6 설치 (Gingerbread and newer)
Installing Java6 JDK on Ubuntu 11.10

$ sudo add-apt-repository ppa:ferramroberto/java
$ sudo apt-get update
$ sudo apt-get install sun-java6-jdk sun-java6-plugin

.bashrc 내용 추가

# Java Setting
export JAVA_HOME=/usr/lib/jvm/java-6-sun
export ANDROID_JAVA_HOME=$JAVA_HOME

Android PDK 빌드 환경 구축 (64Bit OS)
http://source.android.com/source/initializing.html
[Android/안드로이드] Ubuntu에서 E: Package 'lib32readline5-dev' has no installation candidate. 발생시 대처 방법.

$ sudo apt-get install git-core gnupg flex bison gperf build-essential \
  zip curl zlib1g-dev libc6-dev lib32ncurses5-dev ia32-libs \
  x11proto-core-dev libx11-dev lib32readline-gplv2-dev lib32z-dev \
  libgl1-mesa-dev g++-multilib mingw32 tofrodos python-markdown \
  libxml2-utils xsltproc

Libx11-dev:i386 설치

$ sudo apt-get install libx11-dev:i386

repo 스크립트 다운로드
[Android/안드로이드] 64bit Ubuntu Android ICS Source 다운받기

$ mkdir ~/bin
$ PATH=~/bin:$PATH
$ curl https://dl-ssl.google.com/dl/googlesource/git-repo/repo > ~/bin/repo
$ chmod a+x ~/bin/repo

저장소 초기화

$ sudo mkdir /opt/android-source
$ cd /opt/android-source
$ sudo chown test:test .            <-- 옵션
$ repo init -u https://android.googlesource.com/platform/manifest
$ repo init -u https://android.googlesource.com/platform/manifest -b android-4.0.3_r1

소스 내려 받기

$ repo sync

안드로이드 소스 전체빌드
[안드로이드] 안드로이드 소스 전체빌드 해보기
안드로이드 빌드하기

안드로이드 소스 빌드

$ cd /opt/android-source
$ make

빌드 오류 해결법

android build error 해결법
ICS Source download
slang_rs_export_foreach.cpp , error : variable ‘ParamName’ set but not used
Ubuntu 11.10 ics build error

make: *** [out/host/linux-x86/obj/EXECUTABLES/obbtool_intermediates/Main.o] Error 1

$ vi build/core/combo/HOST_linux-x86.mk
#HOST_GLOBAL_CFLAGS += -D_FORTIFY_SOURCE=0
HOST_GLOBAL_CFLAGS += -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0

make: *** [out/host/linux-x86/obj/STATIC_LIBRARIES/libGLcommon_intermediates/GLDispatch.o] Error 1

$ sudo apt-get install mesa-common-dev

make: *** [out/host/linux-x86/obj/EXECUTABLES/llvm-rs-cc_intermediates/slang_rs_export_foreach.o] Error 1

$ vi frameworks/compile/slang/Android.mk
#local_cflags_for_slang := -Wno-sign-promo -Wall -Wno-unused-parameter -Werror
local_cflags_for_slang := -Wno-sign-promo -Wall -Wno-unused-parameter

make: *** [out/host/linux-x86/obj/STATIC_LIBRARIES/liboprofile_pp_intermediates/arrange_profiles.o] Error 1

external/oprofile/libpp/format_output.h 파일의 94번행

-   mutable counts_t & counts;
+   counts_t & counts;

make: *** [out/host/linux-x86/obj/EXECUTABLES/test-librsloader_intermediates/test-librsloader] Error 1

external/llvm/llvm-host-build.mk 내용 추가

+   LOCAL_LDLIBS := -lpthread -ldl

make: *** [out/host/linux-x86/obj/STATIC_LIBRARIES/libgtest_host_intermediates/gtest-all.o] Error 1

vi external/gtest/include/gtest/internal/gtest-param-util.h 내용추가

#include <cstddef>

make: *** [out/host/linux-x86/obj/STATIC_LIBRARIES/libMesa_intermediates/src/glsl/linker.o] Error 1

vi external/mesa3d/src/glsl/linker.cpp 내용추가

#include <stddef.h>

make: *** [out/host/linux-x86/obj/STATIC_LIBRARIES/libmtp_intermediates/MtpDevice.o] Error 1

vi frameworks/base/media/mtp/MtpDevice.cpp 수정

-   int fd = ::open(destPath, O_RDWR | O_CREAT | O_TRUNC);
+   int fd = ::open(destPath, O_RDWR | O_CREAT | O_TRUNC, 0777);

Android NDK(C/C++) 설치

http://developer.android.com/tools/sdk/ndk/index.html

$ sudo mv android-ndk-r9-linux-x86_64.tar.bz2 /opt
$ sudo tar xvf android-ndk-r9-linux-x86_64.tar.bz2

.profile-ndk 파일 작성

export ANDROID_NDK_ROOT=/opt/android-ndk-r9
export NDK_TOOLCHAIN_VERSION=4.6
export TOOLCHAIN=/opt/android-9-toolchain

export PATH=$TOOLCHAIN/bin:$PATH

.profile-ndk 실행 (NDK 빌드시 사용)

$ chmod a+x .profile-ndk 
$ source .profile-ndk

ToolChain 만들기

$ $ANDROID_NDK_ROOT/build/tools/make-standalone-toolchain.sh \
--toolchain=arm-linux-androideabi-4.6 \
--ndk-dir=$ANDROID_NDK_ROOT \
--install-dir=$TOOLCHAIN \
--platform=android-9
$ sudo chown test:test -hR /opt/android-9-toolchain

728x90
728x90

ffmpeg 라이브러리를 이용해서 wowza서버를 사용하는 rtsp 플레이어를 제작해보았습니다.
소스는 iFrameExtractor 프로젝트에서 파일 오픈하는 부분을 rtsp 주소를 사용했고,
ffmpeg 라이브러리 경로를 따로 설정해서 컴파일 했습니다.

설치한 ffmpeg 라이브러리가 ios용으로 컴파일 되어 있어서
시뮬레이터에서는 테스트 할 수가 없네요.

iFrameExtractor 프로젝트는 ffmpeg 라이브러리만 사용했기 때문에 플레이는 되지만,
속도는 나오지 않습니다. OpenGL ES / SDL 라이브러리 이용해야 될 것 같네요.

출처

How can you pass YUV frames from FFmpeg to OpenGL ES?
TECH TUTORIAL ? HOW TO SETUP A SDL-READY XCODE4 PROJECT
CODEC_TYPE_VIDEO undefined
ffmpeg을 이용한 iOS 동영상 플레이어
<video> 태그를 이용하여 rstp 프로토콜의 스트리밍을 재생하고자 하고싶은데요...
Audio and Video HTML
myoutube or RTSP streaming support on chrome

소스 다운로드

jayrparro / iFrameExtractor

ffmpeg 라이브러리 경로 설정

오류 수정

CODEC_TYPE_VIDEO undefined 발생 한다면,
AVMEDIA_TYPE_VIDEO 로 수정

rtsp 주소 설정
iFrameExtractorAppDelegate.m

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
	//self.video = [[VideoFrameExtractor alloc] initWithVideo:[Utilities bundlePath:@"sophie.mov"]];
    //self.video = [[VideoFrameExtractor alloc] initWithVideo:[Utilities bundlePath:@"oh.mp4"]];
    self.video = [[VideoFrameExtractor alloc] initWithVideo:@"rtsp://192.168.0.13/vod/mp4:sample.mp4"];
	[video release];

	// set output image size
	video.outputWidth = 426;
	video.outputHeight = 320;
	
	// print some info about the video
	NSLog(@"video duration: %f",video.duration);
	NSLog(@"video size: %d x %d", video.sourceWidth, video.sourceHeight);
	
	// video images are landscape, so rotate image view 90 degrees
	[imageView setTransform:CGAffineTransformMakeRotation(M_PI/2)];
    [window makeKeyAndVisible];
}

YUV 데이터 -> RGB 데이터 소스
VideoFrameExtractor.m

-(void)convertFrameToRGB {	
	sws_scale (img_convert_ctx, pFrame->data, pFrame->linesize,
			   0, pCodecCtx->height,
			   picture.data, picture.linesize);	
}

실행


728x90
728x90

출처

iOS용 FFmpeg 빌드
[iPhone] ffmpeg 빌드하기
How to cross compile ffmpeg for iOS (iPhone and iPad)
Build m4, autoconf, automake, libtool on Mac OS X Lion
http://www.slideshare.net/hypermin/html5-video

make 커맨드 설치

pkg-config 설치

pkg-config 다운로드

gas-preprocessor 다운로드

gas-preprocessor 다운로드

build-essentials 스크립트 다운로드및 실행

설치되는 항목 m4, autoconf, automake, libtool

https://gist.github.com/1397146

- 디렉토리구조

$HOME
├ local
└ Builds
   └ build-essential
      ├ build-essential.sh
      └ src

- 실행

$ chmod 755 build-essential.sh
$ ./build-essential.sh

- 경로 추가 (~/.profile)

PATH=$PATH:/Users/자신의계정/local/bin

- 확인

압축풀기

- 다운로드

ffmpeg 다운로드

- 압축풀기

$ tar xvfz ffmpeg-0.8.11.tar.bz2

config.sh 파일

./configure --enable-cross-compile \
  --arch=arm \
  --target-os=darwin \
  --cc='/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/arm-apple-darwin10-llvm-gcc-4.2' \
  --as='./gas-preprocessor/gas-preprocessor.pl /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/arm-apple-darwin10-llvm-gcc-4.2' \
  --cpu=cortex-a8 \
  --enable-pic \
  --disable-yasm \
  --sysroot='/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk' \
  --extra-cflags='-mfpu=neon -pipe -Os -gdwarf-2 -miphoneos-version-min=5.0' \
  --extra-ldflags='-arch armv7 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk -miphoneos-version-min=5.0' \
  --disable-asm \
  --disable-doc \
  --disable-ffmpeg \
  --disable-ffplay \
  --disable-ffprobe \
  --disable-ffserver \
  --enable-avdevice \
  --disable-devices \
  --disable-filters \
  --disable-yasm \
  --enable-network \
  --enable-protocol=tcp \
  --enable-demuxer=rtsp \
  --enable-decoder=h264

$ ./config.sh

$ make

$ sudo make install

728x90
728x90

출처 : Android NDK FFmpeg 컴파일 강좌 (1/4)
Android NDK FFmpeg 컴파일 강좌 (4/4)
Android NDK FFmpeg 컴파일 강좌 (3/4)
Android NDK FFmpeg 컴파일 강좌 (2/4)
Android NDK FFmpeg 컴파일 강좌 (새로운 시도)
http://blog.daum.net/hopefullife/209
Android NDK Overview
Android NDK 빌드환경을 사용하지 않는 Makefile
Decoding audio via Android using FFMpeg
OpenMAX AL for ffmpeg
live-converter
read-only stream buffer interface in ffmpeg #1
FFmpeg port for Android ndk
android-ndk-r7 编译 ffmpeg-0.10
Android AudioRecord to FFMPEG encode native AAC
http://www.2cto.com/kf/201201/116171.html
http://pastebin.com/P02Fmw53
AndroidCompile

안드로이드펍에서 남은그루터기, 로봇시대 글을 보고, 컴파일 해보았는데, 작업해야될 부분이 많았어서,
인터넷에서 여러가지 글을 찾아보고, 간단하게 할 수 있는 방법을 찾아 보았습니다.

일주일 동안의 고생한 내용을 정리합니다. 안드로이드펍의 남은그루터기님과, 로봇시대님에게 감사한마음 글로나마 드립니다.

toolchain을 /opt/android-8-toolchain 설치하고, ffmpeg 폴더에 config.sh 파일을 아래와 같이 만들었습니다.
C 드라이브에 ffmpegtmp 폴더를 만들고, 남은그루터기님 처럼 configure 파일은 수정하지 않았습니다.

그리고, 남은그루터기님의 소스를 받아서 rtsp 주소로 실행하면 "Open Movie Error: -2" 라고 나오는데,
지원이 안되는 것으로 알고 있었는데, 프로젝트의 AndroidManifest.xml 파일에 인터넷 접근 권한을 추가 해야  되더군요.
2일이나 고생해서 찾았습니다.

config.sh 파일

export TMPDIR=c:/ffmpegtmp
export ANDROID_ROOT=/opt/android-8-toolchain

./configure --target-os=linux \
--arch=arm \
--enable-cross-compile \
--cc=$ANDROID_ROOT/bin/arm-linux-androideabi-gcc \
--cross-prefix=$ANDROID_ROOT/bin/arm-linux-androideabi- \
--extra-cflags="-marm -march=armv7-a -mfloat-abi=softfp -mfpu=neon" \
--extra-ldflags="-Wl,--fix-cortex-a8" \
--disable-doc \
--disable-ffmpeg \
--disable-ffplay \
--disable-ffprobe \
--disable-ffserver \
--disable-avdevice \
--disable-devices \
--disable-filters \
--disable-yasm \
--enable-network \
--enable-protocol=tcp \
--enable-demuxer=rtsp \
--enable-decoder=h264

남은그루터기님은 각라이브러리 폴더에 Android.mk을 만드셨지만,
config.sh 파일은 만들고 ./config.sh 실행하고 make 컴파일 실행하면,
각 라이브러리 폴더에 .a 파일로 파일이 생성됩니다.
jni 컴파일 할때도 이 라이브러리 파일만 참조 하시면 됩니다.

CPU별 --extra-cflags 추가 플래그

arm v6
    -marm -march=armv6

arm v7vfpv3
    -mfloat-abi=softfp -mfpu=vfpv3-d16 -marm -march=armv7-a

arm v7vfp
    -mfloat-abi=softfp -mfpu=vfp -marm -march=armv7-a

arm v7n
    -mfloat-abi=softfp -mfpu=neon -marm -march=armv7-a -mtune=cortex-a8

arm v6+vfp
    -DCMP_HAVE_VFP -mfloat-abi=softfp -mfpu=vfp -marm -march=armv6

컴파일

$ ./config.sh

$ make

BasicPlayer.c 수정 - 남은그루터기 소스 원본의 내용 일부

#include "avcodec.h"
#include "avformat.h"
#include "swscale.h"

수정된 소스

#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"

Application.mk

APP_ABI := armeabi armeabi-v7a
APP_PLATFORM := android-8

Android.mk

# 참조
#      http://berabue.tistory.com/67
#      http://www.newsmth.net/bbsanc.php?path=%2Fgroups%2Fcomp.faq%2FMobileDev%2Fandroid%2FM.1315568907.n0&ap=275

# 컴파일하고자 하는 소스파일 위치를 알려줍니다. Android.mk를 jni에 놔두었으니 프로젝트/jni폴더가 됩니다.
LOCAL_PATH := $(call my-dir)

FFMPEGDIR := D:/Windows/cygwin/home/bluesanta/BluePlayer/jni/ffmpeg

# LOCAL로 시작하는것들을 초기화시킨다고합니다. LOCAL_PATH는 제외.
include $(CLEAR_VARS)

LOCAL_C_INCLUDES := $(FFMPEGDIR)

# List 'cpufeatures' in your list of static library dependencies
LOCAL_STATIC_LIBRARIES := cpufeatures

# 생성될 so파일명입니다.
LOCAL_MODULE    := libbasicplayer

# 컴파일할 소스파일을 추가합니다.  
LOCAL_SRC_FILES := Interface.c BasicPlayer.c

LDFFMPEG = -L$(FFMPEGDIR)/libavformat -L$(FFMPEGDIR)/libavcodec -L$(FFMPEGDIR)/libavutil -L$(FFMPEGDIR)/libswscale
LOCAL_LDLIBS    := $(LDFFMPEG) -lavformat -lswscale -lavcodec -lavutil -lz -lm -llog -ljnigraphics

# 공유 라이브러리를 생성합니다.
include $(BUILD_SHARED_LIBRARY)

# At the end of your Android.mk, import the 'android/cpufeatures'
$(call import-module,android/cpufeatures)

컴파일

$ ndk-build

728x90
728x90

출처 : RTMPDump
Compiling RTMPdump on Max OS X
Compiling FFmpeg 0.9 with libRTMP and libmp3lame for Intel and ARM CPUs
Compiling FFMPEG 0.6 with RTMP Support for OSX
ffmpeg ndk 빌드 #2 ffmpeg 옵션별 빌드
best-video-player
Fix rtmp double cflags in pkgconfig module

다운로드

RTMPDump 에서 rtmpdump-2.3.tgz 파일 다운로드

압축풀기

$ tar xvfz rtmpdump-2.3.gz

ffmpeg 폴더로 이동 시키기

mv rtmpdump-2.3/librtmp ffmpeg-0.10.3

rtmp 라이브러리 컴파일, 설치

$ cd ffmpeg-0.10.3/librtmp
$ make SYS=linux install
$ echo 'export PKG_CONFIG_PATH=/lib/pkgconfig:/usr/local/lib/pkgconfig' | tee -a ~/.bashrc

configure

config.sh 파일

export TMPDIR=c:/ffmpegtmp

./configure --disable-doc \
--disable-ffmpeg \
--disable-ffplay \
--disable-ffprobe \
--disable-ffserver \
--disable-avdevice \
--disable-devices \
--disable-filters \
--disable-yasm \
--enable-network \
--enable-protocol=tcp \
--enable-demuxer=rtsp \
--enable-decoder=h264 \
--enable-librtmp

$ ./config.sh

$ make

testmain.c

#include <stdio.h> 
#include <stdlib.h> 
#include <libavcodec/avcodec.h> 
#include <libavformat/avformat.h> 
#include <libavformat/avio.h> 
 
 
int main(int argc, char** argv) { 
 
    AVFormatContext* context = avformat_alloc_context(); 
    int video_stream_index; 
 
    av_register_all(); 
    avcodec_register_all(); 
    avformat_network_init(); 

    //if(avformat_open_input(&context, "rtsp://192.168.0.40/vod/mp4:sample.mp4",NULL,NULL) != 0){ 
  	//if(avformat_open_input(&context, "rtmp://192.168.0.40/vod/sample.mp4",NULL,NULL) != 0){     	
    //if(avformat_open_input(&context, "d:\\windows\\b.mp4",NULL,NULL) != 0){ 
 
    //open rtsp 
    if(avformat_open_input(&context, "rtmp://192.168.0.40/vod/sample.mp4",NULL,NULL) != 0){     	
        return EXIT_FAILURE; 
    } 
 
    if(avformat_find_stream_info(context,NULL) < 0){ 
        return EXIT_FAILURE; 
    } 
 
    //search video stream 
    int i;
    for(i =0;i<context->nb_streams;i++){ 
        if(context->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) 
            video_stream_index = i; 
    } 
 
    AVPacket packet; 
    av_init_packet(&packet); 
 
    //open output file 
    AVOutputFormat* fmt = av_guess_format(NULL,"test2.avi",NULL); 
    AVFormatContext* oc = avformat_alloc_context(); 
    oc->oformat = fmt; 
    avio_open2(&oc->pb, "test.avi", AVIO_FLAG_WRITE,NULL,NULL); 
 
    AVStream* stream=NULL; 
    int cnt = 0; 
    //start reading packets from stream and write them to file 
 
    av_read_play(context);//play RTSP 
    while(av_read_frame(context,&packet)>=0 && cnt <100){//read 100 frames 
        if(packet.stream_index == video_stream_index){//packet is video                
            if(stream == NULL){//create stream in file 
                stream = avformat_new_stream(oc,context->streams[video_stream_index]->codec->codec); 
                avcodec_copy_context(stream->codec,context->streams[video_stream_index]->codec); 
                stream->sample_aspect_ratio = context->streams[video_stream_index]->codec->sample_aspect_ratio; 
                avformat_write_header(oc,NULL); 
            } 
            packet.stream_index = stream->id; 
 
            av_write_frame(oc,&packet); 
            cnt++; 
        } 
        av_free_packet(&packet); 
        av_init_packet(&packet); 
    } 
    av_read_pause(context); 
    av_write_trailer(oc); 
    avio_close(oc->pb); 
    avformat_free_context(oc); 
 
    return (EXIT_SUCCESS); 
} 

Makefile

TARGET = hello3

FFMPEGDIR = /home/bluesanta/ffmpeg-0.10.3

LIBDIR = /lib

CC 	= gcc
AR 	= ar
LD 	= ld
NM 	= nm
RANLIB 	= ranlib
STRIP = strip

INCLUDE = -I.. -I.

CFLAGS = -Wall
LDFFMPEG = -L$(FFMPEGDIR)/libavformat -L$(FFMPEGDIR)/libavcodec -L$(FFMPEGDIR)/libavutil -L$(FFMPEGDIR)/librtmp
LDFLAGS = -L$(LIBDIR) $(LDFFMPEG) -lavformat -lavcodec -lavutil -lrtmp -lkernel32 -lcygwin -lm -lgcc -lc -lssl -lz -lcrypto

# application file
APPSOURCES = testmain.c
APPOBJS = $(APPSOURCES:.c=.o)

# define the rule
.SUFFIXES:.c .o 

.c.o:
	@echo Compiling: $< 
	$(CC) -c $(CFLAGS)  $(INCLUDE) -o $@ $<

all: app

app: $(APPOBJS)
	@echo Linking: $(TARGET) 
	$(CC) -o $(TARGET) $(APPOBJS) $(LDFLAGS)
	$(STRIP) -s $(TARGET)

clean:
	@rm -vf $(APPOBJS) $(TARGET) 

컴파일, 실행

 

728x90
728x90

출처 : Record RTSP stream with FFmpeg libavformat
Android NDK FFmpeg 컴파일 강좌 (1/4)

환경

wowza 2.2.4, ffmpeg-0.10.3, cygwin, windows 7

압축풀기

$ tar xvfz ffmpeg-0.10.3.tar.gz

configure

config.sh 파일

export TMPDIR=c:/ffmpegtmp

./configure --disable-doc \
--disable-ffmpeg \
--disable-ffplay \
--disable-ffprobe \
--disable-ffserver \
--disable-avdevice \
--disable-devices \
--disable-filters \
--disable-yasm \
--enable-network \
--enable-protocol=tcp \
--enable-demuxer=rtsp \
--enable-decoder=h264 

$ ./config.sh

$ make

testmain.c

#include <stdio.h> 
#include <stdlib.h> 
#include <libavcodec/avcodec.h> 
#include <libavformat/avformat.h> 
#include <libavformat/avio.h> 
 
 
int main(int argc, char** argv) { 
 
    AVFormatContext* context = avformat_alloc_context(); 
    int video_stream_index; 
 
    av_register_all(); 
    avcodec_register_all(); 
    avformat_network_init(); 

  	//if(avformat_open_input(&context, "rtmp://192.168.0.40/vod/sample.mp4",NULL,NULL) != 0){     	
    //if(avformat_open_input(&context, "d:\\windows\\b.mp4",NULL,NULL) != 0){ 
 
    //open rtsp 
    if(avformat_open_input(&context, "rtsp://192.168.0.40/vod/mp4:sample.mp4",NULL,NULL) != 0){ 
        return EXIT_FAILURE; 
    } 
 
    if(avformat_find_stream_info(context,NULL) < 0){ 
        return EXIT_FAILURE; 
    } 
 
    //search video stream 
    int i;
    for(i =0;i<context->nb_streams;i++){ 
        if(context->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) 
            video_stream_index = i; 
    } 
 
    AVPacket packet; 
    av_init_packet(&packet); 
 
    //open output file 
    AVOutputFormat* fmt = av_guess_format(NULL,"test2.avi",NULL); 
    AVFormatContext* oc = avformat_alloc_context(); 
    oc->oformat = fmt; 
    avio_open2(&oc->pb, "test.avi", AVIO_FLAG_WRITE,NULL,NULL); 
 
    AVStream* stream=NULL; 
    int cnt = 0; 
    //start reading packets from stream and write them to file 
 
    av_read_play(context);//play RTSP 
    while(av_read_frame(context,&packet)>=0 && cnt <100){//read 100 frames 
        if(packet.stream_index == video_stream_index){//packet is video                
            if(stream == NULL){//create stream in file 
                stream = avformat_new_stream(oc,context->streams[video_stream_index]->codec->codec); 
                avcodec_copy_context(stream->codec,context->streams[video_stream_index]->codec); 
                stream->sample_aspect_ratio = context->streams[video_stream_index]->codec->sample_aspect_ratio; 
                avformat_write_header(oc,NULL); 
            } 
            packet.stream_index = stream->id; 
 
            av_write_frame(oc,&packet); 
            cnt++; 
        } 
        av_free_packet(&packet); 
        av_init_packet(&packet); 
    } 
    av_read_pause(context); 
    av_write_trailer(oc); 
    avio_close(oc->pb); 
    avformat_free_context(oc); 
 
    return (EXIT_SUCCESS); 
} 

Makefile

TARGET = hello2

FFMPEGDIR = /home/bluesanta/ffmpeg-0.10.3

LIBDIR = /lib

CC 	= gcc
AR 	= ar
LD 	= ld
NM 	= nm
RANLIB 	= ranlib
STRIP = strip

INCLUDE = -I$(FFMPEGDIR)

CFLAGS = -Wall
LDFFMPEG = -L$(FFMPEGDIR)/libavformat -L$(FFMPEGDIR)/libavcodec -L$(FFMPEGDIR)/libavutil 
LDFLAGS = -L$(LIBDIR) $(LDFFMPEG) -lavformat -lavcodec -lavutil -lkernel32 -lcygwin -lm -lgcc -lc

# application file
APPSOURCES = testmain.c
APPOBJS = $(APPSOURCES:.c=.o)

# define the rule
.SUFFIXES:.c .o 

.c.o:
	@echo Compiling: $< 
	$(CC) -c $(CFLAGS)  $(INCLUDE) -o $@ $<

all: app

app: $(APPOBJS)
	@echo Linking: $(TARGET) 
	$(CC) -o $(TARGET) $(APPOBJS) $(LDFLAGS)
	$(STRIP) -s $(TARGET)

clean:
	@rm -vf $(APPOBJS) $(TARGET) 

컴파일, 실행

728x90

+ Recent posts