├── lib ├── librtmp.so ├── libssl.so ├── libx264.so ├── libz.so ├── libz.so.1 ├── libcrypto.so ├── librtmp.so.0 ├── librtmp.so.1 ├── libssl.so.1.0.0 ├── libx264.so.152 ├── libx264.so.161 ├── libz.so.1.2.11 ├── libcrypto.so.1.0.0 └── pkgconfig │ ├── openssl.pc │ ├── librtmp.pc │ ├── zlib.pc │ ├── x265.pc │ ├── x264.pc │ ├── libssl.pc │ └── libcrypto.pc ├── README.md ├── include ├── x264_config.h ├── rtmp_send.h ├── x265_config.h ├── librtmp │ ├── http.h │ ├── log.h │ ├── amf.h │ └── rtmp.h ├── x264_encoder.h ├── camer.h └── x264.h ├── .gitignore ├── Makefile ├── main.c ├── rtmp_send.c ├── x264_encoder.c ├── camer.c └── LICENSE /lib/librtmp.so: -------------------------------------------------------------------------------- 1 | librtmp.so.0 -------------------------------------------------------------------------------- /lib/libssl.so: -------------------------------------------------------------------------------- 1 | libssl.so.1.0.0 -------------------------------------------------------------------------------- /lib/libx264.so: -------------------------------------------------------------------------------- 1 | libx264.so.161 -------------------------------------------------------------------------------- /lib/libz.so: -------------------------------------------------------------------------------- 1 | libz.so.1.2.11 -------------------------------------------------------------------------------- /lib/libz.so.1: -------------------------------------------------------------------------------- 1 | libz.so.1.2.11 -------------------------------------------------------------------------------- /lib/libcrypto.so: -------------------------------------------------------------------------------- 1 | libcrypto.so.1.0.0 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # V4L2-to-Rtmp 2 | 基于ARM平台的监控系统 使用V4L2框架采集视频数据;经过H264编码压缩;然后通过RTMP协议推流至服务器 3 | -------------------------------------------------------------------------------- /lib/librtmp.so.0: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/745506980/V4L2-to-Rtmp/HEAD/lib/librtmp.so.0 -------------------------------------------------------------------------------- /lib/librtmp.so.1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/745506980/V4L2-to-Rtmp/HEAD/lib/librtmp.so.1 -------------------------------------------------------------------------------- /lib/libssl.so.1.0.0: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/745506980/V4L2-to-Rtmp/HEAD/lib/libssl.so.1.0.0 -------------------------------------------------------------------------------- /lib/libx264.so.152: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/745506980/V4L2-to-Rtmp/HEAD/lib/libx264.so.152 -------------------------------------------------------------------------------- /lib/libx264.so.161: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/745506980/V4L2-to-Rtmp/HEAD/lib/libx264.so.161 -------------------------------------------------------------------------------- /lib/libz.so.1.2.11: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/745506980/V4L2-to-Rtmp/HEAD/lib/libz.so.1.2.11 -------------------------------------------------------------------------------- /lib/libcrypto.so.1.0.0: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/745506980/V4L2-to-Rtmp/HEAD/lib/libcrypto.so.1.0.0 -------------------------------------------------------------------------------- /include/x264_config.h: -------------------------------------------------------------------------------- 1 | #define X264_GPL 1 2 | #define X264_INTERLACED 1 3 | #define X264_BIT_DEPTH 0 4 | #define X264_CHROMA_FORMAT 0 5 | #define X264_VERSION "" 6 | #define X264_POINTVER "0.161.x" 7 | -------------------------------------------------------------------------------- /lib/pkgconfig/openssl.pc: -------------------------------------------------------------------------------- 1 | prefix=/home/openssl 2 | exec_prefix=${prefix} 3 | libdir=${exec_prefix}/lib 4 | includedir=${prefix}/include 5 | 6 | Name: OpenSSL 7 | Description: Secure Sockets Layer and cryptography libraries and tools 8 | Version: 1.0.2s 9 | Requires: libssl libcrypto 10 | -------------------------------------------------------------------------------- /lib/pkgconfig/librtmp.pc: -------------------------------------------------------------------------------- 1 | prefix=/home/rtmp 2 | exec_prefix=${prefix} 3 | libdir=${exec_prefix}/lib 4 | incdir=${prefix}/include 5 | 6 | Name: librtmp 7 | Description: RTMP implementation 8 | Version: v2.3 9 | Requires: libssl,libcrypto 10 | URL: http://rtmpdump.mplayerhq.hu 11 | Libs: -L${libdir} -lrtmp -lz 12 | Cflags: -I${incdir} 13 | -------------------------------------------------------------------------------- /lib/pkgconfig/zlib.pc: -------------------------------------------------------------------------------- 1 | prefix=/home/zlib/ 2 | exec_prefix=${prefix} 3 | libdir=${exec_prefix}/lib 4 | sharedlibdir=${libdir} 5 | includedir=${prefix}/include 6 | 7 | Name: zlib 8 | Description: zlib compression library 9 | Version: 1.2.11 10 | 11 | Requires: 12 | Libs: -L${libdir} -L${sharedlibdir} -lz 13 | Cflags: -I${includedir} 14 | -------------------------------------------------------------------------------- /lib/pkgconfig/x265.pc: -------------------------------------------------------------------------------- 1 | prefix=/usr/local 2 | exec_prefix=${prefix} 3 | libdir=${exec_prefix}/lib 4 | includedir=${prefix}/include 5 | 6 | Name: x265 7 | Description: H.265/HEVC video encoder 8 | Version: 2.6 9 | Libs: -L${libdir} -lx265 10 | Libs.private: -lstdc++ -lm -lgcc_s -lgcc -lgcc_s -lgcc -lrt -ldl 11 | Cflags: -I${includedir} 12 | -------------------------------------------------------------------------------- /lib/pkgconfig/x264.pc: -------------------------------------------------------------------------------- 1 | prefix=/home/x264/ 2 | exec_prefix=${prefix} 3 | libdir=${exec_prefix}/lib 4 | includedir=${prefix}/include 5 | 6 | Name: x264 7 | Description: H.264 (MPEG4 AVC) encoder library 8 | Version: 0.161.x 9 | Libs: -L${exec_prefix}/lib -lx264 10 | Libs.private: -lpthread -lm -ldl 11 | Cflags: -I${prefix}/include -DX264_API_IMPORTS 12 | -------------------------------------------------------------------------------- /lib/pkgconfig/libssl.pc: -------------------------------------------------------------------------------- 1 | prefix=/home/openssl 2 | exec_prefix=${prefix} 3 | libdir=${exec_prefix}/lib 4 | includedir=${prefix}/include 5 | 6 | Name: OpenSSL-libssl 7 | Description: Secure Sockets Layer and cryptography libraries 8 | Version: 1.0.2s 9 | Requires.private: libcrypto 10 | Libs: -L${libdir} -lssl 11 | Libs.private: -ldl 12 | Cflags: -I${includedir} 13 | -------------------------------------------------------------------------------- /lib/pkgconfig/libcrypto.pc: -------------------------------------------------------------------------------- 1 | prefix=/home/openssl 2 | exec_prefix=${prefix} 3 | libdir=${exec_prefix}/lib 4 | includedir=${prefix}/include 5 | enginesdir=${libdir}/engines 6 | 7 | Name: OpenSSL-libcrypto 8 | Description: OpenSSL cryptography library 9 | Version: 1.0.2s 10 | Requires: 11 | Libs: -L${libdir} -lcrypto 12 | Libs.private: -ldl 13 | Cflags: -I${includedir} 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Object files 5 | *.o 6 | *.ko 7 | *.obj 8 | *.elf 9 | 10 | # Linker output 11 | *.ilk 12 | *.map 13 | *.exp 14 | 15 | # Precompiled Headers 16 | *.gch 17 | *.pch 18 | 19 | # Libraries 20 | 21 | # Shared objects (inc. Windows DLLs) 22 | 23 | # Executables 24 | *.exe 25 | *.out 26 | *.app 27 | *.i*86 28 | *.x86_64 29 | *.hex 30 | 31 | # Debug files 32 | *.dSYM/ 33 | *.su 34 | *.idb 35 | *.pdb 36 | 37 | # Kernel Module Compile Results 38 | *.mod* 39 | *.cmd 40 | .tmp_versions/ 41 | modules.order 42 | Module.symvers 43 | Mkfile.old 44 | dkms.conf 45 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # 3 | # Copyright (C) 2020 JunKe Yuan<745506980@qq.com> 4 | # 5 | # This is free software; you can redistribute it and/or 6 | # modify it under the terms of the GNU Lesser General Public 7 | # License as published by the Free Software Foundation; either 8 | # version 2.1 of the License, or (at your option) any later version. 9 | # 10 | # This is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | # Lesser General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU Lesser General Public 16 | # License along with this library; if not, write to the Free Software 17 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 18 | # USA 19 | # 20 | 21 | 22 | 23 | CROSS_COMPILE = arm-linux- 24 | CC=$(CROSS_COMPILE)gcc 25 | 26 | TARGET = Send_h264 27 | 28 | OBJS += rtmp_send.o 29 | OBJS += x264_encoder.o 30 | OBJS += camer.o 31 | OBJS += main.o 32 | 33 | 34 | INCLUDES = -I./include/ 35 | 36 | LIBS = -lpthread -lrt 37 | 38 | LINK_OPTS =-L./lib -lx264 -lrtmp -lssl -lz -lcrypto 39 | 40 | CFLAGS = -Wall -O2 -g 41 | 42 | LD_FLAGS = $(LIBS) $(INCLUDES) $(LINK_OPTS) 43 | 44 | $(TARGET) : $(OBJS) 45 | $(CC) -o $@ $^ $(LINK_OPTS) 46 | 47 | %.o : %.c 48 | $(CC) -c $< -o $@ $(CFLAGS) 49 | 50 | clean: 51 | rm $(OBJS) $(TARGET) 52 | 53 | -------------------------------------------------------------------------------- /include/rtmp_send.h: -------------------------------------------------------------------------------- 1 | 2 | 3 | /* 4 | * Copyright (C) 2020 JunKe Yuan<745506980@qq.com> 5 | * 6 | * This is free software; you can redistribute it and/or 7 | * modify it under the terms of the GNU Lesser General Public 8 | * License as published by the Free Software Foundation; either 9 | * version 2.1 of the License, or (at your option) any later version. 10 | * 11 | * This is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | * Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public 17 | * License along with this library; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 19 | * USA 20 | * 21 | */ 22 | #ifndef __RTMP_SEND_H 23 | #define __RTMP_SEND_H 24 | 25 | #include"librtmp/rtmp.h" 26 | #include"librtmp/amf.h" 27 | #include"x264_encoder.h" 28 | 29 | extern RTMPPacket * packet_sp; 30 | extern RTMP * rtmp; 31 | 32 | int Rtmp_Begin(char * URL); 33 | 34 | 35 | /*对H264码流进行封包 36 | * type = 1 为IDR 37 | * type = 0 非IDR 38 | * */ 39 | int Send_h264_packet(uint8_t * H264_Stream, int length, int type, uint32_t timer); 40 | 41 | 42 | 43 | /*获取对sps和pps进行封包*/ 44 | RTMPPacket * Create_sps_packet(sps_pps *sp); 45 | 46 | 47 | void RTMP_END(); 48 | 49 | 50 | #endif 51 | /*防止头文件重复定义*/ 52 | -------------------------------------------------------------------------------- /include/x265_config.h: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | * Copyright (C) 2013-2017 MulticoreWare, Inc 3 | * 4 | * Authors: Steve Borho 5 | * 6 | * This program is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA. 19 | * 20 | * This program is also available under a commercial proprietary license. 21 | * For more information, contact us at license @ x265.com. 22 | *****************************************************************************/ 23 | 24 | #ifndef X265_CONFIG_H 25 | #define X265_CONFIG_H 26 | 27 | /* Defines generated at build time */ 28 | 29 | /* Incremented each time public API is changed, X265_BUILD is used as 30 | * the shared library SONAME on platforms which support it. It also 31 | * prevents linking against a different version of the static lib */ 32 | #define X265_BUILD 146 33 | 34 | #endif 35 | -------------------------------------------------------------------------------- /include/librtmp/http.h: -------------------------------------------------------------------------------- 1 | #ifndef __RTMP_HTTP_H__ 2 | #define __RTMP_HTTP_H__ 3 | /* 4 | * Copyright (C) 2010 Howard Chu 5 | * Copyright (C) 2010 Antti Ajanki 6 | * 7 | * This file is part of librtmp. 8 | * 9 | * librtmp is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU Lesser General Public License as 11 | * published by the Free Software Foundation; either version 2.1, 12 | * or (at your option) any later version. 13 | * 14 | * librtmp is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | * GNU General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU Lesser General Public License 20 | * along with librtmp see the file COPYING. If not, write to 21 | * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, 22 | * Boston, MA 02110-1301, USA. 23 | * http://www.gnu.org/copyleft/lgpl.html 24 | */ 25 | 26 | typedef enum { 27 | HTTPRES_OK, /* result OK */ 28 | HTTPRES_OK_NOT_MODIFIED, /* not modified since last request */ 29 | HTTPRES_NOT_FOUND, /* not found */ 30 | HTTPRES_BAD_REQUEST, /* client error */ 31 | HTTPRES_SERVER_ERROR, /* server reported an error */ 32 | HTTPRES_REDIRECTED, /* resource has been moved */ 33 | HTTPRES_LOST_CONNECTION /* connection lost while waiting for data */ 34 | } HTTPResult; 35 | 36 | struct HTTP_ctx { 37 | char *date; 38 | int size; 39 | int status; 40 | void *data; 41 | }; 42 | 43 | typedef size_t (HTTP_read_callback)(void *ptr, size_t size, size_t nmemb, void *stream); 44 | 45 | HTTPResult HTTP_get(struct HTTP_ctx *http, const char *url, HTTP_read_callback *cb); 46 | 47 | #endif 48 | -------------------------------------------------------------------------------- /include/x264_encoder.h: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Copyright (C) 2020 JunKe Yuan<745506980@qq.com> 4 | * 5 | * This is free software; you can redistribute it and/or 6 | * modify it under the terms of the GNU Lesser General Public 7 | * License as published by the Free Software Foundation; either 8 | * version 2.1 of the License, or (at your option) any later version. 9 | * 10 | * This is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | * Lesser General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Lesser General Public 16 | * License along with this library; if not, write to the Free Software 17 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 18 | * USA 19 | * 20 | */ 21 | #ifndef __X264_ENCODER_H 22 | #define __X264_ENCODER_H 23 | #include 24 | #include"x264.h" 25 | #include 26 | #include 27 | #include 28 | typedef struct encode{ 29 | x264_param_t param; //相关配置信息 30 | x264_nal_t *nal; 31 | x264_picture_t picture; 32 | x264_t *handle; 33 | }Encode; 34 | /*SPS PPS*/ 35 | typedef struct sps_pps{ 36 | uint8_t * sps; 37 | uint8_t * pps; 38 | uint32_t sps_len; 39 | uint32_t pps_len; 40 | }sps_pps; 41 | /*x264编码*/ 42 | 43 | typedef struct sps_pps_buf{ 44 | char *buf; 45 | unsigned int length; 46 | }sps_pps_buf; 47 | 48 | 49 | 50 | /*编码一帧数据*/ 51 | int Encode_frame(Encode *en, uint32_t pixformat,int fd ,sps_pps_buf * buf, uint8_t *frame, uint32_t width, uint32_t height, uint32_t timer); 52 | 53 | int Encode_init(Encode *en, sps_pps *sp, uint32_t pixformat, uint32_t width, uint32_t height, uint32_t fps, uint32_t bitrate, int ConstantBitRate); 54 | 55 | void Encode_end(x264_t *handle, x264_picture_t *picture, uint8_t * sps, uint8_t *pps); 56 | 57 | int sps_pps_packet(sps_pps * sp); 58 | 59 | 60 | 61 | #endif 62 | /*防止头文件重复定义*/ 63 | -------------------------------------------------------------------------------- /include/camer.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 JunKe Yuan<745506980@qq.com> 3 | * 4 | * This is free software; you can redistribute it and/or 5 | * modify it under the terms of the GNU Lesser General Public 6 | * License as published by the Free Software Foundation; either 7 | * version 2.1 of the License, or (at your option) any later version. 8 | * 9 | * This is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | * Lesser General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU Lesser General Public 15 | * License along with this library; if not, write to the Free Software 16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 17 | * USA 18 | * 19 | */ 20 | #ifndef __CAMER_H 21 | #define __CAMER_H 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include"rtmp_send.h" 37 | #include"x264_encoder.h" 38 | 39 | #define CLEAN(x) (memset(&(x), 0, sizeof(x))) 40 | 41 | #define WIDTH 640 42 | 43 | #define HEIGHT 480 44 | 45 | typedef struct Video_Buffer{ 46 | void * start; 47 | unsigned int length; 48 | }Video_Buffer; 49 | 50 | 51 | int ioctl_(int fd, int request, void *arg); 52 | 53 | void sys_exit(const char *s); 54 | 55 | int open_device(const char * device_name); 56 | 57 | int open_file(const char * file_name); 58 | 59 | void start_stream(void); 60 | 61 | void end_stream(void); 62 | 63 | int init_device(uint32_t pixformat); 64 | 65 | int init_mmap(void); 66 | 67 | int read_frame(Encode *en, sps_pps_buf * buf, uint32_t pixformat, uint32_t timer); 68 | 69 | int process_frame(Encode *en, sps_pps_buf *buf, uint32_t pixformat, uint32_t timer); 70 | 71 | void close_mmap(void); 72 | 73 | void close_device(void); 74 | 75 | 76 | #endif 77 | /*防止头文件重复定义*/ 78 | -------------------------------------------------------------------------------- /include/librtmp/log.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008-2009 Andrej Stepanchuk 3 | * Copyright (C) 2009-2010 Howard Chu 4 | * 5 | * This file is part of librtmp. 6 | * 7 | * librtmp is free software; you can redistribute it and/or modify 8 | * it under the terms of the GNU Lesser General Public License as 9 | * published by the Free Software Foundation; either version 2.1, 10 | * or (at your option) any later version. 11 | * 12 | * librtmp is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Lesser General Public License 18 | * along with librtmp see the file COPYING. If not, write to 19 | * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, 20 | * Boston, MA 02110-1301, USA. 21 | * http://www.gnu.org/copyleft/lgpl.html 22 | */ 23 | 24 | #ifndef __RTMP_LOG_H__ 25 | #define __RTMP_LOG_H__ 26 | 27 | #include 28 | #include 29 | #include 30 | 31 | #ifdef __cplusplus 32 | extern "C" { 33 | #endif 34 | /* Enable this to get full debugging output */ 35 | /* #define _DEBUG */ 36 | 37 | #ifdef _DEBUG 38 | #undef NODEBUG 39 | #endif 40 | 41 | typedef enum 42 | { RTMP_LOGCRIT=0, RTMP_LOGERROR, RTMP_LOGWARNING, RTMP_LOGINFO, 43 | RTMP_LOGDEBUG, RTMP_LOGDEBUG2, RTMP_LOGALL 44 | } RTMP_LogLevel; 45 | 46 | extern RTMP_LogLevel RTMP_debuglevel; 47 | 48 | typedef void (RTMP_LogCallback)(int level, const char *fmt, va_list); 49 | void RTMP_LogSetCallback(RTMP_LogCallback *cb); 50 | void RTMP_LogSetOutput(FILE *file); 51 | #ifdef __GNUC__ 52 | void RTMP_LogPrintf(const char *format, ...) __attribute__ ((__format__ (__printf__, 1, 2))); 53 | void RTMP_LogStatus(const char *format, ...) __attribute__ ((__format__ (__printf__, 1, 2))); 54 | void RTMP_Log(int level, const char *format, ...) __attribute__ ((__format__ (__printf__, 2, 3))); 55 | #else 56 | void RTMP_LogPrintf(const char *format, ...); 57 | void RTMP_LogStatus(const char *format, ...); 58 | void RTMP_Log(int level, const char *format, ...); 59 | #endif 60 | void RTMP_LogHex(int level, const uint8_t *data, unsigned long len); 61 | void RTMP_LogHexString(int level, const uint8_t *data, unsigned long len); 62 | void RTMP_LogSetLevel(RTMP_LogLevel lvl); 63 | RTMP_LogLevel RTMP_LogGetLevel(void); 64 | 65 | #ifdef __cplusplus 66 | } 67 | #endif 68 | 69 | #endif 70 | -------------------------------------------------------------------------------- /main.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 JunKe Yuan<745506980@qq.com> 3 | * 4 | * This is free software; you can redistribute it and/or 5 | * modify it under the terms of the GNU Lesser General Public 6 | * License as published by the Free Software Foundation; either 7 | * version 2.1 of the License, or (at your option) any later version. 8 | * 9 | * This is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | * Lesser General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU Lesser General Public 15 | * License along with this library; if not, write to the Free Software 16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 17 | * USA 18 | * 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | #include "include/camer.h" 25 | #include "include/rtmp_send.h" 26 | #include "include/x264.h" 27 | #include "include/x264_encoder.h" 28 | 29 | #define DEVICE_NAME "/dev/video0" 30 | 31 | #define FILE_NAME "./out.h264" 32 | 33 | RTMP *rtmp = NULL; 34 | RTMPPacket *packet_sp = NULL; 35 | 36 | #define URL "rtmp://127.0.0.1/live/yuan" 37 | int operation() 38 | { 39 | /* 1、图像格式  如YUYV YUV420 40 | * 2、宽高  640x480 41 | * 3、帧率 42 | * 4、 43 | * 44 | * */ 45 | int fps = 30; 46 | int bitrate = 800; 47 | 48 | uint32_t pixformat = V4L2_PIX_FMT_YUV420; 49 | int ret = 0; 50 | Encode en ; 51 | sps_pps sp; 52 | unsigned int timer_ = 1000/fps; //ms 53 | //初始化和连接RMTP 54 | 55 | ret = Rtmp_Begin(URL); 56 | if (ret == -1){ 57 | fprintf(stderr,"RTMP_Begin is error!\n"); 58 | exit(EXIT_FAILURE); 59 | } 60 | //编码器初始化 61 | ret = Encode_init(&en, &sp, pixformat, WIDTH, HEIGHT, fps, bitrate, 0); 62 | if (ret < 0){ 63 | fprintf(stderr,"Encode_init is error\n"); 64 | exit(EXIT_FAILURE); 65 | } 66 | packet_sp = Create_sps_packet(&sp); 67 | 68 | //0x00 00 00 01 + sps 0x00 00 00 01 + pps 69 | //封装H.264文件的sps和pps 70 | sps_pps_buf buf; 71 | buf.buf = malloc(sp.sps_len + sp.pps_len + 8); 72 | int j = 0; 73 | buf.buf[j++] = 0x00; 74 | buf.buf[j++] = 0x00; 75 | buf.buf[j++] = 0x00; 76 | buf.buf[j++] = 0x01; 77 | memcpy(&buf.buf[j], sp.sps, sp.sps_len); 78 | j += sp.sps_len; 79 | buf.buf[j++] = 0x00; 80 | buf.buf[j++] = 0x00; 81 | buf.buf[j++] = 0x00; 82 | buf.buf[j++] = 0x01; 83 | memcpy(&buf.buf[j],sp.pps, sp.pps_len); 84 | j += sp.pps_len; 85 | buf.length = j; 86 | 87 | ret = open_device(DEVICE_NAME); 88 | if (ret == -1) 89 | exit(EXIT_FAILURE); 90 | open_file(FILE_NAME); 91 | init_device(pixformat); 92 | init_mmap(); 93 | start_stream(); 94 | uint32_t timer = 0; 95 | while(1) 96 | { 97 | timer = timer + timer_; 98 | ret = process_frame(&en, &buf, pixformat, timer); 99 | if (ret == -1) break; 100 | } 101 | end_stream(); 102 | close_mmap(); 103 | close_device(); 104 | Encode_end(en.handle, &en.picture, sp.sps, sp.pps); 105 | RTMP_END(rtmp); 106 | free(buf.buf); 107 | free(packet_sp); 108 | return 0; 109 | } 110 | 111 | 112 | 113 | 114 | int main(int argc, char *argv[]) 115 | { 116 | if (argc > 1){ 117 | fprintf(stderr,"Invalid parameter!\n"); 118 | exit(EXIT_FAILURE); 119 | } 120 | 121 | operation(); 122 | return 0; 123 | } 124 | -------------------------------------------------------------------------------- /include/librtmp/amf.h: -------------------------------------------------------------------------------- 1 | #ifndef __AMF_H__ 2 | #define __AMF_H__ 3 | /* 4 | * Copyright (C) 2005-2008 Team XBMC 5 | * http://www.xbmc.org 6 | * Copyright (C) 2008-2009 Andrej Stepanchuk 7 | * Copyright (C) 2009-2010 Howard Chu 8 | * 9 | * This file is part of librtmp. 10 | * 11 | * librtmp is free software; you can redistribute it and/or modify 12 | * it under the terms of the GNU Lesser General Public License as 13 | * published by the Free Software Foundation; either version 2.1, 14 | * or (at your option) any later version. 15 | * 16 | * librtmp is distributed in the hope that it will be useful, 17 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | * GNU General Public License for more details. 20 | * 21 | * You should have received a copy of the GNU Lesser General Public License 22 | * along with librtmp see the file COPYING. If not, write to 23 | * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, 24 | * Boston, MA 02110-1301, USA. 25 | * http://www.gnu.org/copyleft/lgpl.html 26 | */ 27 | 28 | #include 29 | 30 | #ifndef TRUE 31 | #define TRUE 1 32 | #define FALSE 0 33 | #endif 34 | 35 | #ifdef __cplusplus 36 | extern "C" 37 | { 38 | #endif 39 | 40 | typedef enum 41 | { AMF_NUMBER = 0, AMF_BOOLEAN, AMF_STRING, AMF_OBJECT, 42 | AMF_MOVIECLIP, /* reserved, not used */ 43 | AMF_NULL, AMF_UNDEFINED, AMF_REFERENCE, AMF_ECMA_ARRAY, AMF_OBJECT_END, 44 | AMF_STRICT_ARRAY, AMF_DATE, AMF_LONG_STRING, AMF_UNSUPPORTED, 45 | AMF_RECORDSET, /* reserved, not used */ 46 | AMF_XML_DOC, AMF_TYPED_OBJECT, 47 | AMF_AVMPLUS, /* switch to AMF3 */ 48 | AMF_INVALID = 0xff 49 | } AMFDataType; 50 | 51 | typedef enum 52 | { AMF3_UNDEFINED = 0, AMF3_NULL, AMF3_FALSE, AMF3_TRUE, 53 | AMF3_INTEGER, AMF3_DOUBLE, AMF3_STRING, AMF3_XML_DOC, AMF3_DATE, 54 | AMF3_ARRAY, AMF3_OBJECT, AMF3_XML, AMF3_BYTE_ARRAY 55 | } AMF3DataType; 56 | 57 | typedef struct AVal 58 | { 59 | char *av_val; 60 | int av_len; 61 | } AVal; 62 | #define AVC(str) {str,sizeof(str)-1} 63 | #define AVMATCH(a1,a2) ((a1)->av_len == (a2)->av_len && !memcmp((a1)->av_val,(a2)->av_val,(a1)->av_len)) 64 | 65 | struct AMFObjectProperty; 66 | 67 | typedef struct AMFObject 68 | { 69 | int o_num; 70 | struct AMFObjectProperty *o_props; 71 | } AMFObject; 72 | 73 | typedef struct AMFObjectProperty 74 | { 75 | AVal p_name; 76 | AMFDataType p_type; 77 | union 78 | { 79 | double p_number; 80 | AVal p_aval; 81 | AMFObject p_object; 82 | } p_vu; 83 | int16_t p_UTCoffset; 84 | } AMFObjectProperty; 85 | 86 | char *AMF_EncodeString(char *output, char *outend, const AVal * str); 87 | char *AMF_EncodeNumber(char *output, char *outend, double dVal); 88 | char *AMF_EncodeInt16(char *output, char *outend, short nVal); 89 | char *AMF_EncodeInt24(char *output, char *outend, int nVal); 90 | char *AMF_EncodeInt32(char *output, char *outend, int nVal); 91 | char *AMF_EncodeBoolean(char *output, char *outend, int bVal); 92 | 93 | /* Shortcuts for AMFProp_Encode */ 94 | char *AMF_EncodeNamedString(char *output, char *outend, const AVal * name, const AVal * value); 95 | char *AMF_EncodeNamedNumber(char *output, char *outend, const AVal * name, double dVal); 96 | char *AMF_EncodeNamedBoolean(char *output, char *outend, const AVal * name, int bVal); 97 | 98 | unsigned short AMF_DecodeInt16(const char *data); 99 | unsigned int AMF_DecodeInt24(const char *data); 100 | unsigned int AMF_DecodeInt32(const char *data); 101 | void AMF_DecodeString(const char *data, AVal * str); 102 | void AMF_DecodeLongString(const char *data, AVal * str); 103 | int AMF_DecodeBoolean(const char *data); 104 | double AMF_DecodeNumber(const char *data); 105 | 106 | char *AMF_Encode(AMFObject * obj, char *pBuffer, char *pBufEnd); 107 | char *AMF_EncodeEcmaArray(AMFObject *obj, char *pBuffer, char *pBufEnd); 108 | char *AMF_EncodeArray(AMFObject *obj, char *pBuffer, char *pBufEnd); 109 | 110 | int AMF_Decode(AMFObject * obj, const char *pBuffer, int nSize, 111 | int bDecodeName); 112 | int AMF_DecodeArray(AMFObject * obj, const char *pBuffer, int nSize, 113 | int nArrayLen, int bDecodeName); 114 | int AMF3_Decode(AMFObject * obj, const char *pBuffer, int nSize, 115 | int bDecodeName); 116 | void AMF_Dump(AMFObject * obj); 117 | void AMF_Reset(AMFObject * obj); 118 | 119 | void AMF_AddProp(AMFObject * obj, const AMFObjectProperty * prop); 120 | int AMF_CountProp(AMFObject * obj); 121 | AMFObjectProperty *AMF_GetProp(AMFObject * obj, const AVal * name, 122 | int nIndex); 123 | 124 | AMFDataType AMFProp_GetType(AMFObjectProperty * prop); 125 | void AMFProp_SetNumber(AMFObjectProperty * prop, double dval); 126 | void AMFProp_SetBoolean(AMFObjectProperty * prop, int bflag); 127 | void AMFProp_SetString(AMFObjectProperty * prop, AVal * str); 128 | void AMFProp_SetObject(AMFObjectProperty * prop, AMFObject * obj); 129 | 130 | void AMFProp_GetName(AMFObjectProperty * prop, AVal * name); 131 | void AMFProp_SetName(AMFObjectProperty * prop, AVal * name); 132 | double AMFProp_GetNumber(AMFObjectProperty * prop); 133 | int AMFProp_GetBoolean(AMFObjectProperty * prop); 134 | void AMFProp_GetString(AMFObjectProperty * prop, AVal * str); 135 | void AMFProp_GetObject(AMFObjectProperty * prop, AMFObject * obj); 136 | 137 | int AMFProp_IsValid(AMFObjectProperty * prop); 138 | 139 | char *AMFProp_Encode(AMFObjectProperty * prop, char *pBuffer, char *pBufEnd); 140 | int AMF3Prop_Decode(AMFObjectProperty * prop, const char *pBuffer, 141 | int nSize, int bDecodeName); 142 | int AMFProp_Decode(AMFObjectProperty * prop, const char *pBuffer, 143 | int nSize, int bDecodeName); 144 | 145 | void AMFProp_Dump(AMFObjectProperty * prop); 146 | void AMFProp_Reset(AMFObjectProperty * prop); 147 | 148 | typedef struct AMF3ClassDef 149 | { 150 | AVal cd_name; 151 | char cd_externalizable; 152 | char cd_dynamic; 153 | int cd_num; 154 | AVal *cd_props; 155 | } AMF3ClassDef; 156 | 157 | void AMF3CD_AddProp(AMF3ClassDef * cd, AVal * prop); 158 | AVal *AMF3CD_GetProp(AMF3ClassDef * cd, int idx); 159 | 160 | #ifdef __cplusplus 161 | } 162 | #endif 163 | 164 | #endif /* __AMF_H__ */ 165 | -------------------------------------------------------------------------------- /rtmp_send.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 JunKe Yuan<745506980@qq.com> 3 | * 4 | * This is free software; you can redistribute it and/or 5 | * modify it under the terms of the GNU Lesser General Public 6 | * License as published by the Free Software Foundation; either 7 | * version 2.1 of the License, or (at your option) any later version. 8 | * 9 | * This is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | * Lesser General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU Lesser General Public 15 | * License along with this library; if not, write to the Free Software 16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 17 | * USA 18 | * 19 | */ 20 | #include 21 | 22 | 23 | #include "include/librtmp/amf.h" 24 | #include"include/rtmp_send.h" 25 | #include "include/librtmp/rtmp.h" 26 | 27 | #define RTMP_HEADER_SIZE (sizeof(RTMPPacket) + RTMP_MAX_HEADER_SIZE) 28 | 29 | 30 | int 31 | Rtmp_Begin(char * URL) 32 | { 33 | int ret = 0; 34 | //申请内存-RTMP 35 | rtmp = RTMP_Alloc(); 36 | if (rtmp == NULL){ 37 | perror("RTMP_Alloc"); 38 | return -1; 39 | } 40 | /*初始化*/ 41 | RTMP_Init(rtmp); 42 | 43 | /*设置地址*/ 44 | ret = RTMP_SetupURL(rtmp, URL); 45 | if (ret == FALSE){ 46 | perror("RTMP_SetupURL"); 47 | return -1; 48 | } 49 | /*开启输出模式*/ 50 | RTMP_EnableWrite(rtmp); 51 | /*连接服务器*/ 52 | ret = RTMP_Connect(rtmp, NULL); 53 | if (ret == FALSE){ 54 | perror("RTMP_Connect"); 55 | return -1; 56 | } 57 | /*连接流*/ 58 | ret = RTMP_ConnectStream(rtmp, 0); 59 | if (ret == FALSE){ 60 | perror("RTMP_ConnectStream"); 61 | return -1; 62 | } 63 | 64 | return 0; 65 | } 66 | 67 | 68 | 69 | /*SPS PPS*/ 70 | RTMPPacket * Create_sps_packet(sps_pps *sp) 71 | { 72 | /*分配packet空间*/ 73 | RTMPPacket * packet = (RTMPPacket *)malloc(RTMP_HEADER_SIZE + 512); 74 | if (packet == NULL) return NULL; 75 | 76 | packet->m_body = (char *)packet + RTMP_HEADER_SIZE; 77 | 78 | /*填充视频包数据*/ 79 | int i = 0; 80 | 81 | packet->m_body[i++] = 0x17; 82 | packet->m_body[i++] = 0x00; 83 | packet->m_body[i++] = 0x00; 84 | packet->m_body[i++] = 0x00; 85 | packet->m_body[i++] = 0x00; 86 | 87 | packet->m_body[i++] = 0x01; //版本号 88 | 89 | packet->m_body[i++] = sp->sps[1]; //配置信息 baseline 宽高 90 | packet->m_body[i++] = sp->sps[2]; //兼容性 91 | packet->m_body[i++] = sp->sps[3]; //profile_level 92 | packet->m_body[i++] = 0xFF; //几个字节表示NALU的长度 0xFF & 3 + 1 4个字节 93 | 94 | packet->m_body[i++] = 0xE1; //SPS个数 0xE1 & 0x1F = 1 95 | /*sps 长度 2个字节*/ //网络中采用大端模式 96 | packet->m_body[i++] = (sp->sps_len >> 8) & 0xFF; //低8位 97 | packet->m_body[i++] = sp->sps_len & 0xFF; //高8位 98 | //sps数据 99 | memcpy(&packet->m_body[i], sp->sps, sp->sps_len); 100 | i += sp->sps_len; 101 | //pps个数 102 | packet->m_body[i++] = 0x01; 103 | //整个pps长度 104 | packet->m_body[i++] = (sp->pps_len >> 8) & 0xFF; 105 | packet->m_body[i++] = sp->pps_len & 0xFF; 106 | //pps数据 107 | memcpy(&packet->m_body[i], sp->pps, sp->pps_len); 108 | i += sp->pps_len; 109 | 110 | //packet配置 111 | /*massage type id (1~7)控制协议8,9音视频,10以后AMF编码消息*/ 112 | packet->m_packetType = RTMP_PACKET_TYPE_VIDEO; //视频格式 MSGTYPE ID 0x09 RTMP视频数据包 113 | 114 | //数据长度 115 | packet->m_nBodySize = i; 116 | 117 | //块流ID 118 | packet->m_nChannel = 0x06; //0x06 视频通道 0x07 音频通道 119 | packet->m_nTimeStamp = 0; //绝对时间戳 120 | packet->m_hasAbsTimestamp = 0; //相对时间戳 121 | 122 | 123 | 124 | /* Message Header 125 | * type 0 FULL 通信建立开启时,或切换到后台(标记当前PTS的位置) 126 | * type 1 LARGE 视频数据流标准 127 | * type 2 Relative Timestamp Only 音频数据流标准 (无传输切割,流的完整性) 128 | * type 3 Relative Single Byte 空数据标准,时差标准,延迟标记 129 | * */ 130 | packet->m_headerType = RTMP_PACKET_SIZE_LARGE; //ChunkMsgHeader的类型(4种) 131 | 132 | 133 | packet->m_nInfoField2 = rtmp->m_stream_id; //消息流ID 134 | 135 | return packet; 136 | } 137 | 138 | 139 | int Send_h264_packet(uint8_t * H264_Stream, int length, int type, uint32_t timer) 140 | { 141 | RTMPPacket *packet = (RTMPPacket *)malloc(RTMP_HEADER_SIZE + length + 9); 142 | if (packet == NULL){ 143 | fprintf(stderr, "packet malloc is error!\n"); 144 | return -1; 145 | } 146 | int i = 0; 147 | packet->m_body = (char *)packet + RTMP_HEADER_SIZE; 148 | int ret = 0; 149 | if (type == 1) //关键帧 150 | { 151 | packet->m_body[i++] = 0x17; 152 | packet->m_body[i++] = 0x01; 153 | packet->m_body[i++] = 0x00; 154 | packet->m_body[i++] = 0x00; 155 | packet->m_body[i++] = 0x00; 156 | //NALUSIZE 数据长度 157 | packet->m_body[i++] = (length >> 24) & 0xFF; 158 | packet->m_body[i++] = (length >> 16) & 0xFF; 159 | packet->m_body[i++] = (length >> 8) & 0xFF; 160 | packet->m_body[i++] = length & 0xFF; 161 | 162 | memcpy(&packet->m_body[i], H264_Stream, length); 163 | i += length; 164 | 165 | packet->m_packetType = RTMP_PACKET_TYPE_VIDEO; 166 | //数据长度 167 | packet->m_nBodySize = i; 168 | packet->m_hasAbsTimestamp = 0; 169 | packet->m_nTimeStamp = timer; 170 | packet->m_nChannel = 0x06; 171 | packet->m_headerType = RTMP_PACKET_SIZE_LARGE; 172 | packet->m_nInfoField2 = rtmp->m_stream_id; 173 | //SPS PPS 包 174 | ret = RTMP_SendPacket(rtmp, packet_sp, FALSE); //TRUE 放进发送队列 175 | if (RTMP_IsConnected(rtmp)) 176 | { 177 | ret = RTMP_SendPacket(rtmp, packet, FALSE); 178 | } 179 | } 180 | if (type == 0) 181 | { 182 | packet->m_body[i++] = 0x27; 183 | packet->m_body[i++] = 0x01; 184 | packet->m_body[i++] = 0x00; 185 | packet->m_body[i++] = 0x00; 186 | packet->m_body[i++] = 0x00; 187 | 188 | packet->m_body[i++] = (length >> 24) & 0xFF; 189 | packet->m_body[i++] = (length >> 16) & 0xFF; 190 | packet->m_body[i++] = (length >> 8) & 0xFF; 191 | packet->m_body[i++] = length & 0xFF; 192 | 193 | memcpy(&packet->m_body[i], H264_Stream, length); 194 | i += length; 195 | 196 | packet->m_packetType = RTMP_PACKET_TYPE_VIDEO; 197 | 198 | packet->m_nBodySize = i; 199 | packet->m_nTimeStamp = timer; 200 | packet->m_hasAbsTimestamp = 0; 201 | packet->m_nChannel = 0x06; 202 | packet->m_headerType = RTMP_PACKET_SIZE_MEDIUM; 203 | packet->m_nInfoField2 = rtmp->m_stream_id; 204 | ret = RTMP_SendPacket(rtmp, packet, FALSE); 205 | 206 | } 207 | free(packet); 208 | return ret; 209 | } 210 | void RTMP_END() 211 | { 212 | RTMP_Close(rtmp); 213 | RTMP_Free(rtmp); 214 | free(packet_sp); 215 | } 216 | 217 | 218 | -------------------------------------------------------------------------------- /x264_encoder.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 JunKe Yuan<745506980@qq.com> 3 | * 4 | * This is free software; you can redistribute it and/or 5 | * modify it under the terms of the GNU Lesser General Public 6 | * License as published by the Free Software Foundation; either 7 | * version 2.1 of the License, or (at your option) any later version. 8 | * 9 | * This is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | * Lesser General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU Lesser General Public 15 | * License along with this library; if not, write to the Free Software 16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 17 | * USA 18 | * 19 | */ 20 | 21 | 22 | 23 | #include "include/x264_encoder.h" 24 | #include 25 | #include "include/rtmp_send.h" 26 | #include "include/x264.h" 27 | #include 28 | #include 29 | int 30 | Encode_init(struct encode *en, sps_pps *sp, uint32_t pixformat, uint32_t width, uint32_t height, uint32_t fps, uint32_t bitrate, int ConstantBitRate) 31 | { 32 | //初始化配置 33 | x264_param_default(&en->param); 34 | // zerolatency 选项是为了降低在线转码编码的延迟 35 | // 缓存帧的个数为0 rc_lookahead = 0 36 | // sync_lookhead 关闭线程预测 可减小延迟,但也会降低性能 37 | // B 帧为0 实时视频需要 38 | // sclied_threads = 1 基于分片的线程,默认off 开启该方法在压缩率和编码效率上都略低于默认方法,但是没有编码延迟。除非在编码实时流或者对地延迟要求较高的场合开启该方法 39 | x264_param_default_preset(&en->param, "ultrafast", "zerolatency"); 40 | 41 | /*CPU FLAGS*/ 42 | // 线程设置 自动获取线程大小 43 | en->param.i_sync_lookahead = X264_SYNC_LOOKAHEAD_AUTO;//自动获取线程超前缓冲区的大小 44 | /*自动选择并行编码多帧*/ 45 | en->param.i_threads = X264_SYNC_LOOKAHEAD_AUTO; //取空缓冲区继续使用,不死锁的保证 46 | 47 | // en->param.i_threads = 1; 48 | 49 | /*VIDEO FLAGS*/ 50 | en->param.i_width = width; 51 | en->param.i_height = height; 52 | en->param.i_frame_total = 0; //如果已知要编码的帧数,否则为0 53 | en->param.i_keyint_min = 0; //I帧的最小间隔 54 | en->param.i_keyint_max = (int)fps * 2; //I帧的最大间隔  也就是最大2s一个I帧 55 | en->param.b_annexb = 1; //为1将开始码0x0000 0001放在NAL单元之前 56 | en->param.b_repeat_headers = 0; // 关键帧前面是否放SPS和PPS 0 否 1 放 57 | //在RTMP协议中,SPS和PPS有单独的格式发送,所以这里不让关键帧前面放SPS和PPS 58 | /* if (pixformat == V4L2_PIX_FMT_YUYV) 59 | en->param.i_csp = X264_CSP_I422; //CSP 图像输入格式 YUYV YUV420 60 | 61 | if (pixformat == V4L2_PIX_FMT_YUV420)*/ 62 | en->param.i_csp = X264_CSP_I420; 63 | /*I帧间隔*/ 64 | en->param.i_fps_den = 1; //帧率分母 65 | en->param.i_fps_num = fps; //帧率分子 66 | en->param.i_timebase_num = (int)(fps * 1000 + .5); 67 | en->param.i_timebase_den = 1000; 68 | 69 | 70 | /*B帧设置*/ 71 | en->param.i_bframe = 0; //2幅参考图之间有多少个B帧 作为实时传输 B帧为0 72 | en->param.i_bframe_pyramid = 0; // 保留一些B帧作为引用(参考) 0 off 不使用B帧作为参考帧 1 严格分层 2 正常的 73 | en->param.b_open_gop = 0; //不使用open_gop 码流里面包含B帧的时候才会出现open_gop,一个GOP里面的某一帧在解码时要依赖于前一个GOP的某些帧,这个GOP就成为open-gop。有些解码器不能完全支持open-gop,所以默认是关闭的 74 | en->param.i_bframe_adaptive = X264_B_ADAPT_FAST; //B帧的适应算法 75 | 76 | /*log参数*/ 77 | // en->param.i_log_level = X264_LOG_DEBUG; //打印编码信息 78 | 79 | /*速率控制参数*/ 80 | en->param.rc.i_bitrate = bitrate; //设置比特率 单位时间发送的比特数量 kbps 81 | en->param.rc.i_lookahead = 0; 82 | /*是否为恒定码率*/ 83 | if (!ConstantBitRate) 84 | { 85 | en->param.rc.i_rc_method = X264_RC_ABR; //码率控制,CQP(恒定质量), CRF(恒定码率),ABR(平均码率) 86 | en->param.rc.i_vbv_max_bitrate = bitrate; //平均码率下,最大瞬时码率,默认0 87 | en->param.rc.i_vbv_buffer_size = bitrate; 88 | } 89 | else{ 90 | en->param.rc.b_filler = 1; //设置为CBR模式 91 | en->param.rc.i_rc_method = X264_RC_CRF; //恒定码率 92 | en->param.rc.i_vbv_buffer_size = bitrate; //VBV Video Buffering Verifier 视频缓存检验器 93 | en->param.rc.i_vbv_max_bitrate = bitrate; //平均码率模式下最大瞬时码率 94 | } 95 | /*根据参数初始化X264级别*/ 96 | en->handle = x264_encoder_open(&en->param); 97 | /*初始化图片信息*/ 98 | x264_picture_init(&en->picture); 99 | /*按YUYV格式分配空间 最后要x264_picture_clean*/ 100 | if (pixformat == V4L2_PIX_FMT_YUYV){ 101 | x264_picture_alloc(&en->picture, X264_CSP_I422, width, height); 102 | } 103 | if (pixformat == V4L2_PIX_FMT_YUV420){ 104 | x264_picture_alloc(&en->picture, X264_CSP_I420, width, height); 105 | } 106 | en->picture.i_pts = 0; 107 | int pi_nal = 0; 108 | /*en->nal 返回用于整个流的SPS、PPS 和SEI 109 | *pi_nal 返回的是en->nal的单元数 3 SPS PPS SEI 110 | *en->nal->i_payload 是p_payload有效负载大小也就是p_payload的长度 包含起始码0x00000001 111 | *en->nal->p_payload 是里面存放的是SPS PPS SEI的数据 包含起始码0x00000001 112 | * */ 113 | x264_encoder_headers(en->handle, &en->nal, &pi_nal); 114 | if ( pi_nal > 0 ) 115 | { 116 | int i = 0; 117 | for(i = 0; i < pi_nal; i++) 118 | { 119 | if (en->nal[i].i_type == NAL_SPS) //SPS数据 0x67&1F 120 | { 121 | sp->sps = malloc(en->nal[i].i_payload - 4); //去掉起始码的四个字节 122 | sp->sps_len = en->nal[i].i_payload - 4; 123 | memcpy(sp->sps, en->nal[i].p_payload + 4, sp->sps_len);//跳过起始码 124 | } 125 | /*PPS*/ 126 | if (en->nal[i].i_type == NAL_PPS) 127 | { 128 | sp->pps = malloc(en->nal[i].i_payload - 4); 129 | sp->pps_len = en->nal[i].i_payload - 4; 130 | memcpy(sp->pps, en->nal[i].p_payload + 4, sp->pps_len); 131 | } 132 | } 133 | return 1; //成功获取SPS 和 PPS 134 | } 135 | /*对获取SPS PPS*/ 136 | return 0; 137 | } 138 | 139 | 140 | 141 | int 142 | Encode_frame(Encode *en, uint32_t pixformat, int fd, sps_pps_buf *buf, uint8_t *frame, uint32_t width, uint32_t height, uint32_t timer) 143 | { 144 | 145 | /*H264编码并发送*/ 146 | int num, i; 147 | int index_y, index_u, index_v; 148 | /*plane[0] 、plane[1] 、 plane[2] 分别存储Y、U、V分量*/ 149 | 150 | uint8_t * y = en->picture.img.plane[0]; 151 | uint8_t * u = en->picture.img.plane[1]; 152 | uint8_t * v = en->picture.img.plane[2]; 153 | uint8_t * frame_ = frame; 154 | /*对YUYV图像YUV分量分离*/ 155 | if (pixformat == V4L2_PIX_FMT_YUYV) 156 | { 157 | index_y = 0; 158 | index_u = 0; 159 | index_v = 0; 160 | num = (width * height)*2 - 4; 161 | /*YUYV*/ 162 | for (i = 0; i < num; i = i + 4) 163 | { 164 | *(y + (index_y++)) = *(frame_ + i); 165 | *(u + (index_u++)) = *(frame_ + i + 1); 166 | *(y + (index_y++)) = *(frame_ + i + 2); 167 | *(v + (index_v++)) = *(frame_ + i + 3); 168 | } 169 | } 170 | /*YUV420*/ 171 | if (pixformat == V4L2_PIX_FMT_YUV420){ 172 | index_y = width * height; 173 | index_u =index_y >> 2; //u v 分量长度一致 174 | index_v = index_y + index_u; 175 | /*摄像头采集的是YU12 Y = w*h u = w*h >> 2 176 | *307200 177 | *384000 178 | * 179 | * 180 | * 460800 181 | * */ 182 | memcpy(y, frame_, index_y); //分离Y分量 183 | memcpy(u, frame_ + index_y, index_u); 184 | memcpy(v, frame_ + index_v, index_u); 185 | #if 0 186 | frame_ = frame_ + index_y; 187 | 188 | num = (index_y >> 1) - 2; 189 | index_v = 0; 190 | index_u = 0; 191 | for (i = 0; i < num; i = i + 2) 192 | { 193 | *(u + index_v++) = *(frame_ + i); 194 | *(v + index_u++) = *(frame_ + i + 1); 195 | } 196 | #endif 197 | } 198 | /*对图像进行编码*/ 199 | int pi_nal = 0; 200 | x264_picture_t out_picture; 201 | x264_picture_init(&out_picture); 202 | int type = 0; 203 | int ret = x264_encoder_encode(en->handle, &en->nal, &pi_nal, &en->picture, &out_picture); 204 | if (ret < 0){ 205 | fprintf(stderr,"x264_encoder_encode is error\n"); 206 | return -1; 207 | } 208 | // en->picture.i_pts++; 209 | /* 获取编码后的数据*/ 210 | if (pi_nal > 0) 211 | { 212 | for (i = 0; i < pi_nal; i++) 213 | { 214 | type = 0; 215 | if (en->nal[i].i_type == NAL_SLICE || en->nal[i].i_type == NAL_SLICE_IDR) 216 | { 217 | if (en->nal[i].i_type == NAL_SLICE_IDR) //如果是关键帧 218 | { 219 | type = 1; //标记为关键帧 220 | //写入文件 221 | #if 0 222 | //I帧前面需要有sps + pps信息 223 | ret = write(fd, buf->buf, buf->length); //写入sps pps 224 | if (ret == -1){ 225 | fprintf(stderr, "write sps_pps_buf is error!\n"); 226 | return -1; 227 | } 228 | #endif 229 | } 230 | 231 | /*发送编码过后的数据*/ 232 | #if 1 233 | int ret = Send_h264_packet(en->nal[i].p_payload + 4, en->nal[i].i_payload - 4, type, timer); 234 | if (ret < 0){ 235 | fprintf(stderr,"Send_h264_packet is error\n"); 236 | return -1; 237 | } 238 | #if 0 239 | //写入文件 240 | ret = write(fd, en->nal[i].p_payload, en->nal[i].i_payload); 241 | if (ret == -1) 242 | { 243 | fprintf(stderr, "write frame is error !\n"); 244 | return -1; 245 | } 246 | #endif 247 | #endif 248 | } 249 | } 250 | } 251 | return 0; 252 | } 253 | 254 | void Encode_end(x264_t *handle, x264_picture_t * picture, uint8_t *sps, uint8_t * pps) 255 | { 256 | /*释放内存*/ 257 | free(sps); 258 | sps = NULL; 259 | free(pps); 260 | pps = NULL; 261 | 262 | /*清空picture*/ 263 | x264_picture_clean(picture); 264 | 265 | /*关闭编码*/ 266 | x264_encoder_close(handle); 267 | 268 | } 269 | 270 | 271 | /*对sps和pps进行封包*/ 272 | 273 | 274 | 275 | 276 | -------------------------------------------------------------------------------- /camer.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 JunKe Yuan<745506980@qq.com> 3 | * 4 | * This is free software; you can redistribute it and/or 5 | * modify it under the terms of the GNU Lesser General Public 6 | * License as published by the Free Software Foundation; either 7 | * version 2.1 of the License, or (at your option) any later version. 8 | * 9 | * This is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | * Lesser General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU Lesser General Public 15 | * License along with this library; if not, write to the Free Software 16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 17 | * USA 18 | * 19 | */ 20 | 21 | #include"./include/camer.h" 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include "include/rtmp_send.h" 27 | #include "include/x264_encoder.h" 28 | #include 29 | #include 30 | 31 | 32 | int fd; 33 | int file_fd; 34 | int frame_size; 35 | static Video_Buffer * buffer = NULL; 36 | int ioctl_(int fd, int request, void *arg) 37 | { 38 | int ret = 0; 39 | do{ 40 | ret = ioctl(fd, request, arg); 41 | }while(ret == -1 && ret == EINTR); 42 | return ret; 43 | } 44 | 45 | int open_device(const char * device_name) 46 | { 47 | struct stat st; 48 | if( -1 == stat( device_name, &st ) ) 49 | { 50 | printf( "Cannot identify '%s'\n" , device_name ); 51 | return -1; 52 | } 53 | 54 | if ( !S_ISCHR( st.st_mode ) ) 55 | { 56 | printf( "%s is no device\n" , device_name ); 57 | return -1; 58 | } 59 | 60 | fd = open(device_name, O_RDWR | O_NONBLOCK , 0); 61 | if ( -1 == fd ) 62 | { 63 | printf( "Cannot open '%s'\n" , device_name ); 64 | return -1; 65 | } 66 | return 0; 67 | } 68 | 69 | 70 | 71 | int init_device(uint32_t pixformat) 72 | { 73 | //查询设备信息 74 | struct v4l2_capability cap; 75 | 76 | if (ioctl_(fd, VIDIOC_QUERYCAP, &cap) == -1) 77 | { 78 | perror("VIDIOC_QUERYCAP"); 79 | return -1; 80 | } 81 | printf("---------------------LINE:%d\n", __LINE__); 82 | printf("DriverName:%s\nCard Name:%s\nBus info:%s\nDriverVersion:%u.%u.%u\n", 83 | cap.driver,cap.card,cap.bus_info,(cap.version>>16)&0xFF,(cap.version>>8)&0xFF,(cap.version)&0xFF); 84 | 85 | 86 | 87 | //选择视频输入 88 | struct v4l2_input input; 89 | CLEAN(input); 90 | input.index = 0; 91 | if ( ioctl_(fd, VIDIOC_S_INPUT,&input) == -1){ 92 | printf("VIDIOC_S_INPUT IS ERROR! LINE:%d\n",__LINE__); 93 | return -1; 94 | } 95 | 96 | 97 | /*查看摄像头支持的视频格式*/ 98 | struct v4l2_fmtdesc fmtdesc; 99 | // struct v4l2_frmsizeenum frmsize; 100 | fmtdesc.index = 0; 101 | fmtdesc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; 102 | printf("fm:\n"); 103 | while(ioctl(fd, VIDIOC_ENUM_FMT, &fmtdesc) != -1){ //列举出所有支持的格式 104 | printf("%d.%s %c%c%c%c\n", fmtdesc.index + 1, fmtdesc.description, 105 | fmtdesc.pixelformat & 0xFF, 106 | (fmtdesc.pixelformat >> 8) & 0xFF, 107 | (fmtdesc.pixelformat >> 16) & 0xFF, 108 | (fmtdesc.pixelformat >> 24) & 0xFF); 109 | #if 0 110 | frmsize.pixel_format = fmtdesc.pixelformat; 111 | frmsize.index = 0; 112 | 113 | while(ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &frmsize) != -1){ 114 | printf("%dx%d\n",frmsize.discrete.width, frmsize.discrete.height); 115 | frmsize.index++; 116 | } 117 | #endif 118 | fmtdesc.index++; 119 | } 120 | /*查看摄像头支持的分辨率*/ 121 | 122 | //设置帧格式 123 | struct v4l2_format fmt; 124 | CLEAN(fmt); 125 | fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; 126 | fmt.fmt.pix.width = WIDTH; 127 | fmt.fmt.pix.height = HEIGHT; 128 | //视频格式 129 | 130 | fmt.fmt.pix.pixelformat = pixformat; 131 | 132 | // fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YVU420; 133 | // fmt.fmt.pix.field = V4L2_FIELD_INTERLACED; 134 | if (ioctl_(fd, VIDIOC_S_FMT, &fmt) == -1) 135 | { 136 | printf("VIDIOC_S_FMT IS ERROR! LINE:%d\n",__LINE__); 137 | return -1; 138 | } 139 | fmt.type = V4L2_BUF_TYPE_PRIVATE; 140 | if (ioctl_(fd, VIDIOC_S_FMT, &fmt) == -1){ 141 | printf("VIDIOC_S_FMT IS ERROR! LINE:%d\n", __LINE__); 142 | return -1; 143 | } 144 | 145 | //查看帧格式 146 | fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; 147 | if ( ioctl_(fd, VIDIOC_G_FMT, &fmt) == -1){ 148 | printf("VIDIOC_G_FMT IS ERROR! LINE:%d\n", __LINE__); 149 | return -1; 150 | } 151 | printf("width:%d\nheight:%d\npixelformat:%c%c%c%c field:%d\n", 152 | fmt.fmt.pix.width, fmt.fmt.pix.height, 153 | fmt.fmt.pix.pixelformat & 0xFF, 154 | (fmt.fmt.pix.pixelformat >> 8) & 0xFF, 155 | (fmt.fmt.pix.pixelformat >> 16) & 0xFF, 156 | (fmt.fmt.pix.pixelformat >> 24) & 0xFF, 157 | fmt.fmt.pix.field 158 | 159 | ); 160 | #if 0 161 | /*设置流相关  帧率*/ 162 | struct v4l2_streamparm parm; 163 | 164 | CLEAN(parm); 165 | 166 | parm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; 167 | 168 | parm.parm.capture.capability = V4L2_CAP_TIMEPERFRAME; //是否可以被timeperframe参数控制帧率 169 | parm.parm.capture.timeperframe.denominator = 30; //时间间隔分母 170 | parm.parm.capture.timeperframe.numerator = 1; //分子 171 | 172 | if (ioctl_(fd, VIDIOC_S_PARM, &parm) == -1){ 173 | // printf("VIDIOC_S_PARM IS ERROR! \n"); 174 | perror("VIDIOC_S_PARM"); 175 | return -1; 176 | } 177 | 178 | if (ioctl_(fd, VIDIOC_G_PARM, (struct v4l2_streamparm*)&parm) == -1){ 179 | printf("VIDIOC_G_PARM IS ERROR! \n"); 180 | return -1; 181 | } 182 | #endif 183 | 184 | #if 1 185 | /*YUYV*/ 186 | __u32 min = fmt.fmt.pix.width * 2; 187 | if ( fmt.fmt.pix.bytesperline < min ) 188 | fmt.fmt.pix.bytesperline = min; 189 | /*YUV420*/ 190 | min = ( unsigned int )WIDTH * HEIGHT * 3 / 2; 191 | if ( fmt.fmt.pix.sizeimage < min ) 192 | fmt.fmt.pix.sizeimage = min; 193 | frame_size = fmt.fmt.pix.sizeimage; 194 | printf("After Buggy driver paranoia\n"); 195 | printf(" >>fmt.fmt.pix.sizeimage = %d\n", fmt.fmt.pix.sizeimage); 196 | printf(" >>fmt.fmt.pix.bytesperline = %d\n", fmt.fmt.pix.bytesperline); 197 | printf("-#-#-#-#-#-#-#-#-#-#-#-#-#-\n"); 198 | printf("\n"); 199 | #endif 200 | 201 | return 0; 202 | 203 | } 204 | 205 | int init_mmap() 206 | { 207 | //申请帧缓冲区 208 | struct v4l2_requestbuffers req; 209 | CLEAN(req); 210 | req.count = 4; 211 | req.memory = V4L2_MEMORY_MMAP; //使用内存映射缓冲区 212 | req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; 213 | //申请4个帧缓冲区,在内核空间中 214 | if ( ioctl_(fd, VIDIOC_REQBUFS, &req) == -1 ) 215 | { 216 | printf("VIDIOC_REQBUFS IS ERROR! LINE:%d\n",__LINE__); 217 | return -1; 218 | } 219 | //获取每个帧信息,并映射到用户空间 220 | buffer = (Video_Buffer *)calloc(req.count, sizeof(Video_Buffer)); 221 | if (buffer == NULL){ 222 | printf("calloc is error! LINE:%d\n",__LINE__); 223 | return -1; 224 | } 225 | 226 | struct v4l2_buffer buf; 227 | int buf_index = 0; 228 | for (buf_index = 0; buf_index < req.count; buf_index ++) 229 | { 230 | CLEAN(buf); 231 | buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; 232 | buf.index = buf_index; 233 | buf.memory = V4L2_MEMORY_MMAP; 234 | if (ioctl_(fd, VIDIOC_QUERYBUF, &buf) == -1) //获取每个帧缓冲区的信息 如length和offset 235 | { 236 | printf("VIDIOC_QUERYBUF IS ERROR! LINE:%d\n",__LINE__); 237 | return -1; 238 | } 239 | //将内核空间中的帧缓冲区映射到用户空间 240 | buffer[buf_index].length = buf.length; 241 | buffer[buf_index].start = mmap(NULL, //由内核分配映射的起始地址 242 | buf.length,//长度 243 | PROT_READ | PROT_WRITE, //可读写 244 | MAP_SHARED,//可共享 245 | fd, 246 | buf.m.offset); 247 | if (buffer[buf_index].start == MAP_FAILED){ 248 | printf("MAP_FAILED LINE:%d\n",__LINE__); 249 | return -1; 250 | } 251 | //将帧缓冲区放入视频输入队列 252 | if (ioctl_(fd, VIDIOC_QBUF, &buf) == -1) 253 | { 254 | printf("VIDIOC_QBUF IS ERROR! LINE:%d\n", __LINE__); 255 | return -1; 256 | } 257 | printf("Frame buffer :%d address :0x%x length:%d\n",buf_index, (__u32)buffer[buf_index].start, buffer[buf_index].length); 258 | } 259 | return 0; 260 | } 261 | 262 | void start_stream() 263 | { 264 | enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE; 265 | if (ioctl_(fd, VIDIOC_STREAMON, &type) == -1){ 266 | fprintf(stderr, "VIDIOC_STREAMON IS ERROR! LINE:%d\n", __LINE__); 267 | exit(EXIT_FAILURE); 268 | } 269 | } 270 | void end_stream() 271 | { 272 | enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE; 273 | if (ioctl_(fd, VIDIOC_STREAMOFF, &type) == -1){ 274 | fprintf(stderr, "VIDIOC_STREAMOFF IS ERROR! LINE:%d\n", __LINE__); 275 | exit(EXIT_FAILURE); 276 | } 277 | } 278 | 279 | int read_frame(Encode *en, sps_pps_buf *buf_sp, uint32_t pixformat, uint32_t timer) 280 | { 281 | struct v4l2_buffer buf; 282 | int ret = 0; 283 | CLEAN(buf); 284 | buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; 285 | buf.memory = V4L2_MEMORY_MMAP; 286 | if (ioctl_(fd, VIDIOC_DQBUF, &buf) == -1){ 287 | printf("VIDIOC_DQBUF! LINEL:%d\n", __LINE__); 288 | return -1; 289 | } 290 | // time_t start,end; 291 | // start = time(NULL); 292 | #if 0 293 | 294 | ret = write(file_fd, buffer[0].start ,frame_size); 295 | // printf("write:%d\n",frame_size); 296 | 297 | #endif 298 | #if 1 299 | ret = Encode_frame(en, pixformat, file_fd, buf_sp, buffer[0].start, WIDTH, HEIGHT, timer); 300 | if (ret == -1){ 301 | fprintf(stderr,"Encode_frame\n"); 302 | return -1; 303 | } 304 | #endif 305 | // end = time(NULL); 306 | // printf("time:%0.f\n",difftime(end, start)); 307 | if (ioctl_(fd, VIDIOC_QBUF, &buf) == -1){ 308 | printf("VIDIOC_QBUF! LINE:%d\n", __LINE__); 309 | return -1; 310 | } 311 | return 0; 312 | } 313 | 314 | 315 | int open_file(const char * file_name) 316 | { 317 | 318 | file_fd = open(file_name, O_RDWR | O_CREAT, 0777); 319 | if (file_fd == -1) 320 | { 321 | printf("open file is error! LINE:%d\n", __LINE__); 322 | return -1; 323 | } 324 | return 0; 325 | // file = fopen(file_name, "wr+"); 326 | } 327 | 328 | void close_mmap() 329 | { 330 | int i = 0; 331 | for (i = 0; i < 4 ; i++) 332 | { 333 | munmap(buffer[i].start, buffer[i].length); 334 | } 335 | free(buffer); 336 | } 337 | void close_device() 338 | { 339 | close(fd); 340 | close(file_fd); 341 | } 342 | int process_frame(Encode * en, sps_pps_buf * buf, uint32_t pixformat, uint32_t timer) 343 | { 344 | struct timeval tvptr; 345 | int ret; 346 | tvptr.tv_usec = 0; //等待50 us 347 | tvptr.tv_sec = 2; 348 | fd_set fdread; 349 | FD_ZERO(&fdread); 350 | FD_SET(fd, &fdread); 351 | ret = select(fd + 1, &fdread, NULL, NULL, &tvptr); 352 | if (ret == -1){ 353 | perror("EXIT_FAILURE"); 354 | exit(EXIT_FAILURE); 355 | } 356 | if (ret == 0){ 357 | printf("timeout! \n"); 358 | } 359 | // struct timeval start,end; 360 | // gettimeofday(&start, NULL); 361 | 362 | if(read_frame(en, buf, pixformat, timer) == -1) 363 | { 364 | fprintf(stderr, "readframe is error\n"); 365 | return -1; 366 | } 367 | 368 | // gettimeofday(&end, NULL); 369 | // printf("time:%ldms\n",(end.tv_sec - start.tv_sec)*1000 + (end.tv_usec - start.tv_usec)/1000); 370 | 371 | return 0; 372 | } 373 | -------------------------------------------------------------------------------- /include/librtmp/rtmp.h: -------------------------------------------------------------------------------- 1 | #ifndef __RTMP_H__ 2 | #define __RTMP_H__ 3 | /* 4 | * Copyright (C) 2005-2008 Team XBMC 5 | * http://www.xbmc.org 6 | * Copyright (C) 2008-2009 Andrej Stepanchuk 7 | * Copyright (C) 2009-2010 Howard Chu 8 | * 9 | * This file is part of librtmp. 10 | * 11 | * librtmp is free software; you can redistribute it and/or modify 12 | * it under the terms of the GNU Lesser General Public License as 13 | * published by the Free Software Foundation; either version 2.1, 14 | * or (at your option) any later version. 15 | * 16 | * librtmp is distributed in the hope that it will be useful, 17 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | * GNU General Public License for more details. 20 | * 21 | * You should have received a copy of the GNU Lesser General Public License 22 | * along with librtmp see the file COPYING. If not, write to 23 | * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, 24 | * Boston, MA 02110-1301, USA. 25 | * http://www.gnu.org/copyleft/lgpl.html 26 | */ 27 | 28 | #if !defined(NO_CRYPTO) && !defined(CRYPTO) 29 | #define CRYPTO 30 | #endif 31 | 32 | #include 33 | #include 34 | #include 35 | 36 | #include "amf.h" 37 | 38 | #ifdef __cplusplus 39 | extern "C" 40 | { 41 | #endif 42 | 43 | #define RTMP_LIB_VERSION 0x020300 /* 2.3 */ 44 | 45 | #define RTMP_FEATURE_HTTP 0x01 46 | #define RTMP_FEATURE_ENC 0x02 47 | #define RTMP_FEATURE_SSL 0x04 48 | #define RTMP_FEATURE_MFP 0x08 /* not yet supported */ 49 | #define RTMP_FEATURE_WRITE 0x10 /* publish, not play */ 50 | #define RTMP_FEATURE_HTTP2 0x20 /* server-side rtmpt */ 51 | 52 | #define RTMP_PROTOCOL_UNDEFINED -1 53 | #define RTMP_PROTOCOL_RTMP 0 54 | #define RTMP_PROTOCOL_RTMPE RTMP_FEATURE_ENC 55 | #define RTMP_PROTOCOL_RTMPT RTMP_FEATURE_HTTP 56 | #define RTMP_PROTOCOL_RTMPS RTMP_FEATURE_SSL 57 | #define RTMP_PROTOCOL_RTMPTE (RTMP_FEATURE_HTTP|RTMP_FEATURE_ENC) 58 | #define RTMP_PROTOCOL_RTMPTS (RTMP_FEATURE_HTTP|RTMP_FEATURE_SSL) 59 | #define RTMP_PROTOCOL_RTMFP RTMP_FEATURE_MFP 60 | 61 | #define RTMP_DEFAULT_CHUNKSIZE 128 62 | 63 | /* needs to fit largest number of bytes recv() may return */ 64 | #define RTMP_BUFFER_CACHE_SIZE (16*1024) 65 | 66 | #define RTMP_CHANNELS 65600 67 | 68 | extern const char RTMPProtocolStringsLower[][7]; 69 | extern const AVal RTMP_DefaultFlashVer; 70 | extern int RTMP_ctrlC; 71 | 72 | uint32_t RTMP_GetTime(void); 73 | 74 | /* RTMP_PACKET_TYPE_... 0x00 */ 75 | #define RTMP_PACKET_TYPE_CHUNK_SIZE 0x01 76 | /* RTMP_PACKET_TYPE_... 0x02 */ 77 | #define RTMP_PACKET_TYPE_BYTES_READ_REPORT 0x03 78 | #define RTMP_PACKET_TYPE_CONTROL 0x04 79 | #define RTMP_PACKET_TYPE_SERVER_BW 0x05 80 | #define RTMP_PACKET_TYPE_CLIENT_BW 0x06 81 | /* RTMP_PACKET_TYPE_... 0x07 */ 82 | #define RTMP_PACKET_TYPE_AUDIO 0x08 83 | #define RTMP_PACKET_TYPE_VIDEO 0x09 84 | /* RTMP_PACKET_TYPE_... 0x0A */ 85 | /* RTMP_PACKET_TYPE_... 0x0B */ 86 | /* RTMP_PACKET_TYPE_... 0x0C */ 87 | /* RTMP_PACKET_TYPE_... 0x0D */ 88 | /* RTMP_PACKET_TYPE_... 0x0E */ 89 | #define RTMP_PACKET_TYPE_FLEX_STREAM_SEND 0x0F 90 | #define RTMP_PACKET_TYPE_FLEX_SHARED_OBJECT 0x10 91 | #define RTMP_PACKET_TYPE_FLEX_MESSAGE 0x11 92 | #define RTMP_PACKET_TYPE_INFO 0x12 93 | #define RTMP_PACKET_TYPE_SHARED_OBJECT 0x13 94 | #define RTMP_PACKET_TYPE_INVOKE 0x14 95 | /* RTMP_PACKET_TYPE_... 0x15 */ 96 | #define RTMP_PACKET_TYPE_FLASH_VIDEO 0x16 97 | 98 | #define RTMP_MAX_HEADER_SIZE 18 99 | 100 | #define RTMP_PACKET_SIZE_LARGE 0 101 | #define RTMP_PACKET_SIZE_MEDIUM 1 102 | #define RTMP_PACKET_SIZE_SMALL 2 103 | #define RTMP_PACKET_SIZE_MINIMUM 3 104 | 105 | typedef struct RTMPChunk 106 | { 107 | int c_headerSize; 108 | int c_chunkSize; 109 | char *c_chunk; 110 | char c_header[RTMP_MAX_HEADER_SIZE]; 111 | } RTMPChunk; 112 | 113 | typedef struct RTMPPacket 114 | { 115 | uint8_t m_headerType; 116 | uint8_t m_packetType; 117 | uint8_t m_hasAbsTimestamp; /* timestamp absolute or relative? */ 118 | int m_nChannel; 119 | uint32_t m_nTimeStamp; /* timestamp */ 120 | int32_t m_nInfoField2; /* last 4 bytes in a long header */ 121 | uint32_t m_nBodySize; 122 | uint32_t m_nBytesRead; 123 | RTMPChunk *m_chunk; 124 | char *m_body; 125 | } RTMPPacket; 126 | 127 | typedef struct RTMPSockBuf 128 | { 129 | int sb_socket; 130 | int sb_size; /* number of unprocessed bytes in buffer */ 131 | char *sb_start; /* pointer into sb_pBuffer of next byte to process */ 132 | char sb_buf[RTMP_BUFFER_CACHE_SIZE]; /* data read from socket */ 133 | int sb_timedout; 134 | void *sb_ssl; 135 | } RTMPSockBuf; 136 | 137 | void RTMPPacket_Reset(RTMPPacket *p); 138 | void RTMPPacket_Dump(RTMPPacket *p); 139 | int RTMPPacket_Alloc(RTMPPacket *p, uint32_t nSize); 140 | void RTMPPacket_Free(RTMPPacket *p); 141 | 142 | #define RTMPPacket_IsReady(a) ((a)->m_nBytesRead == (a)->m_nBodySize) 143 | 144 | typedef struct RTMP_LNK 145 | { 146 | AVal hostname; 147 | AVal sockshost; 148 | 149 | AVal playpath0; /* parsed from URL */ 150 | AVal playpath; /* passed in explicitly */ 151 | AVal tcUrl; 152 | AVal swfUrl; 153 | AVal pageUrl; 154 | AVal app; 155 | AVal auth; 156 | AVal flashVer; 157 | AVal subscribepath; 158 | AVal usherToken; 159 | AVal token; 160 | AVal pubUser; 161 | AVal pubPasswd; 162 | AMFObject extras; 163 | int edepth; 164 | 165 | int seekTime; 166 | int stopTime; 167 | 168 | #define RTMP_LF_AUTH 0x0001 /* using auth param */ 169 | #define RTMP_LF_LIVE 0x0002 /* stream is live */ 170 | #define RTMP_LF_SWFV 0x0004 /* do SWF verification */ 171 | #define RTMP_LF_PLST 0x0008 /* send playlist before play */ 172 | #define RTMP_LF_BUFX 0x0010 /* toggle stream on BufferEmpty msg */ 173 | #define RTMP_LF_FTCU 0x0020 /* free tcUrl on close */ 174 | #define RTMP_LF_FAPU 0x0040 /* free app on close */ 175 | int lFlags; 176 | 177 | int swfAge; 178 | 179 | int protocol; 180 | int timeout; /* connection timeout in seconds */ 181 | 182 | int pFlags; /* unused, but kept to avoid breaking ABI */ 183 | 184 | unsigned short socksport; 185 | unsigned short port; 186 | 187 | #ifdef CRYPTO 188 | #define RTMP_SWF_HASHLEN 32 189 | void *dh; /* for encryption */ 190 | void *rc4keyIn; 191 | void *rc4keyOut; 192 | 193 | uint32_t SWFSize; 194 | uint8_t SWFHash[RTMP_SWF_HASHLEN]; 195 | char SWFVerificationResponse[RTMP_SWF_HASHLEN+10]; 196 | #endif 197 | } RTMP_LNK; 198 | 199 | /* state for read() wrapper */ 200 | typedef struct RTMP_READ 201 | { 202 | char *buf; 203 | char *bufpos; 204 | unsigned int buflen; 205 | uint32_t timestamp; 206 | uint8_t dataType; 207 | uint8_t flags; 208 | #define RTMP_READ_HEADER 0x01 209 | #define RTMP_READ_RESUME 0x02 210 | #define RTMP_READ_NO_IGNORE 0x04 211 | #define RTMP_READ_GOTKF 0x08 212 | #define RTMP_READ_GOTFLVK 0x10 213 | #define RTMP_READ_SEEKING 0x20 214 | int8_t status; 215 | #define RTMP_READ_COMPLETE -3 216 | #define RTMP_READ_ERROR -2 217 | #define RTMP_READ_EOF -1 218 | #define RTMP_READ_IGNORE 0 219 | 220 | /* if bResume == TRUE */ 221 | uint8_t initialFrameType; 222 | uint32_t nResumeTS; 223 | char *metaHeader; 224 | char *initialFrame; 225 | uint32_t nMetaHeaderSize; 226 | uint32_t nInitialFrameSize; 227 | uint32_t nIgnoredFrameCounter; 228 | uint32_t nIgnoredFlvFrameCounter; 229 | } RTMP_READ; 230 | 231 | typedef struct RTMP_METHOD 232 | { 233 | AVal name; 234 | int num; 235 | } RTMP_METHOD; 236 | 237 | typedef struct RTMP 238 | { 239 | int m_inChunkSize; 240 | int m_outChunkSize; 241 | int m_nBWCheckCounter; 242 | int m_nBytesIn; 243 | int m_nBytesInSent; 244 | int m_nBufferMS; 245 | int m_stream_id; /* returned in _result from createStream */ 246 | int m_mediaChannel; 247 | uint32_t m_mediaStamp; 248 | uint32_t m_pauseStamp; 249 | int m_pausing; 250 | int m_nServerBW; 251 | int m_nClientBW; 252 | uint8_t m_nClientBW2; 253 | uint8_t m_bPlaying; 254 | uint8_t m_bSendEncoding; 255 | uint8_t m_bSendCounter; 256 | 257 | int m_numInvokes; 258 | int m_numCalls; 259 | RTMP_METHOD *m_methodCalls; /* remote method calls queue */ 260 | 261 | int m_channelsAllocatedIn; 262 | int m_channelsAllocatedOut; 263 | RTMPPacket **m_vecChannelsIn; 264 | RTMPPacket **m_vecChannelsOut; 265 | int *m_channelTimestamp; /* abs timestamp of last packet */ 266 | 267 | double m_fAudioCodecs; /* audioCodecs for the connect packet */ 268 | double m_fVideoCodecs; /* videoCodecs for the connect packet */ 269 | double m_fEncoding; /* AMF0 or AMF3 */ 270 | 271 | double m_fDuration; /* duration of stream in seconds */ 272 | 273 | int m_msgCounter; /* RTMPT stuff */ 274 | int m_polling; 275 | int m_resplen; 276 | int m_unackd; 277 | AVal m_clientID; 278 | 279 | RTMP_READ m_read; 280 | RTMPPacket m_write; 281 | RTMPSockBuf m_sb; 282 | RTMP_LNK Link; 283 | } RTMP; 284 | 285 | int RTMP_ParseURL(const char *url, int *protocol, AVal *host, 286 | unsigned int *port, AVal *playpath, AVal *app); 287 | 288 | void RTMP_ParsePlaypath(AVal *in, AVal *out); 289 | void RTMP_SetBufferMS(RTMP *r, int size); 290 | void RTMP_UpdateBufferMS(RTMP *r); 291 | 292 | int RTMP_SetOpt(RTMP *r, const AVal *opt, AVal *arg); 293 | int RTMP_SetupURL(RTMP *r, char *url); 294 | void RTMP_SetupStream(RTMP *r, int protocol, 295 | AVal *hostname, 296 | unsigned int port, 297 | AVal *sockshost, 298 | AVal *playpath, 299 | AVal *tcUrl, 300 | AVal *swfUrl, 301 | AVal *pageUrl, 302 | AVal *app, 303 | AVal *auth, 304 | AVal *swfSHA256Hash, 305 | uint32_t swfSize, 306 | AVal *flashVer, 307 | AVal *subscribepath, 308 | AVal *usherToken, 309 | int dStart, 310 | int dStop, int bLiveStream, long int timeout); 311 | 312 | int RTMP_Connect(RTMP *r, RTMPPacket *cp); 313 | struct sockaddr; 314 | int RTMP_Connect0(RTMP *r, struct sockaddr *svc); 315 | int RTMP_Connect1(RTMP *r, RTMPPacket *cp); 316 | int RTMP_Serve(RTMP *r); 317 | int RTMP_TLS_Accept(RTMP *r, void *ctx); 318 | 319 | int RTMP_ReadPacket(RTMP *r, RTMPPacket *packet); 320 | int RTMP_SendPacket(RTMP *r, RTMPPacket *packet, int queue); 321 | int RTMP_SendChunk(RTMP *r, RTMPChunk *chunk); 322 | int RTMP_IsConnected(RTMP *r); 323 | int RTMP_Socket(RTMP *r); 324 | int RTMP_IsTimedout(RTMP *r); 325 | double RTMP_GetDuration(RTMP *r); 326 | int RTMP_ToggleStream(RTMP *r); 327 | 328 | int RTMP_ConnectStream(RTMP *r, int seekTime); 329 | int RTMP_ReconnectStream(RTMP *r, int seekTime); 330 | void RTMP_DeleteStream(RTMP *r); 331 | int RTMP_GetNextMediaPacket(RTMP *r, RTMPPacket *packet); 332 | int RTMP_ClientPacket(RTMP *r, RTMPPacket *packet); 333 | 334 | void RTMP_Init(RTMP *r); 335 | void RTMP_Close(RTMP *r); 336 | RTMP *RTMP_Alloc(void); 337 | void RTMP_Free(RTMP *r); 338 | void RTMP_EnableWrite(RTMP *r); 339 | 340 | void *RTMP_TLS_AllocServerContext(const char* cert, const char* key); 341 | void RTMP_TLS_FreeServerContext(void *ctx); 342 | 343 | int RTMP_LibVersion(void); 344 | void RTMP_UserInterrupt(void); /* user typed Ctrl-C */ 345 | 346 | int RTMP_SendCtrl(RTMP *r, short nType, unsigned int nObject, 347 | unsigned int nTime); 348 | 349 | /* caller probably doesn't know current timestamp, should 350 | * just use RTMP_Pause instead 351 | */ 352 | int RTMP_SendPause(RTMP *r, int DoPause, int dTime); 353 | int RTMP_Pause(RTMP *r, int DoPause); 354 | 355 | int RTMP_FindFirstMatchingProperty(AMFObject *obj, const AVal *name, 356 | AMFObjectProperty * p); 357 | 358 | int RTMPSockBuf_Fill(RTMPSockBuf *sb); 359 | int RTMPSockBuf_Send(RTMPSockBuf *sb, const char *buf, int len); 360 | int RTMPSockBuf_Close(RTMPSockBuf *sb); 361 | 362 | int RTMP_SendCreateStream(RTMP *r); 363 | int RTMP_SendSeek(RTMP *r, int dTime); 364 | int RTMP_SendServerBW(RTMP *r); 365 | int RTMP_SendClientBW(RTMP *r); 366 | void RTMP_DropRequest(RTMP *r, int i, int freeit); 367 | int RTMP_Read(RTMP *r, char *buf, int size); 368 | int RTMP_Write(RTMP *r, const char *buf, int size); 369 | 370 | /* hashswf.c */ 371 | int RTMP_HashSWF(const char *url, unsigned int *size, unsigned char *hash, 372 | int age); 373 | 374 | #ifdef __cplusplus 375 | }; 376 | #endif 377 | 378 | #endif 379 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 489 | USA 490 | 491 | Also add information on how to contact you by electronic and paper mail. 492 | 493 | You should also get your employer (if you work as a programmer) or your 494 | school, if any, to sign a "copyright disclaimer" for the library, if 495 | necessary. Here is a sample; alter the names: 496 | 497 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 498 | library `Frob' (a library for tweaking knobs) written by James Random 499 | Hacker. 500 | 501 | , 1 April 1990 502 | Ty Coon, President of Vice 503 | 504 | That's all there is to it! 505 | -------------------------------------------------------------------------------- /include/x264.h: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | * x264.h: x264 public header 3 | ***************************************************************************** 4 | * Copyright (C) 2003-2020 x264 project 5 | * 6 | * Authors: Laurent Aimar 7 | * Loren Merritt 8 | * Fiona Glaser 9 | * 10 | * This program is free software; you can redistribute it and/or modify 11 | * it under the terms of the GNU General Public License as published by 12 | * the Free Software Foundation; either version 2 of the License, or 13 | * (at your option) any later version. 14 | * 15 | * This program is distributed in the hope that it will be useful, 16 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | * GNU General Public License for more details. 19 | * 20 | * You should have received a copy of the GNU General Public License 21 | * along with this program; if not, write to the Free Software 22 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA. 23 | * 24 | * This program is also available under a commercial proprietary license. 25 | * For more information, contact us at licensing@x264.com. 26 | *****************************************************************************/ 27 | 28 | #ifndef X264_X264_H 29 | #define X264_X264_H 30 | 31 | #ifdef __cplusplus 32 | extern "C" { 33 | #endif 34 | 35 | #if !defined(_STDINT_H) && !defined(_STDINT_H_) && !defined(_STDINT_H_INCLUDED) && !defined(_STDINT) &&\ 36 | !defined(_SYS_STDINT_H_) && !defined(_INTTYPES_H) && !defined(_INTTYPES_H_) && !defined(_INTTYPES) 37 | # ifdef _MSC_VER 38 | # pragma message("You must include stdint.h or inttypes.h before x264.h") 39 | # else 40 | # warning You must include stdint.h or inttypes.h before x264.h 41 | # endif 42 | #endif 43 | 44 | #include 45 | 46 | #include "x264_config.h" 47 | 48 | #define X264_BUILD 161 49 | 50 | #ifdef _WIN32 51 | # define X264_DLL_IMPORT __declspec(dllimport) 52 | # define X264_DLL_EXPORT __declspec(dllexport) 53 | #else 54 | # if defined(__GNUC__) && (__GNUC__ >= 4) 55 | # define X264_DLL_IMPORT 56 | # define X264_DLL_EXPORT __attribute__((visibility("default"))) 57 | # else 58 | # define X264_DLL_IMPORT 59 | # define X264_DLL_EXPORT 60 | # endif 61 | #endif 62 | 63 | /* Application developers planning to link against a shared library version of 64 | * libx264 from a Microsoft Visual Studio or similar development environment 65 | * will need to define X264_API_IMPORTS before including this header. 66 | * This clause does not apply to MinGW, similar development environments, or non 67 | * Windows platforms. */ 68 | #ifdef X264_API_IMPORTS 69 | # define X264_API X264_DLL_IMPORT 70 | #else 71 | # ifdef X264_API_EXPORTS 72 | # define X264_API X264_DLL_EXPORT 73 | # else 74 | # define X264_API 75 | # endif 76 | #endif 77 | 78 | /* x264_t: 79 | * opaque handler for encoder */ 80 | typedef struct x264_t x264_t; 81 | 82 | /**************************************************************************** 83 | * NAL structure and functions 84 | ****************************************************************************/ 85 | 86 | enum nal_unit_type_e 87 | { 88 | NAL_UNKNOWN = 0, 89 | NAL_SLICE = 1, 90 | NAL_SLICE_DPA = 2, 91 | NAL_SLICE_DPB = 3, 92 | NAL_SLICE_DPC = 4, 93 | NAL_SLICE_IDR = 5, /* ref_idc != 0 */ 94 | NAL_SEI = 6, /* ref_idc == 0 */ 95 | NAL_SPS = 7, 96 | NAL_PPS = 8, 97 | NAL_AUD = 9, 98 | NAL_FILLER = 12, 99 | /* ref_idc == 0 for 6,9,10,11,12 */ 100 | }; 101 | enum nal_priority_e 102 | { 103 | NAL_PRIORITY_DISPOSABLE = 0, 104 | NAL_PRIORITY_LOW = 1, 105 | NAL_PRIORITY_HIGH = 2, 106 | NAL_PRIORITY_HIGHEST = 3, 107 | }; 108 | 109 | /* The data within the payload is already NAL-encapsulated; the ref_idc and type 110 | * are merely in the struct for easy access by the calling application. 111 | * All data returned in an x264_nal_t, including the data in p_payload, is no longer 112 | * valid after the next call to x264_encoder_encode. Thus it must be used or copied 113 | * before calling x264_encoder_encode or x264_encoder_headers again. */ 114 | typedef struct x264_nal_t 115 | { 116 | int i_ref_idc; /* nal_priority_e */ 117 | int i_type; /* nal_unit_type_e */ 118 | int b_long_startcode; 119 | int i_first_mb; /* If this NAL is a slice, the index of the first MB in the slice. */ 120 | int i_last_mb; /* If this NAL is a slice, the index of the last MB in the slice. */ 121 | 122 | /* Size of payload (including any padding) in bytes. */ 123 | int i_payload; 124 | /* If param->b_annexb is set, Annex-B bytestream with startcode. 125 | * Otherwise, startcode is replaced with a 4-byte size. 126 | * This size is the size used in mp4/similar muxing; it is equal to i_payload-4 */ 127 | uint8_t *p_payload; 128 | 129 | /* Size of padding in bytes. */ 130 | int i_padding; 131 | } x264_nal_t; 132 | 133 | /**************************************************************************** 134 | * Encoder parameters 135 | ****************************************************************************/ 136 | /* CPU flags */ 137 | 138 | /* x86 */ 139 | #define X264_CPU_MMX (1U<<0) 140 | #define X264_CPU_MMX2 (1U<<1) /* MMX2 aka MMXEXT aka ISSE */ 141 | #define X264_CPU_MMXEXT X264_CPU_MMX2 142 | #define X264_CPU_SSE (1U<<2) 143 | #define X264_CPU_SSE2 (1U<<3) 144 | #define X264_CPU_LZCNT (1U<<4) 145 | #define X264_CPU_SSE3 (1U<<5) 146 | #define X264_CPU_SSSE3 (1U<<6) 147 | #define X264_CPU_SSE4 (1U<<7) /* SSE4.1 */ 148 | #define X264_CPU_SSE42 (1U<<8) /* SSE4.2 */ 149 | #define X264_CPU_AVX (1U<<9) /* Requires OS support even if YMM registers aren't used */ 150 | #define X264_CPU_XOP (1U<<10) /* AMD XOP */ 151 | #define X264_CPU_FMA4 (1U<<11) /* AMD FMA4 */ 152 | #define X264_CPU_FMA3 (1U<<12) 153 | #define X264_CPU_BMI1 (1U<<13) 154 | #define X264_CPU_BMI2 (1U<<14) 155 | #define X264_CPU_AVX2 (1U<<15) 156 | #define X264_CPU_AVX512 (1U<<16) /* AVX-512 {F, CD, BW, DQ, VL}, requires OS support */ 157 | /* x86 modifiers */ 158 | #define X264_CPU_CACHELINE_32 (1U<<17) /* avoid memory loads that span the border between two cachelines */ 159 | #define X264_CPU_CACHELINE_64 (1U<<18) /* 32/64 is the size of a cacheline in bytes */ 160 | #define X264_CPU_SSE2_IS_SLOW (1U<<19) /* avoid most SSE2 functions on Athlon64 */ 161 | #define X264_CPU_SSE2_IS_FAST (1U<<20) /* a few functions are only faster on Core2 and Phenom */ 162 | #define X264_CPU_SLOW_SHUFFLE (1U<<21) /* The Conroe has a slow shuffle unit (relative to overall SSE performance) */ 163 | #define X264_CPU_STACK_MOD4 (1U<<22) /* if stack is only mod4 and not mod16 */ 164 | #define X264_CPU_SLOW_ATOM (1U<<23) /* The Atom is terrible: slow SSE unaligned loads, slow 165 | * SIMD multiplies, slow SIMD variable shifts, slow pshufb, 166 | * cacheline split penalties -- gather everything here that 167 | * isn't shared by other CPUs to avoid making half a dozen 168 | * new SLOW flags. */ 169 | #define X264_CPU_SLOW_PSHUFB (1U<<24) /* such as on the Intel Atom */ 170 | #define X264_CPU_SLOW_PALIGNR (1U<<25) /* such as on the AMD Bobcat */ 171 | 172 | /* PowerPC */ 173 | #define X264_CPU_ALTIVEC 0x0000001U 174 | 175 | /* ARM and AArch64 */ 176 | #define X264_CPU_ARMV6 0x0000001U 177 | #define X264_CPU_NEON 0x0000002U /* ARM NEON */ 178 | #define X264_CPU_FAST_NEON_MRC 0x0000004U /* Transfer from NEON to ARM register is fast (Cortex-A9) */ 179 | #define X264_CPU_ARMV8 0x0000008U 180 | 181 | /* MIPS */ 182 | #define X264_CPU_MSA 0x0000001U /* MIPS MSA */ 183 | 184 | /* Analyse flags */ 185 | #define X264_ANALYSE_I4x4 0x0001U /* Analyse i4x4 */ 186 | #define X264_ANALYSE_I8x8 0x0002U /* Analyse i8x8 (requires 8x8 transform) */ 187 | #define X264_ANALYSE_PSUB16x16 0x0010U /* Analyse p16x8, p8x16 and p8x8 */ 188 | #define X264_ANALYSE_PSUB8x8 0x0020U /* Analyse p8x4, p4x8, p4x4 */ 189 | #define X264_ANALYSE_BSUB16x16 0x0100U /* Analyse b16x8, b8x16 and b8x8 */ 190 | 191 | #define X264_DIRECT_PRED_NONE 0 192 | #define X264_DIRECT_PRED_SPATIAL 1 193 | #define X264_DIRECT_PRED_TEMPORAL 2 194 | #define X264_DIRECT_PRED_AUTO 3 195 | #define X264_ME_DIA 0 196 | #define X264_ME_HEX 1 197 | #define X264_ME_UMH 2 198 | #define X264_ME_ESA 3 199 | #define X264_ME_TESA 4 200 | #define X264_CQM_FLAT 0 201 | #define X264_CQM_JVT 1 202 | #define X264_CQM_CUSTOM 2 203 | #define X264_RC_CQP 0 204 | #define X264_RC_CRF 1 205 | #define X264_RC_ABR 2 206 | #define X264_QP_AUTO 0 207 | #define X264_AQ_NONE 0 208 | #define X264_AQ_VARIANCE 1 209 | #define X264_AQ_AUTOVARIANCE 2 210 | #define X264_AQ_AUTOVARIANCE_BIASED 3 211 | #define X264_B_ADAPT_NONE 0 212 | #define X264_B_ADAPT_FAST 1 213 | #define X264_B_ADAPT_TRELLIS 2 214 | #define X264_WEIGHTP_NONE 0 215 | #define X264_WEIGHTP_SIMPLE 1 216 | #define X264_WEIGHTP_SMART 2 217 | #define X264_B_PYRAMID_NONE 0 218 | #define X264_B_PYRAMID_STRICT 1 219 | #define X264_B_PYRAMID_NORMAL 2 220 | #define X264_KEYINT_MIN_AUTO 0 221 | #define X264_KEYINT_MAX_INFINITE (1<<30) 222 | 223 | /* AVC-Intra flavors */ 224 | #define X264_AVCINTRA_FLAVOR_PANASONIC 0 225 | #define X264_AVCINTRA_FLAVOR_SONY 1 226 | 227 | static const char * const x264_direct_pred_names[] = { "none", "spatial", "temporal", "auto", 0 }; 228 | static const char * const x264_motion_est_names[] = { "dia", "hex", "umh", "esa", "tesa", 0 }; 229 | static const char * const x264_b_pyramid_names[] = { "none", "strict", "normal", 0 }; 230 | static const char * const x264_overscan_names[] = { "undef", "show", "crop", 0 }; 231 | static const char * const x264_vidformat_names[] = { "component", "pal", "ntsc", "secam", "mac", "undef", 0 }; 232 | static const char * const x264_fullrange_names[] = { "off", "on", 0 }; 233 | static const char * const x264_colorprim_names[] = { "", "bt709", "undef", "", "bt470m", "bt470bg", "smpte170m", "smpte240m", "film", "bt2020", "smpte428", 234 | "smpte431", "smpte432", 0 }; 235 | static const char * const x264_transfer_names[] = { "", "bt709", "undef", "", "bt470m", "bt470bg", "smpte170m", "smpte240m", "linear", "log100", "log316", 236 | "iec61966-2-4", "bt1361e", "iec61966-2-1", "bt2020-10", "bt2020-12", "smpte2084", "smpte428", "arib-std-b67", 0 }; 237 | static const char * const x264_colmatrix_names[] = { "GBR", "bt709", "undef", "", "fcc", "bt470bg", "smpte170m", "smpte240m", "YCgCo", "bt2020nc", "bt2020c", 238 | "smpte2085", "chroma-derived-nc", "chroma-derived-c", "ICtCp", 0 }; 239 | static const char * const x264_nal_hrd_names[] = { "none", "vbr", "cbr", 0 }; 240 | static const char * const x264_avcintra_flavor_names[] = { "panasonic", "sony", 0 }; 241 | 242 | /* Colorspace type */ 243 | #define X264_CSP_MASK 0x00ff /* */ 244 | #define X264_CSP_NONE 0x0000 /* Invalid mode */ 245 | #define X264_CSP_I400 0x0001 /* monochrome 4:0:0 */ 246 | #define X264_CSP_I420 0x0002 /* yuv 4:2:0 planar */ 247 | #define X264_CSP_YV12 0x0003 /* yvu 4:2:0 planar */ 248 | #define X264_CSP_NV12 0x0004 /* yuv 4:2:0, with one y plane and one packed u+v */ 249 | #define X264_CSP_NV21 0x0005 /* yuv 4:2:0, with one y plane and one packed v+u */ 250 | #define X264_CSP_I422 0x0006 /* yuv 4:2:2 planar */ 251 | #define X264_CSP_YV16 0x0007 /* yvu 4:2:2 planar */ 252 | #define X264_CSP_NV16 0x0008 /* yuv 4:2:2, with one y plane and one packed u+v */ 253 | #define X264_CSP_YUYV 0x0009 /* yuyv 4:2:2 packed */ 254 | #define X264_CSP_UYVY 0x000a /* uyvy 4:2:2 packed */ 255 | #define X264_CSP_V210 0x000b /* 10-bit yuv 4:2:2 packed in 32 */ 256 | #define X264_CSP_I444 0x000c /* yuv 4:4:4 planar */ 257 | #define X264_CSP_YV24 0x000d /* yvu 4:4:4 planar */ 258 | #define X264_CSP_BGR 0x000e /* packed bgr 24bits */ 259 | #define X264_CSP_BGRA 0x000f /* packed bgr 32bits */ 260 | #define X264_CSP_RGB 0x0010 /* packed rgb 24bits */ 261 | #define X264_CSP_MAX 0x0011 /* end of list */ 262 | #define X264_CSP_VFLIP 0x1000 /* the csp is vertically flipped */ 263 | #define X264_CSP_HIGH_DEPTH 0x2000 /* the csp has a depth of 16 bits per pixel component */ 264 | 265 | /* Slice type */ 266 | #define X264_TYPE_AUTO 0x0000 /* Let x264 choose the right type */ 267 | #define X264_TYPE_IDR 0x0001 268 | #define X264_TYPE_I 0x0002 269 | #define X264_TYPE_P 0x0003 270 | #define X264_TYPE_BREF 0x0004 /* Non-disposable B-frame */ 271 | #define X264_TYPE_B 0x0005 272 | #define X264_TYPE_KEYFRAME 0x0006 /* IDR or I depending on b_open_gop option */ 273 | #define IS_X264_TYPE_I(x) ((x)==X264_TYPE_I || (x)==X264_TYPE_IDR || (x)==X264_TYPE_KEYFRAME) 274 | #define IS_X264_TYPE_B(x) ((x)==X264_TYPE_B || (x)==X264_TYPE_BREF) 275 | 276 | /* Log level */ 277 | #define X264_LOG_NONE (-1) 278 | #define X264_LOG_ERROR 0 279 | #define X264_LOG_WARNING 1 280 | #define X264_LOG_INFO 2 281 | #define X264_LOG_DEBUG 3 282 | 283 | /* Threading */ 284 | #define X264_THREADS_AUTO 0 /* Automatically select optimal number of threads */ 285 | #define X264_SYNC_LOOKAHEAD_AUTO (-1) /* Automatically select optimal lookahead thread buffer size */ 286 | 287 | /* HRD */ 288 | #define X264_NAL_HRD_NONE 0 289 | #define X264_NAL_HRD_VBR 1 290 | #define X264_NAL_HRD_CBR 2 291 | 292 | /* Zones: override ratecontrol or other options for specific sections of the video. 293 | * See x264_encoder_reconfig() for which options can be changed. 294 | * If zones overlap, whichever comes later in the list takes precedence. */ 295 | typedef struct x264_zone_t 296 | { 297 | int i_start, i_end; /* range of frame numbers */ 298 | int b_force_qp; /* whether to use qp vs bitrate factor */ 299 | int i_qp; 300 | float f_bitrate_factor; 301 | struct x264_param_t *param; 302 | } x264_zone_t; 303 | 304 | typedef struct x264_param_t 305 | { 306 | /* CPU flags */ 307 | uint32_t cpu; 308 | int i_threads; /* encode multiple frames in parallel */ 309 | int i_lookahead_threads; /* multiple threads for lookahead analysis */ 310 | int b_sliced_threads; /* Whether to use slice-based threading. */ 311 | int b_deterministic; /* whether to allow non-deterministic optimizations when threaded */ 312 | int b_cpu_independent; /* force canonical behavior rather than cpu-dependent optimal algorithms */ 313 | int i_sync_lookahead; /* threaded lookahead buffer */ 314 | 315 | /* Video Properties */ 316 | int i_width; 317 | int i_height; 318 | int i_csp; /* CSP of encoded bitstream */ 319 | int i_bitdepth; 320 | int i_level_idc; 321 | int i_frame_total; /* number of frames to encode if known, else 0 */ 322 | 323 | /* NAL HRD 324 | * Uses Buffering and Picture Timing SEIs to signal HRD 325 | * The HRD in H.264 was not designed with VFR in mind. 326 | * It is therefore not recommendeded to use NAL HRD with VFR. 327 | * Furthermore, reconfiguring the VBV (via x264_encoder_reconfig) 328 | * will currently generate invalid HRD. */ 329 | int i_nal_hrd; 330 | 331 | struct 332 | { 333 | /* they will be reduced to be 0 < x <= 65535 and prime */ 334 | int i_sar_height; 335 | int i_sar_width; 336 | 337 | int i_overscan; /* 0=undef, 1=no overscan, 2=overscan */ 338 | 339 | /* see h264 annex E for the values of the following */ 340 | int i_vidformat; 341 | int b_fullrange; 342 | int i_colorprim; 343 | int i_transfer; 344 | int i_colmatrix; 345 | int i_chroma_loc; /* both top & bottom */ 346 | } vui; 347 | 348 | /* Bitstream parameters */ 349 | int i_frame_reference; /* Maximum number of reference frames */ 350 | int i_dpb_size; /* Force a DPB size larger than that implied by B-frames and reference frames. 351 | * Useful in combination with interactive error resilience. */ 352 | int i_keyint_max; /* Force an IDR keyframe at this interval */ 353 | int i_keyint_min; /* Scenecuts closer together than this are coded as I, not IDR. */ 354 | int i_scenecut_threshold; /* how aggressively to insert extra I frames */ 355 | int b_intra_refresh; /* Whether or not to use periodic intra refresh instead of IDR frames. */ 356 | 357 | int i_bframe; /* how many b-frame between 2 references pictures */ 358 | int i_bframe_adaptive; 359 | int i_bframe_bias; 360 | int i_bframe_pyramid; /* Keep some B-frames as references: 0=off, 1=strict hierarchical, 2=normal */ 361 | int b_open_gop; 362 | int b_bluray_compat; 363 | int i_avcintra_class; 364 | int i_avcintra_flavor; 365 | 366 | int b_deblocking_filter; 367 | int i_deblocking_filter_alphac0; /* [-6, 6] -6 light filter, 6 strong */ 368 | int i_deblocking_filter_beta; /* [-6, 6] idem */ 369 | 370 | int b_cabac; 371 | int i_cabac_init_idc; 372 | 373 | int b_interlaced; 374 | int b_constrained_intra; 375 | 376 | int i_cqm_preset; 377 | char *psz_cqm_file; /* filename (in UTF-8) of CQM file, JM format */ 378 | uint8_t cqm_4iy[16]; /* used only if i_cqm_preset == X264_CQM_CUSTOM */ 379 | uint8_t cqm_4py[16]; 380 | uint8_t cqm_4ic[16]; 381 | uint8_t cqm_4pc[16]; 382 | uint8_t cqm_8iy[64]; 383 | uint8_t cqm_8py[64]; 384 | uint8_t cqm_8ic[64]; 385 | uint8_t cqm_8pc[64]; 386 | 387 | /* Log */ 388 | void (*pf_log)( void *, int i_level, const char *psz, va_list ); 389 | void *p_log_private; 390 | int i_log_level; 391 | int b_full_recon; /* fully reconstruct frames, even when not necessary for encoding. Implied by psz_dump_yuv */ 392 | char *psz_dump_yuv; /* filename (in UTF-8) for reconstructed frames */ 393 | 394 | /* Encoder analyser parameters */ 395 | struct 396 | { 397 | unsigned int intra; /* intra partitions */ 398 | unsigned int inter; /* inter partitions */ 399 | 400 | int b_transform_8x8; 401 | int i_weighted_pred; /* weighting for P-frames */ 402 | int b_weighted_bipred; /* implicit weighting for B-frames */ 403 | int i_direct_mv_pred; /* spatial vs temporal mv prediction */ 404 | int i_chroma_qp_offset; 405 | 406 | int i_me_method; /* motion estimation algorithm to use (X264_ME_*) */ 407 | int i_me_range; /* integer pixel motion estimation search range (from predicted mv) */ 408 | int i_mv_range; /* maximum length of a mv (in pixels). -1 = auto, based on level */ 409 | int i_mv_range_thread; /* minimum space between threads. -1 = auto, based on number of threads. */ 410 | int i_subpel_refine; /* subpixel motion estimation quality */ 411 | int b_chroma_me; /* chroma ME for subpel and mode decision in P-frames */ 412 | int b_mixed_references; /* allow each mb partition to have its own reference number */ 413 | int i_trellis; /* trellis RD quantization */ 414 | int b_fast_pskip; /* early SKIP detection on P-frames */ 415 | int b_dct_decimate; /* transform coefficient thresholding on P-frames */ 416 | int i_noise_reduction; /* adaptive pseudo-deadzone */ 417 | float f_psy_rd; /* Psy RD strength */ 418 | float f_psy_trellis; /* Psy trellis strength */ 419 | int b_psy; /* Toggle all psy optimizations */ 420 | 421 | int b_mb_info; /* Use input mb_info data in x264_picture_t */ 422 | int b_mb_info_update; /* Update the values in mb_info according to the results of encoding. */ 423 | 424 | /* the deadzone size that will be used in luma quantization */ 425 | int i_luma_deadzone[2]; /* {inter, intra} */ 426 | 427 | int b_psnr; /* compute and print PSNR stats */ 428 | int b_ssim; /* compute and print SSIM stats */ 429 | } analyse; 430 | 431 | /* Rate control parameters */ 432 | struct 433 | { 434 | int i_rc_method; /* X264_RC_* */ 435 | 436 | int i_qp_constant; /* 0=lossless */ 437 | int i_qp_min; /* min allowed QP value */ 438 | int i_qp_max; /* max allowed QP value */ 439 | int i_qp_step; /* max QP step between frames */ 440 | 441 | int i_bitrate; 442 | float f_rf_constant; /* 1pass VBR, nominal QP */ 443 | float f_rf_constant_max; /* In CRF mode, maximum CRF as caused by VBV */ 444 | float f_rate_tolerance; 445 | int i_vbv_max_bitrate; 446 | int i_vbv_buffer_size; 447 | float f_vbv_buffer_init; /* <=1: fraction of buffer_size. >1: kbit */ 448 | float f_ip_factor; 449 | float f_pb_factor; 450 | 451 | /* VBV filler: force CBR VBV and use filler bytes to ensure hard-CBR. 452 | * Implied by NAL-HRD CBR. */ 453 | int b_filler; 454 | 455 | int i_aq_mode; /* psy adaptive QP. (X264_AQ_*) */ 456 | float f_aq_strength; 457 | int b_mb_tree; /* Macroblock-tree ratecontrol. */ 458 | int i_lookahead; 459 | 460 | /* 2pass */ 461 | int b_stat_write; /* Enable stat writing in psz_stat_out */ 462 | char *psz_stat_out; /* output filename (in UTF-8) of the 2pass stats file */ 463 | int b_stat_read; /* Read stat from psz_stat_in and use it */ 464 | char *psz_stat_in; /* input filename (in UTF-8) of the 2pass stats file */ 465 | 466 | /* 2pass params (same as ffmpeg ones) */ 467 | float f_qcompress; /* 0.0 => cbr, 1.0 => constant qp */ 468 | float f_qblur; /* temporally blur quants */ 469 | float f_complexity_blur; /* temporally blur complexity */ 470 | x264_zone_t *zones; /* ratecontrol overrides */ 471 | int i_zones; /* number of zone_t's */ 472 | char *psz_zones; /* alternate method of specifying zones */ 473 | } rc; 474 | 475 | /* Cropping Rectangle parameters: added to those implicitly defined by 476 | non-mod16 video resolutions. */ 477 | struct 478 | { 479 | int i_left; 480 | int i_top; 481 | int i_right; 482 | int i_bottom; 483 | } crop_rect; 484 | 485 | /* frame packing arrangement flag */ 486 | int i_frame_packing; 487 | 488 | /* alternative transfer SEI */ 489 | int i_alternative_transfer; 490 | 491 | /* Muxing parameters */ 492 | int b_aud; /* generate access unit delimiters */ 493 | int b_repeat_headers; /* put SPS/PPS before each keyframe */ 494 | int b_annexb; /* if set, place start codes (4 bytes) before NAL units, 495 | * otherwise place size (4 bytes) before NAL units. */ 496 | int i_sps_id; /* SPS and PPS id number */ 497 | int b_vfr_input; /* VFR input. If 1, use timebase and timestamps for ratecontrol purposes. 498 | * If 0, use fps only. */ 499 | int b_pulldown; /* use explicity set timebase for CFR */ 500 | uint32_t i_fps_num; 501 | uint32_t i_fps_den; 502 | uint32_t i_timebase_num; /* Timebase numerator */ 503 | uint32_t i_timebase_den; /* Timebase denominator */ 504 | 505 | int b_tff; 506 | 507 | /* Pulldown: 508 | * The correct pic_struct must be passed with each input frame. 509 | * The input timebase should be the timebase corresponding to the output framerate. This should be constant. 510 | * e.g. for 3:2 pulldown timebase should be 1001/30000 511 | * The PTS passed with each frame must be the PTS of the frame after pulldown is applied. 512 | * Frame doubling and tripling require b_vfr_input set to zero (see H.264 Table D-1) 513 | * 514 | * Pulldown changes are not clearly defined in H.264. Therefore, it is the calling app's responsibility to manage this. 515 | */ 516 | 517 | int b_pic_struct; 518 | 519 | /* Fake Interlaced. 520 | * 521 | * Used only when b_interlaced=0. Setting this flag makes it possible to flag the stream as PAFF interlaced yet 522 | * encode all frames progessively. It is useful for encoding 25p and 30p Blu-Ray streams. 523 | */ 524 | 525 | int b_fake_interlaced; 526 | 527 | /* Don't optimize header parameters based on video content, e.g. ensure that splitting an input video, compressing 528 | * each part, and stitching them back together will result in identical SPS/PPS. This is necessary for stitching 529 | * with container formats that don't allow multiple SPS/PPS. */ 530 | int b_stitchable; 531 | 532 | int b_opencl; /* use OpenCL when available */ 533 | int i_opencl_device; /* specify count of GPU devices to skip, for CLI users */ 534 | void *opencl_device_id; /* pass explicit cl_device_id as void*, for API users */ 535 | char *psz_clbin_file; /* filename (in UTF-8) of the compiled OpenCL kernel cache file */ 536 | 537 | /* Slicing parameters */ 538 | int i_slice_max_size; /* Max size per slice in bytes; includes estimated NAL overhead. */ 539 | int i_slice_max_mbs; /* Max number of MBs per slice; overrides i_slice_count. */ 540 | int i_slice_min_mbs; /* Min number of MBs per slice */ 541 | int i_slice_count; /* Number of slices per frame: forces rectangular slices. */ 542 | int i_slice_count_max; /* Absolute cap on slices per frame; stops applying slice-max-size 543 | * and slice-max-mbs if this is reached. */ 544 | 545 | /* Optional callback for freeing this x264_param_t when it is done being used. 546 | * Only used when the x264_param_t sits in memory for an indefinite period of time, 547 | * i.e. when an x264_param_t is passed to x264_t in an x264_picture_t or in zones. 548 | * Not used when x264_encoder_reconfig is called directly. */ 549 | void (*param_free)( void* ); 550 | 551 | /* Optional low-level callback for low-latency encoding. Called for each output NAL unit 552 | * immediately after the NAL unit is finished encoding. This allows the calling application 553 | * to begin processing video data (e.g. by sending packets over a network) before the frame 554 | * is done encoding. 555 | * 556 | * This callback MUST do the following in order to work correctly: 557 | * 1) Have available an output buffer of at least size nal->i_payload*3/2 + 5 + 64. 558 | * 2) Call x264_nal_encode( h, dst, nal ), where dst is the output buffer. 559 | * After these steps, the content of nal is valid and can be used in the same way as if 560 | * the NAL unit were output by x264_encoder_encode. 561 | * 562 | * This does not need to be synchronous with the encoding process: the data pointed to 563 | * by nal (both before and after x264_nal_encode) will remain valid until the next 564 | * x264_encoder_encode call. The callback must be re-entrant. 565 | * 566 | * This callback does not work with frame-based threads; threads must be disabled 567 | * or sliced-threads enabled. This callback also does not work as one would expect 568 | * with HRD -- since the buffering period SEI cannot be calculated until the frame 569 | * is finished encoding, it will not be sent via this callback. 570 | * 571 | * Note also that the NALs are not necessarily returned in order when sliced threads is 572 | * enabled. Accordingly, the variable i_first_mb and i_last_mb are available in 573 | * x264_nal_t to help the calling application reorder the slices if necessary. 574 | * 575 | * When this callback is enabled, x264_encoder_encode does not return valid NALs; 576 | * the calling application is expected to acquire all output NALs through the callback. 577 | * 578 | * It is generally sensible to combine this callback with a use of slice-max-mbs or 579 | * slice-max-size. 580 | * 581 | * The opaque pointer is the opaque pointer from the input frame associated with this 582 | * NAL unit. This helps distinguish between nalu_process calls from different sources, 583 | * e.g. if doing multiple encodes in one process. 584 | */ 585 | void (*nalu_process)( x264_t *h, x264_nal_t *nal, void *opaque ); 586 | 587 | /* For internal use only */ 588 | void *opaque; 589 | } x264_param_t; 590 | 591 | X264_API void x264_nal_encode( x264_t *h, uint8_t *dst, x264_nal_t *nal ); 592 | 593 | /**************************************************************************** 594 | * H.264 level restriction information 595 | ****************************************************************************/ 596 | 597 | typedef struct x264_level_t 598 | { 599 | uint8_t level_idc; 600 | int32_t mbps; /* max macroblock processing rate (macroblocks/sec) */ 601 | int32_t frame_size; /* max frame size (macroblocks) */ 602 | int32_t dpb; /* max decoded picture buffer (mbs) */ 603 | int32_t bitrate; /* max bitrate (kbit/sec) */ 604 | int32_t cpb; /* max vbv buffer (kbit) */ 605 | uint16_t mv_range; /* max vertical mv component range (pixels) */ 606 | uint8_t mvs_per_2mb; /* max mvs per 2 consecutive mbs. */ 607 | uint8_t slice_rate; /* ?? */ 608 | uint8_t mincr; /* min compression ratio */ 609 | uint8_t bipred8x8; /* limit bipred to >=8x8 */ 610 | uint8_t direct8x8; /* limit b_direct to >=8x8 */ 611 | uint8_t frame_only; /* forbid interlacing */ 612 | } x264_level_t; 613 | 614 | /* all of the levels defined in the standard, terminated by .level_idc=0 */ 615 | X264_API extern const x264_level_t x264_levels[]; 616 | 617 | /**************************************************************************** 618 | * Basic parameter handling functions 619 | ****************************************************************************/ 620 | 621 | /* x264_param_default: 622 | * fill x264_param_t with default values and do CPU detection */ 623 | X264_API void x264_param_default( x264_param_t * ); 624 | 625 | /* x264_param_parse: 626 | * set one parameter by name. 627 | * returns 0 on success, or returns one of the following errors. 628 | * note: BAD_VALUE occurs only if it can't even parse the value, 629 | * numerical range is not checked until x264_encoder_open() or 630 | * x264_encoder_reconfig(). 631 | * value=NULL means "true" for boolean options, but is a BAD_VALUE for non-booleans. 632 | * can allocate memory which should be freed by call of x264_param_cleanup. */ 633 | #define X264_PARAM_BAD_NAME (-1) 634 | #define X264_PARAM_BAD_VALUE (-2) 635 | #define X264_PARAM_ALLOC_FAILED (-3) 636 | X264_API int x264_param_parse( x264_param_t *, const char *name, const char *value ); 637 | 638 | /* x264_param_cleanup: 639 | * Cleans up and frees allocated members of x264_param_t. 640 | * This *does not* free the x264_param_t itself, as it may exist on the 641 | * stack. It only frees any members of the struct that were allocated by 642 | * x264 itself, in e.g. x264_param_parse(). */ 643 | X264_API void x264_param_cleanup( x264_param_t *param ); 644 | 645 | /**************************************************************************** 646 | * Advanced parameter handling functions 647 | ****************************************************************************/ 648 | 649 | /* These functions expose the full power of x264's preset-tune-profile system for 650 | * easy adjustment of large numbers of internal parameters. 651 | * 652 | * In order to replicate x264CLI's option handling, these functions MUST be called 653 | * in the following order: 654 | * 1) x264_param_default_preset 655 | * 2) Custom user options (via param_parse or directly assigned variables) 656 | * 3) x264_param_apply_fastfirstpass 657 | * 4) x264_param_apply_profile 658 | * 659 | * Additionally, x264CLI does not apply step 3 if the preset chosen is "placebo" 660 | * or --slow-firstpass is set. */ 661 | 662 | /* x264_param_default_preset: 663 | * The same as x264_param_default, but also use the passed preset and tune 664 | * to modify the default settings. 665 | * (either can be NULL, which implies no preset or no tune, respectively) 666 | * 667 | * Currently available presets are, ordered from fastest to slowest: */ 668 | static const char * const x264_preset_names[] = { "ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow", "placebo", 0 }; 669 | 670 | /* The presets can also be indexed numerically, as in: 671 | * x264_param_default_preset( ¶m, "3", ... ) 672 | * with ultrafast mapping to "0" and placebo mapping to "9". This mapping may 673 | * of course change if new presets are added in between, but will always be 674 | * ordered from fastest to slowest. 675 | * 676 | * Warning: the speed of these presets scales dramatically. Ultrafast is a full 677 | * 100 times faster than placebo! 678 | * 679 | * Currently available tunings are: */ 680 | static const char * const x264_tune_names[] = { "film", "animation", "grain", "stillimage", "psnr", "ssim", "fastdecode", "zerolatency", 0 }; 681 | 682 | /* Multiple tunings can be used if separated by a delimiter in ",./-+", 683 | * however multiple psy tunings cannot be used. 684 | * film, animation, grain, stillimage, psnr, and ssim are psy tunings. 685 | * 686 | * returns 0 on success, negative on failure (e.g. invalid preset/tune name). */ 687 | X264_API int x264_param_default_preset( x264_param_t *, const char *preset, const char *tune ); 688 | 689 | /* x264_param_apply_fastfirstpass: 690 | * If first-pass mode is set (rc.b_stat_read == 0, rc.b_stat_write == 1), 691 | * modify the encoder settings to disable options generally not useful on 692 | * the first pass. */ 693 | X264_API void x264_param_apply_fastfirstpass( x264_param_t * ); 694 | 695 | /* x264_param_apply_profile: 696 | * Applies the restrictions of the given profile. 697 | * Currently available profiles are, from most to least restrictive: */ 698 | static const char * const x264_profile_names[] = { "baseline", "main", "high", "high10", "high422", "high444", 0 }; 699 | 700 | /* (can be NULL, in which case the function will do nothing) 701 | * 702 | * Does NOT guarantee that the given profile will be used: if the restrictions 703 | * of "High" are applied to settings that are already Baseline-compatible, the 704 | * stream will remain baseline. In short, it does not increase settings, only 705 | * decrease them. 706 | * 707 | * returns 0 on success, negative on failure (e.g. invalid profile name). */ 708 | X264_API int x264_param_apply_profile( x264_param_t *, const char *profile ); 709 | 710 | /**************************************************************************** 711 | * Picture structures and functions 712 | ****************************************************************************/ 713 | 714 | /* x264_chroma_format: 715 | * Specifies the chroma formats that x264 supports encoding. When this 716 | * value is non-zero, then it represents a X264_CSP_* that is the only 717 | * chroma format that x264 supports encoding. If the value is 0 then 718 | * there are no restrictions. */ 719 | X264_API extern const int x264_chroma_format; 720 | 721 | enum pic_struct_e 722 | { 723 | PIC_STRUCT_AUTO = 0, // automatically decide (default) 724 | PIC_STRUCT_PROGRESSIVE = 1, // progressive frame 725 | // "TOP" and "BOTTOM" are not supported in x264 (PAFF only) 726 | PIC_STRUCT_TOP_BOTTOM = 4, // top field followed by bottom 727 | PIC_STRUCT_BOTTOM_TOP = 5, // bottom field followed by top 728 | PIC_STRUCT_TOP_BOTTOM_TOP = 6, // top field, bottom field, top field repeated 729 | PIC_STRUCT_BOTTOM_TOP_BOTTOM = 7, // bottom field, top field, bottom field repeated 730 | PIC_STRUCT_DOUBLE = 8, // double frame 731 | PIC_STRUCT_TRIPLE = 9, // triple frame 732 | }; 733 | 734 | typedef struct x264_hrd_t 735 | { 736 | double cpb_initial_arrival_time; 737 | double cpb_final_arrival_time; 738 | double cpb_removal_time; 739 | 740 | double dpb_output_time; 741 | } x264_hrd_t; 742 | 743 | /* Arbitrary user SEI: 744 | * Payload size is in bytes and the payload pointer must be valid. 745 | * Payload types and syntax can be found in Annex D of the H.264 Specification. 746 | * SEI payload alignment bits as described in Annex D must be included at the 747 | * end of the payload if needed. 748 | * The payload should not be NAL-encapsulated. 749 | * Payloads are written first in order of input, apart from in the case when HRD 750 | * is enabled where payloads are written after the Buffering Period SEI. */ 751 | 752 | typedef struct x264_sei_payload_t 753 | { 754 | int payload_size; 755 | int payload_type; 756 | uint8_t *payload; 757 | } x264_sei_payload_t; 758 | 759 | typedef struct x264_sei_t 760 | { 761 | int num_payloads; 762 | x264_sei_payload_t *payloads; 763 | /* In: optional callback to free each payload AND x264_sei_payload_t when used. */ 764 | void (*sei_free)( void* ); 765 | } x264_sei_t; 766 | 767 | typedef struct x264_image_t 768 | { 769 | int i_csp; /* Colorspace */ 770 | int i_plane; /* Number of image planes */ 771 | int i_stride[4]; /* Strides for each plane */ 772 | uint8_t *plane[4]; /* Pointers to each plane */ 773 | } x264_image_t; 774 | 775 | typedef struct x264_image_properties_t 776 | { 777 | /* All arrays of data here are ordered as follows: 778 | * each array contains one offset per macroblock, in raster scan order. In interlaced 779 | * mode, top-field MBs and bottom-field MBs are interleaved at the row level. 780 | * Macroblocks are 16x16 blocks of pixels (with respect to the luma plane). For the 781 | * purposes of calculating the number of macroblocks, width and height are rounded up to 782 | * the nearest 16. If in interlaced mode, height is rounded up to the nearest 32 instead. */ 783 | 784 | /* In: an array of quantizer offsets to be applied to this image during encoding. 785 | * These are added on top of the decisions made by x264. 786 | * Offsets can be fractional; they are added before QPs are rounded to integer. 787 | * Adaptive quantization must be enabled to use this feature. Behavior if quant 788 | * offsets differ between encoding passes is undefined. */ 789 | float *quant_offsets; 790 | /* In: optional callback to free quant_offsets when used. 791 | * Useful if one wants to use a different quant_offset array for each frame. */ 792 | void (*quant_offsets_free)( void* ); 793 | 794 | /* In: optional array of flags for each macroblock. 795 | * Allows specifying additional information for the encoder such as which macroblocks 796 | * remain unchanged. Usable flags are listed below. 797 | * x264_param_t.analyse.b_mb_info must be set to use this, since x264 needs to track 798 | * extra data internally to make full use of this information. 799 | * 800 | * Out: if b_mb_info_update is set, x264 will update this array as a result of encoding. 801 | * 802 | * For "MBINFO_CONSTANT", it will remove this flag on any macroblock whose decoded 803 | * pixels have changed. This can be useful for e.g. noting which areas of the 804 | * frame need to actually be blitted. Note: this intentionally ignores the effects 805 | * of deblocking for the current frame, which should be fine unless one needs exact 806 | * pixel-perfect accuracy. 807 | * 808 | * Results for MBINFO_CONSTANT are currently only set for P-frames, and are not 809 | * guaranteed to enumerate all blocks which haven't changed. (There may be false 810 | * negatives, but no false positives.) 811 | */ 812 | uint8_t *mb_info; 813 | /* In: optional callback to free mb_info when used. */ 814 | void (*mb_info_free)( void* ); 815 | 816 | /* The macroblock is constant and remains unchanged from the previous frame. */ 817 | #define X264_MBINFO_CONSTANT (1U<<0) 818 | /* More flags may be added in the future. */ 819 | 820 | /* Out: SSIM of the the frame luma (if x264_param_t.b_ssim is set) */ 821 | double f_ssim; 822 | /* Out: Average PSNR of the frame (if x264_param_t.b_psnr is set) */ 823 | double f_psnr_avg; 824 | /* Out: PSNR of Y, U, and V (if x264_param_t.b_psnr is set) */ 825 | double f_psnr[3]; 826 | 827 | /* Out: Average effective CRF of the encoded frame */ 828 | double f_crf_avg; 829 | } x264_image_properties_t; 830 | 831 | typedef struct x264_picture_t 832 | { 833 | /* In: force picture type (if not auto) 834 | * If x264 encoding parameters are violated in the forcing of picture types, 835 | * x264 will correct the input picture type and log a warning. 836 | * Out: type of the picture encoded */ 837 | int i_type; 838 | /* In: force quantizer for != X264_QP_AUTO */ 839 | int i_qpplus1; 840 | /* In: pic_struct, for pulldown/doubling/etc...used only if b_pic_struct=1. 841 | * use pic_struct_e for pic_struct inputs 842 | * Out: pic_struct element associated with frame */ 843 | int i_pic_struct; 844 | /* Out: whether this frame is a keyframe. Important when using modes that result in 845 | * SEI recovery points being used instead of IDR frames. */ 846 | int b_keyframe; 847 | /* In: user pts, Out: pts of encoded picture (user)*/ 848 | int64_t i_pts; 849 | /* Out: frame dts. When the pts of the first frame is close to zero, 850 | * initial frames may have a negative dts which must be dealt with by any muxer */ 851 | int64_t i_dts; 852 | /* In: custom encoding parameters to be set from this frame forwards 853 | (in coded order, not display order). If NULL, continue using 854 | parameters from the previous frame. Some parameters, such as 855 | aspect ratio, can only be changed per-GOP due to the limitations 856 | of H.264 itself; in this case, the caller must force an IDR frame 857 | if it needs the changed parameter to apply immediately. */ 858 | x264_param_t *param; 859 | /* In: raw image data */ 860 | /* Out: reconstructed image data. x264 may skip part of the reconstruction process, 861 | e.g. deblocking, in frames where it isn't necessary. To force complete 862 | reconstruction, at a small speed cost, set b_full_recon. */ 863 | x264_image_t img; 864 | /* In: optional information to modify encoder decisions for this frame 865 | * Out: information about the encoded frame */ 866 | x264_image_properties_t prop; 867 | /* Out: HRD timing information. Output only when i_nal_hrd is set. */ 868 | x264_hrd_t hrd_timing; 869 | /* In: arbitrary user SEI (e.g subtitles, AFDs) */ 870 | x264_sei_t extra_sei; 871 | /* private user data. copied from input to output frames. */ 872 | void *opaque; 873 | } x264_picture_t; 874 | 875 | /* x264_picture_init: 876 | * initialize an x264_picture_t. Needs to be done if the calling application 877 | * allocates its own x264_picture_t as opposed to using x264_picture_alloc. */ 878 | X264_API void x264_picture_init( x264_picture_t *pic ); 879 | 880 | /* x264_picture_alloc: 881 | * alloc data for a picture. You must call x264_picture_clean on it. 882 | * returns 0 on success, or -1 on malloc failure or invalid colorspace. */ 883 | X264_API int x264_picture_alloc( x264_picture_t *pic, int i_csp, int i_width, int i_height ); 884 | 885 | /* x264_picture_clean: 886 | * free associated resource for a x264_picture_t allocated with 887 | * x264_picture_alloc ONLY */ 888 | X264_API void x264_picture_clean( x264_picture_t *pic ); 889 | 890 | /**************************************************************************** 891 | * Encoder functions 892 | ****************************************************************************/ 893 | 894 | /* Force a link error in the case of linking against an incompatible API version. 895 | * Glue #defines exist to force correct macro expansion; the final output of the macro 896 | * is x264_encoder_open_##X264_BUILD (for purposes of dlopen). */ 897 | #define x264_encoder_glue1(x,y) x##y 898 | #define x264_encoder_glue2(x,y) x264_encoder_glue1(x,y) 899 | #define x264_encoder_open x264_encoder_glue2(x264_encoder_open_,X264_BUILD) 900 | 901 | /* x264_encoder_open: 902 | * create a new encoder handler, all parameters from x264_param_t are copied */ 903 | X264_API x264_t *x264_encoder_open( x264_param_t * ); 904 | 905 | /* x264_encoder_reconfig: 906 | * various parameters from x264_param_t are copied. 907 | * this takes effect immediately, on whichever frame is encoded next; 908 | * due to delay, this may not be the next frame passed to encoder_encode. 909 | * if the change should apply to some particular frame, use x264_picture_t->param instead. 910 | * returns 0 on success, negative on parameter validation error. 911 | * not all parameters can be changed; see the actual function for a detailed breakdown. 912 | * 913 | * since not all parameters can be changed, moving from preset to preset may not always 914 | * fully copy all relevant parameters, but should still work usably in practice. however, 915 | * more so than for other presets, many of the speed shortcuts used in ultrafast cannot be 916 | * switched out of; using reconfig to switch between ultrafast and other presets is not 917 | * recommended without a more fine-grained breakdown of parameters to take this into account. */ 918 | X264_API int x264_encoder_reconfig( x264_t *, x264_param_t * ); 919 | /* x264_encoder_parameters: 920 | * copies the current internal set of parameters to the pointer provided 921 | * by the caller. useful when the calling application needs to know 922 | * how x264_encoder_open has changed the parameters, or the current state 923 | * of the encoder after multiple x264_encoder_reconfig calls. 924 | * note that the data accessible through pointers in the returned param struct 925 | * (e.g. filenames) should not be modified by the calling application. */ 926 | X264_API void x264_encoder_parameters( x264_t *, x264_param_t * ); 927 | /* x264_encoder_headers: 928 | * return the SPS and PPS that will be used for the whole stream. 929 | * *pi_nal is the number of NAL units outputted in pp_nal. 930 | * returns the number of bytes in the returned NALs. 931 | * returns negative on error. 932 | * the payloads of all output NALs are guaranteed to be sequential in memory. */ 933 | X264_API int x264_encoder_headers( x264_t *, x264_nal_t **pp_nal, int *pi_nal ); 934 | /* x264_encoder_encode: 935 | * encode one picture. 936 | * *pi_nal is the number of NAL units outputted in pp_nal. 937 | * returns the number of bytes in the returned NALs. 938 | * returns negative on error and zero if no NAL units returned. 939 | * the payloads of all output NALs are guaranteed to be sequential in memory. */ 940 | X264_API int x264_encoder_encode( x264_t *, x264_nal_t **pp_nal, int *pi_nal, x264_picture_t *pic_in, x264_picture_t *pic_out ); 941 | /* x264_encoder_close: 942 | * close an encoder handler */ 943 | X264_API void x264_encoder_close( x264_t * ); 944 | /* x264_encoder_delayed_frames: 945 | * return the number of currently delayed (buffered) frames 946 | * this should be used at the end of the stream, to know when you have all the encoded frames. */ 947 | X264_API int x264_encoder_delayed_frames( x264_t * ); 948 | /* x264_encoder_maximum_delayed_frames( x264_t * ): 949 | * return the maximum number of delayed (buffered) frames that can occur with the current 950 | * parameters. */ 951 | X264_API int x264_encoder_maximum_delayed_frames( x264_t * ); 952 | /* x264_encoder_intra_refresh: 953 | * If an intra refresh is not in progress, begin one with the next P-frame. 954 | * If an intra refresh is in progress, begin one as soon as the current one finishes. 955 | * Requires that b_intra_refresh be set. 956 | * 957 | * Useful for interactive streaming where the client can tell the server that packet loss has 958 | * occurred. In this case, keyint can be set to an extremely high value so that intra refreshes 959 | * only occur when calling x264_encoder_intra_refresh. 960 | * 961 | * In multi-pass encoding, if x264_encoder_intra_refresh is called differently in each pass, 962 | * behavior is undefined. 963 | * 964 | * Should not be called during an x264_encoder_encode. */ 965 | X264_API void x264_encoder_intra_refresh( x264_t * ); 966 | /* x264_encoder_invalidate_reference: 967 | * An interactive error resilience tool, designed for use in a low-latency one-encoder-few-clients 968 | * system. When the client has packet loss or otherwise incorrectly decodes a frame, the encoder 969 | * can be told with this command to "forget" the frame and all frames that depend on it, referencing 970 | * only frames that occurred before the loss. This will force a keyframe if no frames are left to 971 | * reference after the aforementioned "forgetting". 972 | * 973 | * It is strongly recommended to use a large i_dpb_size in this case, which allows the encoder to 974 | * keep around extra, older frames to fall back on in case more recent frames are all invalidated. 975 | * Unlike increasing i_frame_reference, this does not increase the number of frames used for motion 976 | * estimation and thus has no speed impact. It is also recommended to set a very large keyframe 977 | * interval, so that keyframes are not used except as necessary for error recovery. 978 | * 979 | * x264_encoder_invalidate_reference is not currently compatible with the use of B-frames or intra 980 | * refresh. 981 | * 982 | * In multi-pass encoding, if x264_encoder_invalidate_reference is called differently in each pass, 983 | * behavior is undefined. 984 | * 985 | * Should not be called during an x264_encoder_encode, but multiple calls can be made simultaneously. 986 | * 987 | * Returns 0 on success, negative on failure. */ 988 | X264_API int x264_encoder_invalidate_reference( x264_t *, int64_t pts ); 989 | 990 | #ifdef __cplusplus 991 | } 992 | #endif 993 | 994 | #endif 995 | --------------------------------------------------------------------------------