• Android 使用FFmpeg3.3.9基于命令实现视频压缩


    前言

    首先利用linux平台编译ffmpeg的so库,具体详情请查看文章:Android NDK(ndk-r16b)交叉编译FFmpeg(3.3.9)_jszlittlecat_720的博客-CSDN博客

    1.创建VideoCompress类

     

    1. package com.suoer.ndk.ffmpegtestapplication;
    2. public class VideoCompress {
    3. /**
    4. * compressVideo native 方法
    5. * @param compressCommand 压缩命令
    6. * @param callback 压缩回调
    7. */
    8. public native void compressVideo(String[] compressCommand,CompressCallback callback);
    9. //CompressCallback 压缩回调
    10. public interface CompressCallback{
    11. /**
    12. * onCompress
    13. * @param current 压缩的当前进度
    14. * @param total 总进度
    15. */
    16. public void onCompress(int current,int total);
    17. }
    18. }
    compressVideo报红,鼠标停在上面,左边会出现红色小灯泡,点击红色小灯泡

     点击Create JNI function for compressVideo

    自动打开native-lib.cpp并创建完成Java_com_suoer_ndk_ffmpegtestapplication_VideoCompress_compressVideo 方法

     在此方法下实现压缩视频

    2.MainActivity实现点击TextView实现压缩视频

    2.1权限问题处理

    压缩视频需要读写文件的权限

    打开AndroidManifest.xml

    添加读写文件权限

    1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">uses-permission>
    2. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE">uses-permission>

     权限处理使用rxpermissions

    rxpermissions github地址:GitHub - tbruyelle/RxPermissions: Android runtime permissions powered by RxJava2

    rxpermissions使用方式

    打开项目下的build.gradle添加如下代码:

    maven { url 'https://jitpack.io' }

     打开app下的build.gradle添加如下代码:

    implementation 'com.github.tbruyelle:rxpermissions:0.12'

     点击同步按钮,同步文件

     2.2子线程处理耗时操作

    压缩视频是耗时操作,子线程处理耗时操作。

    使用rxandroid实现子线程耗时操作并实现子线程和主线程切换

    rxandroid github地址:GitHub - ReactiveX/RxAndroid: RxJava bindings for Android

     rxandroid使用方式:

    打开项目下的build.gradle添加如下代码:

    maven { url "https://oss.jfrog.org/libs-snapshot" }

     打开app下的build.gradle添加如下代码:

    implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'

     点击同步按钮同步文件

    MainActivity.java内容如下:

    1. package com.suoer.ndk.ffmpegtestapplication;
    2. import android.Manifest;
    3. import android.os.Bundle;
    4. import android.os.Environment;
    5. import android.util.Log;
    6. import android.view.View;
    7. import android.widget.TextView;
    8. import com.tbruyelle.rxpermissions3.RxPermissions;
    9. import java.io.File;
    10. import androidx.appcompat.app.AppCompatActivity;
    11. import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
    12. import io.reactivex.rxjava3.core.Observable;
    13. import io.reactivex.rxjava3.functions.Consumer;
    14. import io.reactivex.rxjava3.functions.Function;
    15. import io.reactivex.rxjava3.schedulers.Schedulers;
    16. public class MainActivity extends AppCompatActivity {
    17. private File mInFile=new File(Environment.getExternalStorageDirectory(),"test.mp4");//mInFile 需要压缩的文件路径
    18. private File mOutFile=new File(Environment.getExternalStorageDirectory(),"out.mp4");//mOutFile压缩后的文件路径
    19. // Used to load the 'native-lib' library on application startup.
    20. static {
    21. System.loadLibrary("native-lib");
    22. }
    23. @Override
    24. protected void onCreate(Bundle savedInstanceState) {
    25. super.onCreate(savedInstanceState);
    26. setContentView(R.layout.activity_main);
    27. // Example of a call to a native method
    28. TextView tv = findViewById(R.id.sample_text);
    29. //tv.setText("ffmpeg版本:"+stringFromJNI());
    30. tv.setText("压缩");
    31. //tv的点击事件 点击按钮实现视频压缩
    32. tv.setOnClickListener(new View.OnClickListener() {
    33. @Override
    34. public void onClick(View v) {
    35. // 压缩文件 需要读写文件权限 申请权限
    36. RxPermissions rxPermissions=new RxPermissions(MainActivity.this);
    37. rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Consumer() {
    38. @Override
    39. public void accept(Boolean aBoolean) throws Throwable {
    40. if(aBoolean){
    41. //权限已经获取 压缩视频
    42. compressVideo();
    43. }
    44. }
    45. });
    46. }
    47. });
    48. }
    49. /**
    50. * 开启子线程处理耗时压缩问题
    51. */
    52. private void compressVideo() {
    53. //ffmpeg的压缩命令:ffmpeg -i test.mp4 -b:v 1024k out.mp4
    54. //ffmpeg -i test.mp4 -b:v 1024k out.mp4
    55. //-b:v 1024k 1024k为码率 码率越高视频越清晰,而且视频越大
    56. //test.mp4需要压缩的文件
    57. //out.mp4 压缩之后的文件
    58. String[] compressCommand={"ffmpeg","-i",mInFile.getAbsolutePath(),"-b:v","1024k",mOutFile.getAbsolutePath()};
    59. //压缩是耗时的,需要子线程处理
    60. Observable.just(compressCommand).map(new Function() {
    61. @Override
    62. public File apply(String[] compressCommand) throws Throwable {
    63. VideoCompress videoCompress=new VideoCompress();
    64. videoCompress.compressVideo(compressCommand, new VideoCompress.CompressCallback() {
    65. @Override
    66. public void onCompress(int current, int total) {
    67. Log.e("TAG", "onCompress: 压缩进度:"+current+"/"+total);
    68. }
    69. });
    70. return mOutFile;
    71. }
    72. }).subscribeOn(Schedulers.io())
    73. .observeOn(AndroidSchedulers.mainThread())
    74. .subscribe(new Consumer() {
    75. @Override
    76. public void accept(File file) throws Throwable {
    77. //压缩完成
    78. Log.e("TAG", "accept: 压缩完成!" );
    79. }
    80. });
    81. }
    82. /**
    83. * A native method that is implemented by the 'native-lib' native library,
    84. * which is packaged with this application.
    85. */
    86. public native String stringFromJNI();
    87. }

    3.拷贝视频压缩使用命令实现需要的其他文件

    include目录下创建compat文件夹把所需要的头文件 os2threads.h va_copy.h w32pthreads.h拷贝此文件夹中

    这三个头文件存在于下载之后的ffmpeg-3.3.9.tar.gz解压之后的文件夹ffmpeg-3.3.9的compat文件夹中

     在jniLibs文件夹中创建other文件夹

     拷贝linux平台编译后的文件cmdutils.h cmdutils_common_opts.h config.h ffmpeg.h 拷贝至other文件夹中

     

     将下载之后的ffmpeg-3.3.9.tar.gz解压之后的文件夹ffmpeg-3.3.9中的cmdutils.c 

    ffmpeg.c ffmpeg_filter.c ffmpeg_opt.c 四个文件拷贝至cpp文件夹中

     

     配置CMakeLists.txt文件修改如下内容

     CMakeLists.txt内容如下:

    1. # For more information about using CMake with Android Studio, read the
    2. # documentation: https://d.android.com/studio/projects/add-native-code.html
    3. # Sets the minimum version of CMake required to build the native library.
    4. cmake_minimum_required(VERSION 3.10.2)
    5. # Declares and names the project.
    6. project("ffmpegtestapplication")
    7. #判断编译器类型,如果是gcc编译器,则在编译选项中加入c++11支持
    8. if(CMAKE_COMPILER_IS_GNUCXX)
    9. set(CMAKE_CXX_FLAGS "-std=c++11 ${CMAKE_CXX_FLAGS}")
    10. message(STATUS "optional:-std=c++11")
    11. endif(CMAKE_COMPILER_IS_GNUCXX)
    12. #需要引入我们头文件,以这个配置的目录为基准
    13. include_directories(${CMAKE_SOURCE_DIR}/../jniLibs/include)
    14. include_directories(${CMAKE_SOURCE_DIR}/../jniLibs/other)
    15. # Creates and names a library, sets it as either STATIC
    16. # or SHARED, and provides the relative paths to its source code.
    17. # You can define multiple libraries, and CMake builds them for you.
    18. # Gradle automatically packages shared libraries with your APK.
    19. add_library( # Sets the name of the library.
    20. native-lib
    21. # Sets the library as a shared library.
    22. SHARED
    23. # Provides a relative path to your source file(s).
    24. native-lib.cpp
    25. #添加额外的c文件
    26. cmdutils.c
    27. ffmpeg.c
    28. ffmpeg_filter.c
    29. ffmpeg_opt.c
    30. )
    31. # 编解码(最重要的库)
    32. add_library(
    33. avcodec
    34. SHARED
    35. IMPORTED)
    36. set_target_properties(
    37. avcodec
    38. PROPERTIES IMPORTED_LOCATION
    39. ${CMAKE_SOURCE_DIR}/../jniLibs/armeabi-v7a/libavcodec-57.so)
    40. # 设备信息
    41. add_library(
    42. avdevice
    43. SHARED
    44. IMPORTED)
    45. set_target_properties(
    46. avdevice
    47. PROPERTIES IMPORTED_LOCATION
    48. ${CMAKE_SOURCE_DIR}/../jniLibs/armeabi-v7a/libavdevice-57.so)
    49. # 滤镜特效处理库
    50. add_library(
    51. avfilter
    52. SHARED
    53. IMPORTED)
    54. set_target_properties(
    55. avfilter
    56. PROPERTIES IMPORTED_LOCATION
    57. ${CMAKE_SOURCE_DIR}/../jniLibs/armeabi-v7a/libavfilter-6.so)
    58. # 封装格式处理库
    59. add_library(
    60. avformat
    61. SHARED
    62. IMPORTED)
    63. set_target_properties(
    64. avformat
    65. PROPERTIES IMPORTED_LOCATION
    66. ${CMAKE_SOURCE_DIR}/../jniLibs/armeabi-v7a/libavformat-57.so)
    67. # 重采样处理库
    68. add_library(
    69. avresample
    70. SHARED
    71. IMPORTED)
    72. set_target_properties(
    73. avresample
    74. PROPERTIES IMPORTED_LOCATION
    75. ${CMAKE_SOURCE_DIR}/../jniLibs/armeabi-v7a/libavresample-3.so)
    76. # 工具库(大部分库都需要这个库的支持)
    77. add_library(
    78. avutil
    79. SHARED
    80. IMPORTED)
    81. set_target_properties(
    82. avutil
    83. PROPERTIES IMPORTED_LOCATION
    84. ${CMAKE_SOURCE_DIR}/../jniLibs/armeabi-v7a/libavutil-55.so)
    85. # 后期处理
    86. add_library(
    87. postproc
    88. SHARED
    89. IMPORTED)
    90. set_target_properties(
    91. postproc
    92. PROPERTIES IMPORTED_LOCATION
    93. ${CMAKE_SOURCE_DIR}/../jniLibs/armeabi-v7a/libpostproc-54.so)
    94. # 音频采样数据格式转换库
    95. add_library(
    96. swresample
    97. SHARED
    98. IMPORTED)
    99. set_target_properties(
    100. swresample
    101. PROPERTIES IMPORTED_LOCATION
    102. ${CMAKE_SOURCE_DIR}/../jniLibs/armeabi-v7a/libswresample-2.so)
    103. # 视频像素数据格式转换
    104. add_library(
    105. swscale
    106. SHARED
    107. IMPORTED)
    108. set_target_properties(
    109. swscale
    110. PROPERTIES IMPORTED_LOCATION
    111. ${CMAKE_SOURCE_DIR}/../jniLibs/armeabi-v7a/libswscale-4.so)
    112. # Searches for a specified prebuilt library and stores the path as a
    113. # variable. Because CMake includes system libraries in the search path by
    114. # default, you only need to specify the name of the public NDK library
    115. # you want to add. CMake verifies that the library exists before
    116. # completing its build.
    117. find_library( # Sets the name of the path variable.
    118. log-lib
    119. # Specifies the name of the NDK library that
    120. # you want CMake to locate.
    121. log )
    122. # Specifies libraries CMake should link to your target library. You
    123. # can link multiple libraries, such as libraries you define in this
    124. # build script, prebuilt third-party libraries, or system libraries.
    125. target_link_libraries( # Specifies the target library.
    126. native-lib avcodec avdevice avfilter avformat avresample avutil postproc swresample swscale
    127. # Links the target library to the log library
    128. # included in the NDK.
    129. ${log-lib} )

    运行Run app至手机设备,出现如下如所示错误

     D:\suowei\androidproject\FFmpegTestApplication\app\src\main\cpp\cmdutils.c:47:10: fatal error: 'libavutil/libm.h' file not found

    解决方式:将下载之后的ffmpeg-3.3.9.tar.gz解压之后的文件夹ffmpeg-3.3.9中libavutil中的libm.h拷贝至android项目jniLibs下的libavutil中

     

     D:\suowei\androidproject\FFmpegTestApplication\app\src\main\cpp\ffmpeg.c:52:10: fatal error: 'libavutil/internal.h' file not found

     解决方式:将下载之后的ffmpeg-3.3.9.tar.gz解压之后的文件夹ffmpeg-3.3.9中libavutil中的internal.h拷贝至android项目jniLibs下的libavutil中

     

     重新Run app至手机设备,出现如下图所示错误

     D:\suowei\androidproject\FFmpegTestApplication\app\src\main\cpp\cmdutils.c:58:10: fatal error: 'libavformat/network.h' file not found

    解决方式:将下载之后的ffmpeg-3.3.9.tar.gz解压之后的文件夹ffmpeg-3.3.9中libavformat中的network.h拷贝至android项目jniLibs下的libavformat中

     

     D:\suowei\androidproject\FFmpegTestApplication\app\src\main\jniLibs\include\libavutil\internal.h:42:10: fatal error: 'timer.h' file not found

     解决方式:将下载之后的ffmpeg-3.3.9.tar.gz解压之后的文件夹ffmpeg-3.3.9中libavutil中的timer.h拷贝至android项目jniLibs下的libavutil中

     

     

     重新Run app至手机设备,出现如下图所示错误

     D:/suowei/androidproject/FFmpegTestApplication/app/src/main/cpp/../jniLibs/include\libavformat/network.h:29:10: fatal error: 'os_support.h' file not found
    #include "os_support.h"

      解决方式:将下载之后的ffmpeg-3.3.9.tar.gz解压之后的文件夹ffmpeg-3.3.9中libavformat中的os_support.h拷贝至android项目jniLibs下的libavformat中

     

     D:/suowei/androidproject/FFmpegTestApplication/app/src/main/cpp/../jniLibs/include\libavutil/timer.h:44:13: fatal error: 'arm/timer.h' file not found

    解决方式:android项目jniLibs目录下的libavutil文件夹下创建arm文件夹

     将下载之后的ffmpeg-3.3.9.tar.gz解压之后的文件夹ffmpeg-3.3.9中libavutil中的arm文件夹下的timer.h拷贝至android项目jniLibs下的libavutil中的arm文件夹下

     

     重新Run app至手机设备,出现如下图所示错误

     D:/suowei/androidproject/FFmpegTestApplication/app/src/main/cpp/ffmpeg.c:65:10: fatal error: 'libavcodec/mathops.h' file not found

    解决方式:将下载之后的ffmpeg-3.3.9.tar.gz解压之后的文件夹ffmpeg-3.3.9中libavcodec中的mathops.h拷贝至android项目jniLibs下的libavcodec中

     

     重新Run app至手机设备,出现如下图所示错误

     D:/suowei/androidproject/FFmpegTestApplication/app/src/main/cpp/../jniLibs/include\libavformat/network.h:31:10: fatal error: 'url.h' file not found

    解决方式:将下载之后的ffmpeg-3.3.9.tar.gz解压之后的文件夹ffmpeg-3.3.9中libavformat中的url.h拷贝至android项目jniLibs下的libavformat中

     D:/suowei/androidproject/FFmpegTestApplication/app/src/main/cpp/../jniLibs/include\libavcodec/mathops.h:28:10: fatal error: 'libavutil/reverse.h' file not found

    解决方式:将下载之后的ffmpeg-3.3.9.tar.gz解压之后的文件夹ffmpeg-3.3.9中libavutil中的reverse.h拷贝至android项目jniLibs下的libavutil中

     

     

     重新Run app至手机设备,出现如下图所示错误

     D:/suowei/androidproject/FFmpegTestApplication/app/src/main/cpp/../jniLibs/include\libavcodec/mathops.h:40:13: fatal error: 'arm/mathops.h' file not found

    解决方式:android项目jniLibs目录下的libavcodec文件夹下创建arm文件夹

     

     将下载之后的ffmpeg-3.3.9.tar.gz解压之后的文件夹ffmpeg-3.3.9中libavcodec中的arm文件夹下的mathops.h拷贝至android项目jniLibs下的libavcodec中的arm文件夹下

     

     重新Run app至手机设备,android项目运行成功。

    4.编写native-cpp实现视频压缩

     

    修改ffmpeg.c,找到main方法修改方法名称为:run_ffmpeg_command 并注释掉此行代码

    exit_program(received_nb_signals ? 255 : main_return_code);
    
    1. //命令函数的入口
    2. int run_ffmpeg_command(int argc, char **argv)
    3. {
    4. int i, ret;
    5. int64_t ti;
    6. init_dynload();
    7. register_exit(ffmpeg_cleanup);
    8. setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
    9. av_log_set_flags(AV_LOG_SKIP_REPEATED);
    10. parse_loglevel(argc, argv, options);
    11. if(argc>1 && !strcmp(argv[1], "-d")){
    12. run_as_daemon=1;
    13. av_log_set_callback(log_callback_null);
    14. argc--;
    15. argv++;
    16. }
    17. avcodec_register_all();
    18. #if CONFIG_AVDEVICE
    19. avdevice_register_all();
    20. #endif
    21. avfilter_register_all();
    22. av_register_all();
    23. avformat_network_init();
    24. show_banner(argc, argv, options);
    25. /* parse options and open all input/output files */
    26. ret = ffmpeg_parse_options(argc, argv);
    27. if (ret < 0)
    28. exit_program(1);
    29. if (nb_output_files <= 0 && nb_input_files == 0) {
    30. show_usage();
    31. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
    32. exit_program(1);
    33. }
    34. /* file converter / grab */
    35. if (nb_output_files <= 0) {
    36. av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
    37. exit_program(1);
    38. }
    39. // if (nb_input_files == 0) {
    40. // av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
    41. // exit_program(1);
    42. // }
    43. for (i = 0; i < nb_output_files; i++) {
    44. if (strcmp(output_files[i]->ctx->oformat->name, "rtp"))
    45. want_sdp = 0;
    46. }
    47. current_time = ti = getutime();
    48. if (transcode() < 0)
    49. exit_program(1);
    50. ti = getutime() - ti;
    51. if (do_benchmark) {
    52. av_log(NULL, AV_LOG_INFO, "bench: utime=%0.3fs\n", ti / 1000000.0);
    53. }
    54. av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
    55. decode_error_stat[0], decode_error_stat[1]);
    56. if ((decode_error_stat[0] + decode_error_stat[1]) * max_error_rate < decode_error_stat[1])
    57. exit_program(69);
    58. //注释掉此行代码 如果不注释掉该行代码,命令执行完会导致app退出
    59. //exit_program(received_nb_signals ? 255 : main_return_code);
    60. return main_return_code;
    61. }

    native-lib.cpp代码如下:

    1. #include
    2. #include
    3. #include
    4. #define TAG "JNI_TAG"
    5. #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG,__VA_ARGS__);
    6. extern "C" {
    7. #include "libavutil/avutil.h"
    8. //声明方法 argc命令的个数 argv 二维数组
    9. int run_ffmpeg_command(int argc, char **argv);
    10. }
    11. extern "C" JNIEXPORT jstring JNICALL
    12. Java_com_suoer_ndk_ffmpegtestapplication_MainActivity_stringFromJNI(
    13. JNIEnv* env,
    14. jobject /* this */) {
    15. //std::string hello = "Hello from C++";
    16. return env->NewStringUTF(av_version_info());
    17. }extern "C"
    18. JNIEXPORT void JNICALL
    19. Java_com_suoer_ndk_ffmpegtestapplication_VideoCompress_compressVideo(JNIEnv *env, jobject thiz,
    20. jobjectArray compress_command,
    21. jobject callback) {
    22. //ffmpeg 处理视频压缩
    23. //arm这个里面的so都是用来处理音视频的,include都是头文件
    24. //还有几个没有被打包编译成so,因为这些不算是音视频的处理代码,只是我们现在支持命令(封装)
    25. //1.获取命令个数
    26. int argc=env->GetArrayLength(compress_command);
    27. //2.给char **argv填充数据
    28. char **argv=(char **)malloc(sizeof(char*)*argc);
    29. for (int i = 0; i
    30. jstring j_param=(jstring)env->GetObjectArrayElement(compress_command,i);
    31. argv[i]= (char *)(env->GetStringUTFChars(j_param, NULL));
    32. LOGE("参数:%s",argv[i]);
    33. }
    34. //3.调用命令函数去压缩
    35. run_ffmpeg_command(argc,argv);
    36. //4.释放内存
    37. for (int i = 0; i
    38. free(argv[i]);
    39. }
    40. free(argv);
    41. }

    视频压缩回调处理,视频压缩进度回调

    修改ffmpeg.c内容如下:

    print_report方法

     

     transcode方法

     

     

     run_ffmpeg_command方法

     

     

     ffmpeg.c内容如下:

    1. /*
    2. * Copyright (c) 2000-2003 Fabrice Bellard
    3. *
    4. * This file is part of FFmpeg.
    5. *
    6. * FFmpeg 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. * FFmpeg 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 FFmpeg; if not, write to the Free Software
    18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
    19. */
    20. /**
    21. * @file
    22. * multimedia converter based on the FFmpeg libraries
    23. */
    24. #include "config.h"
    25. #include
    26. #include
    27. #include
    28. #include
    29. #include
    30. #include
    31. #include
    32. #include
    33. #if HAVE_IO_H
    34. #include
    35. #endif
    36. #if HAVE_UNISTD_H
    37. #include
    38. #endif
    39. #include "libavformat/avformat.h"
    40. #include "libavdevice/avdevice.h"
    41. #include "libswresample/swresample.h"
    42. #include "libavutil/opt.h"
    43. #include "libavutil/channel_layout.h"
    44. #include "libavutil/parseutils.h"
    45. #include "libavutil/samplefmt.h"
    46. #include "libavutil/fifo.h"
    47. #include "libavutil/hwcontext.h"
    48. #include "libavutil/internal.h"
    49. #include "libavutil/intreadwrite.h"
    50. #include "libavutil/dict.h"
    51. #include "libavutil/display.h"
    52. #include "libavutil/mathematics.h"
    53. #include "libavutil/pixdesc.h"
    54. #include "libavutil/avstring.h"
    55. #include "libavutil/libm.h"
    56. #include "libavutil/imgutils.h"
    57. #include "libavutil/timestamp.h"
    58. #include "libavutil/bprint.h"
    59. #include "libavutil/time.h"
    60. #include "libavutil/threadmessage.h"
    61. #include "libavcodec/mathops.h"
    62. #include "libavformat/os_support.h"
    63. # include "libavfilter/avfilter.h"
    64. # include "libavfilter/buffersrc.h"
    65. # include "libavfilter/buffersink.h"
    66. #if HAVE_SYS_RESOURCE_H
    67. #include
    68. #include
    69. #include
    70. #elif HAVE_GETPROCESSTIMES
    71. #include
    72. #endif
    73. #if HAVE_GETPROCESSMEMORYINFO
    74. #include
    75. #include
    76. #endif
    77. #if HAVE_SETCONSOLECTRLHANDLER
    78. #include
    79. #endif
    80. #if HAVE_SYS_SELECT_H
    81. #include
    82. #endif
    83. #if HAVE_TERMIOS_H
    84. #include
    85. #include
    86. #include
    87. #include
    88. #elif HAVE_KBHIT
    89. #include
    90. #endif
    91. #if HAVE_PTHREADS
    92. #include
    93. #endif
    94. #include
    95. #include
    96. #include "ffmpeg.h"
    97. #include "cmdutils.h"
    98. #include "libavutil/avassert.h"
    99. const char program_name[] = "ffmpeg";
    100. const int program_birth_year = 2000;
    101. static FILE *vstats_file;
    102. const char *const forced_keyframes_const_names[] = {
    103. "n",
    104. "n_forced",
    105. "prev_forced_n",
    106. "prev_forced_t",
    107. "t",
    108. NULL
    109. };
    110. static void do_video_stats(OutputStream *ost, int frame_size);
    111. static int64_t getutime(void);
    112. static int64_t getmaxrss(void);
    113. static int ifilter_has_all_input_formats(FilterGraph *fg);
    114. static int run_as_daemon = 0;
    115. static int nb_frames_dup = 0;
    116. static unsigned dup_warning = 1000;
    117. static int nb_frames_drop = 0;
    118. static int64_t decode_error_stat[2];
    119. static int want_sdp = 1;
    120. static int current_time;
    121. AVIOContext *progress_avio = NULL;
    122. static uint8_t *subtitle_out;
    123. InputStream **input_streams = NULL;
    124. int nb_input_streams = 0;
    125. InputFile **input_files = NULL;
    126. int nb_input_files = 0;
    127. OutputStream **output_streams = NULL;
    128. int nb_output_streams = 0;
    129. OutputFile **output_files = NULL;
    130. int nb_output_files = 0;
    131. FilterGraph **filtergraphs;
    132. int nb_filtergraphs;
    133. #if HAVE_TERMIOS_H
    134. /* init terminal so that we can grab keys */
    135. static struct termios oldtty;
    136. static int restore_tty;
    137. #endif
    138. #if HAVE_PTHREADS
    139. static void free_input_threads(void);
    140. #endif
    141. /* sub2video hack:
    142. Convert subtitles to video with alpha to insert them in filter graphs.
    143. This is a temporary solution until libavfilter gets real subtitles support.
    144. */
    145. static int sub2video_get_blank_frame(InputStream *ist)
    146. {
    147. int ret;
    148. AVFrame *frame = ist->sub2video.frame;
    149. av_frame_unref(frame);
    150. ist->sub2video.frame->width = ist->dec_ctx->width ? ist->dec_ctx->width : ist->sub2video.w;
    151. ist->sub2video.frame->height = ist->dec_ctx->height ? ist->dec_ctx->height : ist->sub2video.h;
    152. ist->sub2video.frame->format = AV_PIX_FMT_RGB32;
    153. if ((ret = av_frame_get_buffer(frame, 32)) < 0)
    154. return ret;
    155. memset(frame->data[0], 0, frame->height * frame->linesize[0]);
    156. return 0;
    157. }
    158. static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
    159. AVSubtitleRect *r)
    160. {
    161. uint32_t *pal, *dst2;
    162. uint8_t *src, *src2;
    163. int x, y;
    164. if (r->type != SUBTITLE_BITMAP) {
    165. av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
    166. return;
    167. }
    168. if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
    169. av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle (%d %d %d %d) overflowing %d %d\n",
    170. r->x, r->y, r->w, r->h, w, h
    171. );
    172. return;
    173. }
    174. dst += r->y * dst_linesize + r->x * 4;
    175. src = r->data[0];
    176. pal = (uint32_t *)r->data[1];
    177. for (y = 0; y < r->h; y++) {
    178. dst2 = (uint32_t *)dst;
    179. src2 = src;
    180. for (x = 0; x < r->w; x++)
    181. *(dst2++) = pal[*(src2++)];
    182. dst += dst_linesize;
    183. src += r->linesize[0];
    184. }
    185. }
    186. static void sub2video_push_ref(InputStream *ist, int64_t pts)
    187. {
    188. AVFrame *frame = ist->sub2video.frame;
    189. int i;
    190. av_assert1(frame->data[0]);
    191. ist->sub2video.last_pts = frame->pts = pts;
    192. for (i = 0; i < ist->nb_filters; i++)
    193. av_buffersrc_add_frame_flags(ist->filters[i]->filter, frame,
    194. AV_BUFFERSRC_FLAG_KEEP_REF |
    195. AV_BUFFERSRC_FLAG_PUSH);
    196. }
    197. void sub2video_update(InputStream *ist, AVSubtitle *sub)
    198. {
    199. AVFrame *frame = ist->sub2video.frame;
    200. int8_t *dst;
    201. int dst_linesize;
    202. int num_rects, i;
    203. int64_t pts, end_pts;
    204. if (!frame)
    205. return;
    206. if (sub) {
    207. pts = av_rescale_q(sub->pts + sub->start_display_time * 1000LL,
    208. AV_TIME_BASE_Q, ist->st->time_base);
    209. end_pts = av_rescale_q(sub->pts + sub->end_display_time * 1000LL,
    210. AV_TIME_BASE_Q, ist->st->time_base);
    211. num_rects = sub->num_rects;
    212. } else {
    213. pts = ist->sub2video.end_pts;
    214. end_pts = INT64_MAX;
    215. num_rects = 0;
    216. }
    217. if (sub2video_get_blank_frame(ist) < 0) {
    218. av_log(ist->dec_ctx, AV_LOG_ERROR,
    219. "Impossible to get a blank canvas.\n");
    220. return;
    221. }
    222. dst = frame->data [0];
    223. dst_linesize = frame->linesize[0];
    224. for (i = 0; i < num_rects; i++)
    225. sub2video_copy_rect(dst, dst_linesize, frame->width, frame->height, sub->rects[i]);
    226. sub2video_push_ref(ist, pts);
    227. ist->sub2video.end_pts = end_pts;
    228. }
    229. static void sub2video_heartbeat(InputStream *ist, int64_t pts)
    230. {
    231. InputFile *infile = input_files[ist->file_index];
    232. int i, j, nb_reqs;
    233. int64_t pts2;
    234. /* When a frame is read from a file, examine all sub2video streams in
    235. the same file and send the sub2video frame again. Otherwise, decoded
    236. video frames could be accumulating in the filter graph while a filter
    237. (possibly overlay) is desperately waiting for a subtitle frame. */
    238. for (i = 0; i < infile->nb_streams; i++) {
    239. InputStream *ist2 = input_streams[infile->ist_index + i];
    240. if (!ist2->sub2video.frame)
    241. continue;
    242. /* subtitles seem to be usually muxed ahead of other streams;
    243. if not, subtracting a larger time here is necessary */
    244. pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
    245. /* do not send the heartbeat frame if the subtitle is already ahead */
    246. if (pts2 <= ist2->sub2video.last_pts)
    247. continue;
    248. if (pts2 >= ist2->sub2video.end_pts || !ist2->sub2video.frame->data[0])
    249. sub2video_update(ist2, NULL);
    250. for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
    251. nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
    252. if (nb_reqs)
    253. sub2video_push_ref(ist2, pts2);
    254. }
    255. }
    256. static void sub2video_flush(InputStream *ist)
    257. {
    258. int i;
    259. if (ist->sub2video.end_pts < INT64_MAX)
    260. sub2video_update(ist, NULL);
    261. for (i = 0; i < ist->nb_filters; i++)
    262. av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
    263. }
    264. /* end of sub2video hack */
    265. static void term_exit_sigsafe(void)
    266. {
    267. #if HAVE_TERMIOS_H
    268. if(restore_tty)
    269. tcsetattr (0, TCSANOW, &oldtty);
    270. #endif
    271. }
    272. void term_exit(void)
    273. {
    274. av_log(NULL, AV_LOG_QUIET, "%s", "");
    275. term_exit_sigsafe();
    276. }
    277. static volatile int received_sigterm = 0;
    278. static volatile int received_nb_signals = 0;
    279. static atomic_int transcode_init_done = ATOMIC_VAR_INIT(0);
    280. static volatile int ffmpeg_exited = 0;
    281. static int main_return_code = 0;
    282. static void
    283. sigterm_handler(int sig)
    284. {
    285. received_sigterm = sig;
    286. received_nb_signals++;
    287. term_exit_sigsafe();
    288. if(received_nb_signals > 3) {
    289. write(2/*STDERR_FILENO*/, "Received > 3 system signals, hard exiting\n",
    290. strlen("Received > 3 system signals, hard exiting\n"));
    291. exit(123);
    292. }
    293. }
    294. #if HAVE_SETCONSOLECTRLHANDLER
    295. static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
    296. {
    297. av_log(NULL, AV_LOG_DEBUG, "\nReceived windows signal %ld\n", fdwCtrlType);
    298. switch (fdwCtrlType)
    299. {
    300. case CTRL_C_EVENT:
    301. case CTRL_BREAK_EVENT:
    302. sigterm_handler(SIGINT);
    303. return TRUE;
    304. case CTRL_CLOSE_EVENT:
    305. case CTRL_LOGOFF_EVENT:
    306. case CTRL_SHUTDOWN_EVENT:
    307. sigterm_handler(SIGTERM);
    308. /* Basically, with these 3 events, when we return from this method the
    309. process is hard terminated, so stall as long as we need to
    310. to try and let the main thread(s) clean up and gracefully terminate
    311. (we have at most 5 seconds, but should be done far before that). */
    312. while (!ffmpeg_exited) {
    313. Sleep(0);
    314. }
    315. return TRUE;
    316. default:
    317. av_log(NULL, AV_LOG_ERROR, "Received unknown windows signal %ld\n", fdwCtrlType);
    318. return FALSE;
    319. }
    320. }
    321. #endif
    322. void term_init(void)
    323. {
    324. #if HAVE_TERMIOS_H
    325. if (!run_as_daemon && stdin_interaction) {
    326. struct termios tty;
    327. if (tcgetattr (0, &tty) == 0) {
    328. oldtty = tty;
    329. restore_tty = 1;
    330. tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
    331. |INLCR|IGNCR|ICRNL|IXON);
    332. tty.c_oflag |= OPOST;
    333. tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
    334. tty.c_cflag &= ~(CSIZE|PARENB);
    335. tty.c_cflag |= CS8;
    336. tty.c_cc[VMIN] = 1;
    337. tty.c_cc[VTIME] = 0;
    338. tcsetattr (0, TCSANOW, &tty);
    339. }
    340. signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
    341. }
    342. #endif
    343. signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
    344. signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
    345. #ifdef SIGXCPU
    346. signal(SIGXCPU, sigterm_handler);
    347. #endif
    348. #if HAVE_SETCONSOLECTRLHANDLER
    349. SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
    350. #endif
    351. }
    352. /* read a key without blocking */
    353. static int read_key(void)
    354. {
    355. unsigned char ch;
    356. #if HAVE_TERMIOS_H
    357. int n = 1;
    358. struct timeval tv;
    359. fd_set rfds;
    360. FD_ZERO(&rfds);
    361. FD_SET(0, &rfds);
    362. tv.tv_sec = 0;
    363. tv.tv_usec = 0;
    364. n = select(1, &rfds, NULL, NULL, &tv);
    365. if (n > 0) {
    366. n = read(0, &ch, 1);
    367. if (n == 1)
    368. return ch;
    369. return n;
    370. }
    371. #elif HAVE_KBHIT
    372. # if HAVE_PEEKNAMEDPIPE
    373. static int is_pipe;
    374. static HANDLE input_handle;
    375. DWORD dw, nchars;
    376. if(!input_handle){
    377. input_handle = GetStdHandle(STD_INPUT_HANDLE);
    378. is_pipe = !GetConsoleMode(input_handle, &dw);
    379. }
    380. if (is_pipe) {
    381. /* When running under a GUI, you will end here. */
    382. if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
    383. // input pipe may have been closed by the program that ran ffmpeg
    384. return -1;
    385. }
    386. //Read it
    387. if(nchars != 0) {
    388. read(0, &ch, 1);
    389. return ch;
    390. }else{
    391. return -1;
    392. }
    393. }
    394. # endif
    395. if(kbhit())
    396. return(getch());
    397. #endif
    398. return -1;
    399. }
    400. static int decode_interrupt_cb(void *ctx)
    401. {
    402. return received_nb_signals > atomic_load(&transcode_init_done);
    403. }
    404. const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
    405. static void ffmpeg_cleanup(int ret)
    406. {
    407. int i, j;
    408. if (do_benchmark) {
    409. int maxrss = getmaxrss() / 1024;
    410. av_log(NULL, AV_LOG_INFO, "bench: maxrss=%ikB\n", maxrss);
    411. }
    412. for (i = 0; i < nb_filtergraphs; i++) {
    413. FilterGraph *fg = filtergraphs[i];
    414. avfilter_graph_free(&fg->graph);
    415. for (j = 0; j < fg->nb_inputs; j++) {
    416. while (av_fifo_size(fg->inputs[j]->frame_queue)) {
    417. AVFrame *frame;
    418. av_fifo_generic_read(fg->inputs[j]->frame_queue, &frame,
    419. sizeof(frame), NULL);
    420. av_frame_free(&frame);
    421. }
    422. av_fifo_free(fg->inputs[j]->frame_queue);
    423. if (fg->inputs[j]->ist->sub2video.sub_queue) {
    424. while (av_fifo_size(fg->inputs[j]->ist->sub2video.sub_queue)) {
    425. AVSubtitle sub;
    426. av_fifo_generic_read(fg->inputs[j]->ist->sub2video.sub_queue,
    427. &sub, sizeof(sub), NULL);
    428. avsubtitle_free(&sub);
    429. }
    430. av_fifo_free(fg->inputs[j]->ist->sub2video.sub_queue);
    431. }
    432. av_buffer_unref(&fg->inputs[j]->hw_frames_ctx);
    433. av_freep(&fg->inputs[j]->name);
    434. av_freep(&fg->inputs[j]);
    435. }
    436. av_freep(&fg->inputs);
    437. for (j = 0; j < fg->nb_outputs; j++) {
    438. av_freep(&fg->outputs[j]->name);
    439. av_freep(&fg->outputs[j]->formats);
    440. av_freep(&fg->outputs[j]->channel_layouts);
    441. av_freep(&fg->outputs[j]->sample_rates);
    442. av_freep(&fg->outputs[j]);
    443. }
    444. av_freep(&fg->outputs);
    445. av_freep(&fg->graph_desc);
    446. av_freep(&filtergraphs[i]);
    447. }
    448. av_freep(&filtergraphs);
    449. av_freep(&subtitle_out);
    450. /* close files */
    451. for (i = 0; i < nb_output_files; i++) {
    452. OutputFile *of = output_files[i];
    453. AVFormatContext *s;
    454. if (!of)
    455. continue;
    456. s = of->ctx;
    457. if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE))
    458. avio_closep(&s->pb);
    459. avformat_free_context(s);
    460. av_dict_free(&of->opts);
    461. av_freep(&output_files[i]);
    462. }
    463. for (i = 0; i < nb_output_streams; i++) {
    464. OutputStream *ost = output_streams[i];
    465. if (!ost)
    466. continue;
    467. for (j = 0; j < ost->nb_bitstream_filters; j++)
    468. av_bsf_free(&ost->bsf_ctx[j]);
    469. av_freep(&ost->bsf_ctx);
    470. av_freep(&ost->bsf_extradata_updated);
    471. av_frame_free(&ost->filtered_frame);
    472. av_frame_free(&ost->last_frame);
    473. av_dict_free(&ost->encoder_opts);
    474. av_parser_close(ost->parser);
    475. avcodec_free_context(&ost->parser_avctx);
    476. av_freep(&ost->forced_keyframes);
    477. av_expr_free(ost->forced_keyframes_pexpr);
    478. av_freep(&ost->avfilter);
    479. av_freep(&ost->logfile_prefix);
    480. av_freep(&ost->audio_channels_map);
    481. ost->audio_channels_mapped = 0;
    482. av_dict_free(&ost->sws_dict);
    483. avcodec_free_context(&ost->enc_ctx);
    484. avcodec_parameters_free(&ost->ref_par);
    485. if (ost->muxing_queue) {
    486. while (av_fifo_size(ost->muxing_queue)) {
    487. AVPacket pkt;
    488. av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
    489. av_packet_unref(&pkt);
    490. }
    491. av_fifo_freep(&ost->muxing_queue);
    492. }
    493. av_freep(&output_streams[i]);
    494. }
    495. #if HAVE_PTHREADS
    496. free_input_threads();
    497. #endif
    498. for (i = 0; i < nb_input_files; i++) {
    499. avformat_close_input(&input_files[i]->ctx);
    500. av_freep(&input_files[i]);
    501. }
    502. for (i = 0; i < nb_input_streams; i++) {
    503. InputStream *ist = input_streams[i];
    504. av_frame_free(&ist->decoded_frame);
    505. av_frame_free(&ist->filter_frame);
    506. av_dict_free(&ist->decoder_opts);
    507. avsubtitle_free(&ist->prev_sub.subtitle);
    508. av_frame_free(&ist->sub2video.frame);
    509. av_freep(&ist->filters);
    510. av_freep(&ist->hwaccel_device);
    511. av_freep(&ist->dts_buffer);
    512. avcodec_free_context(&ist->dec_ctx);
    513. av_freep(&input_streams[i]);
    514. }
    515. if (vstats_file) {
    516. if (fclose(vstats_file))
    517. av_log(NULL, AV_LOG_ERROR,
    518. "Error closing vstats file, loss of information possible: %s\n",
    519. av_err2str(AVERROR(errno)));
    520. }
    521. av_freep(&vstats_filename);
    522. av_freep(&input_streams);
    523. av_freep(&input_files);
    524. av_freep(&output_streams);
    525. av_freep(&output_files);
    526. uninit_opts();
    527. avformat_network_deinit();
    528. if (received_sigterm) {
    529. av_log(NULL, AV_LOG_INFO, "Exiting normally, received signal %d.\n",
    530. (int) received_sigterm);
    531. } else if (ret && atomic_load(&transcode_init_done)) {
    532. av_log(NULL, AV_LOG_INFO, "Conversion failed!\n");
    533. }
    534. term_exit();
    535. ffmpeg_exited = 1;
    536. }
    537. void remove_avoptions(AVDictionary **a, AVDictionary *b)
    538. {
    539. AVDictionaryEntry *t = NULL;
    540. while ((t = av_dict_get(b, "", t, AV_DICT_IGNORE_SUFFIX))) {
    541. av_dict_set(a, t->key, NULL, AV_DICT_MATCH_CASE);
    542. }
    543. }
    544. void assert_avoptions(AVDictionary *m)
    545. {
    546. AVDictionaryEntry *t;
    547. if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
    548. av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
    549. exit_program(1);
    550. }
    551. }
    552. static void abort_codec_experimental(AVCodec *c, int encoder)
    553. {
    554. exit_program(1);
    555. }
    556. static void update_benchmark(const char *fmt, ...)
    557. {
    558. if (do_benchmark_all) {
    559. int64_t t = getutime();
    560. va_list va;
    561. char buf[1024];
    562. if (fmt) {
    563. va_start(va, fmt);
    564. vsnprintf(buf, sizeof(buf), fmt, va);
    565. va_end(va);
    566. av_log(NULL, AV_LOG_INFO, "bench: %8"PRIu64" %s \n", t - current_time, buf);
    567. }
    568. current_time = t;
    569. }
    570. }
    571. static void close_all_output_streams(OutputStream *ost, OSTFinished this_stream, OSTFinished others)
    572. {
    573. int i;
    574. for (i = 0; i < nb_output_streams; i++) {
    575. OutputStream *ost2 = output_streams[i];
    576. ost2->finished |= ost == ost2 ? this_stream : others;
    577. }
    578. }
    579. static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int unqueue)
    580. {
    581. AVFormatContext *s = of->ctx;
    582. AVStream *st = ost->st;
    583. int ret;
    584. /*
    585. * Audio encoders may split the packets -- #frames in != #packets out.
    586. * But there is no reordering, so we can limit the number of output packets
    587. * by simply dropping them here.
    588. * Counting encoded video frames needs to be done separately because of
    589. * reordering, see do_video_out().
    590. * Do not count the packet when unqueued because it has been counted when queued.
    591. */
    592. if (!(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->encoding_needed) && !unqueue) {
    593. if (ost->frame_number >= ost->max_frames) {
    594. av_packet_unref(pkt);
    595. return;
    596. }
    597. ost->frame_number++;
    598. }
    599. if (!of->header_written) {
    600. AVPacket tmp_pkt = {0};
    601. /* the muxer is not initialized yet, buffer the packet */
    602. if (!av_fifo_space(ost->muxing_queue)) {
    603. int new_size = FFMIN(2 * av_fifo_size(ost->muxing_queue),
    604. ost->max_muxing_queue_size);
    605. if (new_size <= av_fifo_size(ost->muxing_queue)) {
    606. av_log(NULL, AV_LOG_ERROR,
    607. "Too many packets buffered for output stream %d:%d.\n",
    608. ost->file_index, ost->st->index);
    609. exit_program(1);
    610. }
    611. ret = av_fifo_realloc2(ost->muxing_queue, new_size);
    612. if (ret < 0)
    613. exit_program(1);
    614. }
    615. ret = av_packet_ref(&tmp_pkt, pkt);
    616. if (ret < 0)
    617. exit_program(1);
    618. av_fifo_generic_write(ost->muxing_queue, &tmp_pkt, sizeof(tmp_pkt), NULL);
    619. av_packet_unref(pkt);
    620. return;
    621. }
    622. if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
    623. (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
    624. pkt->pts = pkt->dts = AV_NOPTS_VALUE;
    625. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
    626. int i;
    627. uint8_t *sd = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_STATS,
    628. NULL);
    629. ost->quality = sd ? AV_RL32(sd) : -1;
    630. ost->pict_type = sd ? sd[4] : AV_PICTURE_TYPE_NONE;
    631. for (i = 0; i<FF_ARRAY_ELEMS(ost->error); i++) {
    632. if (sd && i < sd[5])
    633. ost->error[i] = AV_RL64(sd + 8 + 8*i);
    634. else
    635. ost->error[i] = -1;
    636. }
    637. if (ost->frame_rate.num && ost->is_cfr) {
    638. if (pkt->duration > 0)
    639. av_log(NULL, AV_LOG_WARNING, "Overriding packet duration by frame rate, this should not happen\n");
    640. pkt->duration = av_rescale_q(1, av_inv_q(ost->frame_rate),
    641. ost->mux_timebase);
    642. }
    643. }
    644. av_packet_rescale_ts(pkt, ost->mux_timebase, ost->st->time_base);
    645. if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
    646. if (pkt->dts != AV_NOPTS_VALUE &&
    647. pkt->pts != AV_NOPTS_VALUE &&
    648. pkt->dts > pkt->pts) {
    649. av_log(s, AV_LOG_WARNING, "Invalid DTS: %"PRId64" PTS: %"PRId64" in output stream %d:%d, replacing by guess\n",
    650. pkt->dts, pkt->pts,
    651. ost->file_index, ost->st->index);
    652. pkt->pts =
    653. pkt->dts = pkt->pts + pkt->dts + ost->last_mux_dts + 1
    654. - FFMIN3(pkt->pts, pkt->dts, ost->last_mux_dts + 1)
    655. - FFMAX3(pkt->pts, pkt->dts, ost->last_mux_dts + 1);
    656. }
    657. if ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
    658. pkt->dts != AV_NOPTS_VALUE &&
    659. !(st->codecpar->codec_id == AV_CODEC_ID_VP9 && ost->stream_copy) &&
    660. ost->last_mux_dts != AV_NOPTS_VALUE) {
    661. int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
    662. if (pkt->dts < max) {
    663. int loglevel = max - pkt->dts > 2 || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
    664. av_log(s, loglevel, "Non-monotonous DTS in output stream "
    665. "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
    666. ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
    667. if (exit_on_error) {
    668. av_log(NULL, AV_LOG_FATAL, "aborting.\n");
    669. exit_program(1);
    670. }
    671. av_log(s, loglevel, "changing to %"PRId64". This may result "
    672. "in incorrect timestamps in the output file.\n",
    673. max);
    674. if (pkt->pts >= pkt->dts)
    675. pkt->pts = FFMAX(pkt->pts, max);
    676. pkt->dts = max;
    677. }
    678. }
    679. }
    680. ost->last_mux_dts = pkt->dts;
    681. ost->data_size += pkt->size;
    682. ost->packets_written++;
    683. pkt->stream_index = ost->index;
    684. if (debug_ts) {
    685. av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
    686. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
    687. av_get_media_type_string(ost->enc_ctx->codec_type),
    688. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
    689. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
    690. pkt->size
    691. );
    692. }
    693. ret = av_interleaved_write_frame(s, pkt);
    694. if (ret < 0) {
    695. print_error("av_interleaved_write_frame()", ret);
    696. main_return_code = 1;
    697. close_all_output_streams(ost, MUXER_FINISHED | ENCODER_FINISHED, ENCODER_FINISHED);
    698. }
    699. av_packet_unref(pkt);
    700. }
    701. static void close_output_stream(OutputStream *ost)
    702. {
    703. OutputFile *of = output_files[ost->file_index];
    704. ost->finished |= ENCODER_FINISHED;
    705. if (of->shortest) {
    706. int64_t end = av_rescale_q(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, AV_TIME_BASE_Q);
    707. of->recording_time = FFMIN(of->recording_time, end);
    708. }
    709. }
    710. static void output_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost)
    711. {
    712. int ret = 0;
    713. /* apply the output bitstream filters, if any */
    714. if (ost->nb_bitstream_filters) {
    715. int idx;
    716. ret = av_bsf_send_packet(ost->bsf_ctx[0], pkt);
    717. if (ret < 0)
    718. goto finish;
    719. idx = 1;
    720. while (idx) {
    721. /* get a packet from the previous filter up the chain */
    722. ret = av_bsf_receive_packet(ost->bsf_ctx[idx - 1], pkt);
    723. if (ret == AVERROR(EAGAIN)) {
    724. ret = 0;
    725. idx--;
    726. continue;
    727. } else if (ret < 0)
    728. goto finish;
    729. /* HACK! - aac_adtstoasc updates extradata after filtering the first frame when
    730. * the api states this shouldn't happen after init(). Propagate it here to the
    731. * muxer and to the next filters in the chain to workaround this.
    732. * TODO/FIXME - Make aac_adtstoasc use new packet side data instead of changing
    733. * par_out->extradata and adapt muxers accordingly to get rid of this. */
    734. if (!(ost->bsf_extradata_updated[idx - 1] & 1)) {
    735. ret = avcodec_parameters_copy(ost->st->codecpar, ost->bsf_ctx[idx - 1]->par_out);
    736. if (ret < 0)
    737. goto finish;
    738. ost->bsf_extradata_updated[idx - 1] |= 1;
    739. }
    740. /* send it to the next filter down the chain or to the muxer */
    741. if (idx < ost->nb_bitstream_filters) {
    742. /* HACK/FIXME! - See above */
    743. if (!(ost->bsf_extradata_updated[idx] & 2)) {
    744. ret = avcodec_parameters_copy(ost->bsf_ctx[idx]->par_out, ost->bsf_ctx[idx - 1]->par_out);
    745. if (ret < 0)
    746. goto finish;
    747. ost->bsf_extradata_updated[idx] |= 2;
    748. }
    749. ret = av_bsf_send_packet(ost->bsf_ctx[idx], pkt);
    750. if (ret < 0)
    751. goto finish;
    752. idx++;
    753. } else
    754. write_packet(of, pkt, ost, 0);
    755. }
    756. } else
    757. write_packet(of, pkt, ost, 0);
    758. finish:
    759. if (ret < 0 && ret != AVERROR_EOF) {
    760. av_log(NULL, AV_LOG_ERROR, "Error applying bitstream filters to an output "
    761. "packet for stream #%d:%d.\n", ost->file_index, ost->index);
    762. if(exit_on_error)
    763. exit_program(1);
    764. }
    765. }
    766. static int check_recording_time(OutputStream *ost)
    767. {
    768. OutputFile *of = output_files[ost->file_index];
    769. if (of->recording_time != INT64_MAX &&
    770. av_compare_ts(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, of->recording_time,
    771. AV_TIME_BASE_Q) >= 0) {
    772. close_output_stream(ost);
    773. return 0;
    774. }
    775. return 1;
    776. }
    777. static void do_audio_out(OutputFile *of, OutputStream *ost,
    778. AVFrame *frame)
    779. {
    780. AVCodecContext *enc = ost->enc_ctx;
    781. AVPacket pkt;
    782. int ret;
    783. av_init_packet(&pkt);
    784. pkt.data = NULL;
    785. pkt.size = 0;
    786. if (!check_recording_time(ost))
    787. return;
    788. if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
    789. frame->pts = ost->sync_opts;
    790. ost->sync_opts = frame->pts + frame->nb_samples;
    791. ost->samples_encoded += frame->nb_samples;
    792. ost->frames_encoded++;
    793. av_assert0(pkt.size || !pkt.data);
    794. update_benchmark(NULL);
    795. if (debug_ts) {
    796. av_log(NULL, AV_LOG_INFO, "encoder <- type:audio "
    797. "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
    798. av_ts2str(frame->pts), av_ts2timestr(frame->pts, &enc->time_base),
    799. enc->time_base.num, enc->time_base.den);
    800. }
    801. ret = avcodec_send_frame(enc, frame);
    802. if (ret < 0)
    803. goto error;
    804. while (1) {
    805. ret = avcodec_receive_packet(enc, &pkt);
    806. if (ret == AVERROR(EAGAIN))
    807. break;
    808. if (ret < 0)
    809. goto error;
    810. update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
    811. av_packet_rescale_ts(&pkt, enc->time_base, ost->mux_timebase);
    812. if (debug_ts) {
    813. av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
    814. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
    815. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &enc->time_base),
    816. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &enc->time_base));
    817. }
    818. output_packet(of, &pkt, ost);
    819. }
    820. return;
    821. error:
    822. av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
    823. exit_program(1);
    824. }
    825. static void do_subtitle_out(OutputFile *of,
    826. OutputStream *ost,
    827. AVSubtitle *sub)
    828. {
    829. int subtitle_out_max_size = 1024 * 1024;
    830. int subtitle_out_size, nb, i;
    831. AVCodecContext *enc;
    832. AVPacket pkt;
    833. int64_t pts;
    834. if (sub->pts == AV_NOPTS_VALUE) {
    835. av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
    836. if (exit_on_error)
    837. exit_program(1);
    838. return;
    839. }
    840. enc = ost->enc_ctx;
    841. if (!subtitle_out) {
    842. subtitle_out = av_malloc(subtitle_out_max_size);
    843. if (!subtitle_out) {
    844. av_log(NULL, AV_LOG_FATAL, "Failed to allocate subtitle_out\n");
    845. exit_program(1);
    846. }
    847. }
    848. /* Note: DVB subtitle need one packet to draw them and one other
    849. packet to clear them */
    850. /* XXX: signal it in the codec context ? */
    851. if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
    852. nb = 2;
    853. else
    854. nb = 1;
    855. /* shift timestamp to honor -ss and make check_recording_time() work with -t */
    856. pts = sub->pts;
    857. if (output_files[ost->file_index]->start_time != AV_NOPTS_VALUE)
    858. pts -= output_files[ost->file_index]->start_time;
    859. for (i = 0; i < nb; i++) {
    860. unsigned save_num_rects = sub->num_rects;
    861. ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
    862. if (!check_recording_time(ost))
    863. return;
    864. sub->pts = pts;
    865. // start_display_time is required to be 0
    866. sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
    867. sub->end_display_time -= sub->start_display_time;
    868. sub->start_display_time = 0;
    869. if (i == 1)
    870. sub->num_rects = 0;
    871. ost->frames_encoded++;
    872. subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
    873. subtitle_out_max_size, sub);
    874. if (i == 1)
    875. sub->num_rects = save_num_rects;
    876. if (subtitle_out_size < 0) {
    877. av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
    878. exit_program(1);
    879. }
    880. av_init_packet(&pkt);
    881. pkt.data = subtitle_out;
    882. pkt.size = subtitle_out_size;
    883. pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->mux_timebase);
    884. pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->mux_timebase);
    885. if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
    886. /* XXX: the pts correction is handled here. Maybe handling
    887. it in the codec would be better */
    888. if (i == 0)
    889. pkt.pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, ost->mux_timebase);
    890. else
    891. pkt.pts += av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->mux_timebase);
    892. }
    893. pkt.dts = pkt.pts;
    894. output_packet(of, &pkt, ost);
    895. }
    896. }
    897. static void do_video_out(OutputFile *of,
    898. OutputStream *ost,
    899. AVFrame *next_picture,
    900. double sync_ipts)
    901. {
    902. int ret, format_video_sync;
    903. AVPacket pkt;
    904. AVCodecContext *enc = ost->enc_ctx;
    905. AVCodecParameters *mux_par = ost->st->codecpar;
    906. AVRational frame_rate;
    907. int nb_frames, nb0_frames, i;
    908. double delta, delta0;
    909. double duration = 0;
    910. int frame_size = 0;
    911. InputStream *ist = NULL;
    912. AVFilterContext *filter = ost->filter->filter;
    913. if (ost->source_index >= 0)
    914. ist = input_streams[ost->source_index];
    915. frame_rate = av_buffersink_get_frame_rate(filter);
    916. if (frame_rate.num > 0 && frame_rate.den > 0)
    917. duration = 1/(av_q2d(frame_rate) * av_q2d(enc->time_base));
    918. if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
    919. duration = FFMIN(duration, 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base)));
    920. if (!ost->filters_script &&
    921. !ost->filters &&
    922. next_picture &&
    923. ist &&
    924. lrintf(av_frame_get_pkt_duration(next_picture) * av_q2d(ist->st->time_base) / av_q2d(enc->time_base)) > 0) {
    925. duration = lrintf(av_frame_get_pkt_duration(next_picture) * av_q2d(ist->st->time_base) / av_q2d(enc->time_base));
    926. }
    927. if (!next_picture) {
    928. //end, flushing
    929. nb0_frames = nb_frames = mid_pred(ost->last_nb0_frames[0],
    930. ost->last_nb0_frames[1],
    931. ost->last_nb0_frames[2]);
    932. } else {
    933. delta0 = sync_ipts - ost->sync_opts; // delta0 is the "drift" between the input frame (next_picture) and where it would fall in the output.
    934. delta = delta0 + duration;
    935. /* by default, we output a single frame */
    936. nb0_frames = 0; // tracks the number of times the PREVIOUS frame should be duplicated, mostly for variable framerate (VFR)
    937. nb_frames = 1;
    938. format_video_sync = video_sync_method;
    939. if (format_video_sync == VSYNC_AUTO) {
    940. if(!strcmp(of->ctx->oformat->name, "avi")) {
    941. format_video_sync = VSYNC_VFR;
    942. } else
    943. format_video_sync = (of->ctx->oformat->flags & AVFMT_VARIABLE_FPS) ? ((of->ctx->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : VSYNC_CFR;
    944. if ( ist
    945. && format_video_sync == VSYNC_CFR
    946. && input_files[ist->file_index]->ctx->nb_streams == 1
    947. && input_files[ist->file_index]->input_ts_offset == 0) {
    948. format_video_sync = VSYNC_VSCFR;
    949. }
    950. if (format_video_sync == VSYNC_CFR && copy_ts) {
    951. format_video_sync = VSYNC_VSCFR;
    952. }
    953. }
    954. ost->is_cfr = (format_video_sync == VSYNC_CFR || format_video_sync == VSYNC_VSCFR);
    955. if (delta0 < 0 &&
    956. delta > 0 &&
    957. format_video_sync != VSYNC_PASSTHROUGH &&
    958. format_video_sync != VSYNC_DROP) {
    959. if (delta0 < -0.6) {
    960. av_log(NULL, AV_LOG_WARNING, "Past duration %f too large\n", -delta0);
    961. } else
    962. av_log(NULL, AV_LOG_DEBUG, "Clipping frame in rate conversion by %f\n", -delta0);
    963. sync_ipts = ost->sync_opts;
    964. duration += delta0;
    965. delta0 = 0;
    966. }
    967. switch (format_video_sync) {
    968. case VSYNC_VSCFR:
    969. if (ost->frame_number == 0 && delta0 >= 0.5) {
    970. av_log(NULL, AV_LOG_DEBUG, "Not duplicating %d initial frames\n", (int)lrintf(delta0));
    971. delta = duration;
    972. delta0 = 0;
    973. ost->sync_opts = lrint(sync_ipts);
    974. }
    975. case VSYNC_CFR:
    976. // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
    977. if (frame_drop_threshold && delta < frame_drop_threshold && ost->frame_number) {
    978. nb_frames = 0;
    979. } else if (delta < -1.1)
    980. nb_frames = 0;
    981. else if (delta > 1.1) {
    982. nb_frames = lrintf(delta);
    983. if (delta0 > 1.1)
    984. nb0_frames = lrintf(delta0 - 0.6);
    985. }
    986. break;
    987. case VSYNC_VFR:
    988. if (delta <= -0.6)
    989. nb_frames = 0;
    990. else if (delta > 0.6)
    991. ost->sync_opts = lrint(sync_ipts);
    992. break;
    993. case VSYNC_DROP:
    994. case VSYNC_PASSTHROUGH:
    995. ost->sync_opts = lrint(sync_ipts);
    996. break;
    997. default:
    998. av_assert0(0);
    999. }
    1000. }
    1001. nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
    1002. nb0_frames = FFMIN(nb0_frames, nb_frames);
    1003. memmove(ost->last_nb0_frames + 1,
    1004. ost->last_nb0_frames,
    1005. sizeof(ost->last_nb0_frames[0]) * (FF_ARRAY_ELEMS(ost->last_nb0_frames) - 1));
    1006. ost->last_nb0_frames[0] = nb0_frames;
    1007. if (nb0_frames == 0 && ost->last_dropped) {
    1008. nb_frames_drop++;
    1009. av_log(NULL, AV_LOG_VERBOSE,
    1010. "*** dropping frame %d from stream %d at ts %"PRId64"\n",
    1011. ost->frame_number, ost->st->index, ost->last_frame->pts);
    1012. }
    1013. if (nb_frames > (nb0_frames && ost->last_dropped) + (nb_frames > nb0_frames)) {
    1014. if (nb_frames > dts_error_threshold * 30) {
    1015. av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);
    1016. nb_frames_drop++;
    1017. return;
    1018. }
    1019. nb_frames_dup += nb_frames - (nb0_frames && ost->last_dropped) - (nb_frames > nb0_frames);
    1020. av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
    1021. if (nb_frames_dup > dup_warning) {
    1022. av_log(NULL, AV_LOG_WARNING, "More than %d frames duplicated\n", dup_warning);
    1023. dup_warning *= 10;
    1024. }
    1025. }
    1026. ost->last_dropped = nb_frames == nb0_frames && next_picture;
    1027. /* duplicates frame if needed */
    1028. for (i = 0; i < nb_frames; i++) {
    1029. AVFrame *in_picture;
    1030. av_init_packet(&pkt);
    1031. pkt.data = NULL;
    1032. pkt.size = 0;
    1033. if (i < nb0_frames && ost->last_frame) {
    1034. in_picture = ost->last_frame;
    1035. } else
    1036. in_picture = next_picture;
    1037. if (!in_picture)
    1038. return;
    1039. in_picture->pts = ost->sync_opts;
    1040. #if 1
    1041. if (!check_recording_time(ost))
    1042. #else
    1043. if (ost->frame_number >= ost->max_frames)
    1044. #endif
    1045. return;
    1046. #if FF_API_LAVF_FMT_RAWPICTURE
    1047. if (of->ctx->oformat->flags & AVFMT_RAWPICTURE &&
    1048. enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
    1049. /* raw pictures are written as AVPicture structure to
    1050. avoid any copies. We support temporarily the older
    1051. method. */
    1052. if (in_picture->interlaced_frame)
    1053. mux_par->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
    1054. else
    1055. mux_par->field_order = AV_FIELD_PROGRESSIVE;
    1056. pkt.data = (uint8_t *)in_picture;
    1057. pkt.size = sizeof(AVPicture);
    1058. pkt.pts = av_rescale_q(in_picture->pts, enc->time_base, ost->mux_timebase);
    1059. pkt.flags |= AV_PKT_FLAG_KEY;
    1060. output_packet(of, &pkt, ost);
    1061. } else
    1062. #endif
    1063. {
    1064. int forced_keyframe = 0;
    1065. double pts_time;
    1066. if (enc->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME) &&
    1067. ost->top_field_first >= 0)
    1068. in_picture->top_field_first = !!ost->top_field_first;
    1069. if (in_picture->interlaced_frame) {
    1070. if (enc->codec->id == AV_CODEC_ID_MJPEG)
    1071. mux_par->field_order = in_picture->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
    1072. else
    1073. mux_par->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
    1074. } else
    1075. mux_par->field_order = AV_FIELD_PROGRESSIVE;
    1076. in_picture->quality = enc->global_quality;
    1077. in_picture->pict_type = 0;
    1078. pts_time = in_picture->pts != AV_NOPTS_VALUE ?
    1079. in_picture->pts * av_q2d(enc->time_base) : NAN;
    1080. if (ost->forced_kf_index < ost->forced_kf_count &&
    1081. in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
    1082. ost->forced_kf_index++;
    1083. forced_keyframe = 1;
    1084. } else if (ost->forced_keyframes_pexpr) {
    1085. double res;
    1086. ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;
    1087. res = av_expr_eval(ost->forced_keyframes_pexpr,
    1088. ost->forced_keyframes_expr_const_values, NULL);
    1089. ff_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
    1090. ost->forced_keyframes_expr_const_values[FKF_N],
    1091. ost->forced_keyframes_expr_const_values[FKF_N_FORCED],
    1092. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N],
    1093. ost->forced_keyframes_expr_const_values[FKF_T],
    1094. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T],
    1095. res);
    1096. if (res) {
    1097. forced_keyframe = 1;
    1098. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] =
    1099. ost->forced_keyframes_expr_const_values[FKF_N];
    1100. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] =
    1101. ost->forced_keyframes_expr_const_values[FKF_T];
    1102. ost->forced_keyframes_expr_const_values[FKF_N_FORCED] += 1;
    1103. }
    1104. ost->forced_keyframes_expr_const_values[FKF_N] += 1;
    1105. } else if ( ost->forced_keyframes
    1106. && !strncmp(ost->forced_keyframes, "source", 6)
    1107. && in_picture->key_frame==1) {
    1108. forced_keyframe = 1;
    1109. }
    1110. if (forced_keyframe) {
    1111. in_picture->pict_type = AV_PICTURE_TYPE_I;
    1112. av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
    1113. }
    1114. update_benchmark(NULL);
    1115. if (debug_ts) {
    1116. av_log(NULL, AV_LOG_INFO, "encoder <- type:video "
    1117. "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
    1118. av_ts2str(in_picture->pts), av_ts2timestr(in_picture->pts, &enc->time_base),
    1119. enc->time_base.num, enc->time_base.den);
    1120. }
    1121. ost->frames_encoded++;
    1122. ret = avcodec_send_frame(enc, in_picture);
    1123. if (ret < 0)
    1124. goto error;
    1125. while (1) {
    1126. ret = avcodec_receive_packet(enc, &pkt);
    1127. update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
    1128. if (ret == AVERROR(EAGAIN))
    1129. break;
    1130. if (ret < 0)
    1131. goto error;
    1132. if (debug_ts) {
    1133. av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
    1134. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
    1135. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &enc->time_base),
    1136. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &enc->time_base));
    1137. }
    1138. if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & AV_CODEC_CAP_DELAY))
    1139. pkt.pts = ost->sync_opts;
    1140. av_packet_rescale_ts(&pkt, enc->time_base, ost->mux_timebase);
    1141. if (debug_ts) {
    1142. av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
    1143. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
    1144. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->mux_timebase),
    1145. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->mux_timebase));
    1146. }
    1147. frame_size = pkt.size;
    1148. output_packet(of, &pkt, ost);
    1149. /* if two pass, output log */
    1150. if (ost->logfile && enc->stats_out) {
    1151. fprintf(ost->logfile, "%s", enc->stats_out);
    1152. }
    1153. }
    1154. }
    1155. ost->sync_opts++;
    1156. /*
    1157. * For video, number of frames in == number of packets out.
    1158. * But there may be reordering, so we can't throw away frames on encoder
    1159. * flush, we need to limit them here, before they go into encoder.
    1160. */
    1161. ost->frame_number++;
    1162. if (vstats_filename && frame_size)
    1163. do_video_stats(ost, frame_size);
    1164. }
    1165. if (!ost->last_frame)
    1166. ost->last_frame = av_frame_alloc();
    1167. av_frame_unref(ost->last_frame);
    1168. if (next_picture && ost->last_frame)
    1169. av_frame_ref(ost->last_frame, next_picture);
    1170. else
    1171. av_frame_free(&ost->last_frame);
    1172. return;
    1173. error:
    1174. av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
    1175. exit_program(1);
    1176. }
    1177. static double psnr(double d)
    1178. {
    1179. return -10.0 * log10(d);
    1180. }
    1181. static void do_video_stats(OutputStream *ost, int frame_size)
    1182. {
    1183. AVCodecContext *enc;
    1184. int frame_number;
    1185. double ti1, bitrate, avg_bitrate;
    1186. /* this is executed just the first time do_video_stats is called */
    1187. if (!vstats_file) {
    1188. vstats_file = fopen(vstats_filename, "w");
    1189. if (!vstats_file) {
    1190. perror("fopen");
    1191. exit_program(1);
    1192. }
    1193. }
    1194. enc = ost->enc_ctx;
    1195. if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
    1196. frame_number = ost->st->nb_frames;
    1197. if (vstats_version <= 1) {
    1198. fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number,
    1199. ost->quality / (float)FF_QP2LAMBDA);
    1200. } else {
    1201. fprintf(vstats_file, "out= %2d st= %2d frame= %5d q= %2.1f ", ost->file_index, ost->index, frame_number,
    1202. ost->quality / (float)FF_QP2LAMBDA);
    1203. }
    1204. if (ost->error[0]>=0 && (enc->flags & AV_CODEC_FLAG_PSNR))
    1205. fprintf(vstats_file, "PSNR= %6.2f ", psnr(ost->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
    1206. fprintf(vstats_file,"f_size= %6d ", frame_size);
    1207. /* compute pts value */
    1208. ti1 = av_stream_get_end_pts(ost->st) * av_q2d(ost->st->time_base);
    1209. if (ti1 < 0.01)
    1210. ti1 = 0.01;
    1211. bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
    1212. avg_bitrate = (double)(ost->data_size * 8) / ti1 / 1000.0;
    1213. fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
    1214. (double)ost->data_size / 1024, ti1, bitrate, avg_bitrate);
    1215. fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(ost->pict_type));
    1216. }
    1217. }
    1218. static int init_output_stream(OutputStream *ost, char *error, int error_len);
    1219. static void finish_output_stream(OutputStream *ost)
    1220. {
    1221. OutputFile *of = output_files[ost->file_index];
    1222. int i;
    1223. ost->finished = ENCODER_FINISHED | MUXER_FINISHED;
    1224. if (of->shortest) {
    1225. for (i = 0; i < of->ctx->nb_streams; i++)
    1226. output_streams[of->ost_index + i]->finished = ENCODER_FINISHED | MUXER_FINISHED;
    1227. }
    1228. }
    1229. /**
    1230. * Get and encode new output from any of the filtergraphs, without causing
    1231. * activity.
    1232. *
    1233. * @return 0 for success, <0 for severe errors
    1234. */
    1235. static int reap_filters(int flush)
    1236. {
    1237. AVFrame *filtered_frame = NULL;
    1238. int i;
    1239. /* Reap all buffers present in the buffer sinks */
    1240. for (i = 0; i < nb_output_streams; i++) {
    1241. OutputStream *ost = output_streams[i];
    1242. OutputFile *of = output_files[ost->file_index];
    1243. AVFilterContext *filter;
    1244. AVCodecContext *enc = ost->enc_ctx;
    1245. int ret = 0;
    1246. if (!ost->filter || !ost->filter->graph->graph)
    1247. continue;
    1248. filter = ost->filter->filter;
    1249. if (!ost->initialized) {
    1250. char error[1024] = "";
    1251. ret = init_output_stream(ost, error, sizeof(error));
    1252. if (ret < 0) {
    1253. av_log(NULL, AV_LOG_ERROR, "Error initializing output stream %d:%d -- %s\n",
    1254. ost->file_index, ost->index, error);
    1255. exit_program(1);
    1256. }
    1257. }
    1258. if (!ost->filtered_frame && !(ost->filtered_frame = av_frame_alloc())) {
    1259. return AVERROR(ENOMEM);
    1260. }
    1261. filtered_frame = ost->filtered_frame;
    1262. while (1) {
    1263. double float_pts = AV_NOPTS_VALUE; // this is identical to filtered_frame.pts but with higher precision
    1264. ret = av_buffersink_get_frame_flags(filter, filtered_frame,
    1265. AV_BUFFERSINK_FLAG_NO_REQUEST);
    1266. if (ret < 0) {
    1267. if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
    1268. av_log(NULL, AV_LOG_WARNING,
    1269. "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(ret));
    1270. } else if (flush && ret == AVERROR_EOF) {
    1271. if (av_buffersink_get_type(filter) == AVMEDIA_TYPE_VIDEO)
    1272. do_video_out(of, ost, NULL, AV_NOPTS_VALUE);
    1273. }
    1274. break;
    1275. }
    1276. if (ost->finished) {
    1277. av_frame_unref(filtered_frame);
    1278. continue;
    1279. }
    1280. if (filtered_frame->pts != AV_NOPTS_VALUE) {
    1281. int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
    1282. AVRational filter_tb = av_buffersink_get_time_base(filter);
    1283. AVRational tb = enc->time_base;
    1284. int extra_bits = av_clip(29 - av_log2(tb.den), 0, 16);
    1285. tb.den <<= extra_bits;
    1286. float_pts =
    1287. av_rescale_q(filtered_frame->pts, filter_tb, tb) -
    1288. av_rescale_q(start_time, AV_TIME_BASE_Q, tb);
    1289. float_pts /= 1 << extra_bits;
    1290. // avoid exact midoints to reduce the chance of rounding differences, this can be removed in case the fps code is changed to work with integers
    1291. float_pts += FFSIGN(float_pts) * 1.0 / (1<<17);
    1292. filtered_frame->pts =
    1293. av_rescale_q(filtered_frame->pts, filter_tb, enc->time_base) -
    1294. av_rescale_q(start_time, AV_TIME_BASE_Q, enc->time_base);
    1295. }
    1296. //if (ost->source_index >= 0)
    1297. // *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
    1298. switch (av_buffersink_get_type(filter)) {
    1299. case AVMEDIA_TYPE_VIDEO:
    1300. if (!ost->frame_aspect_ratio.num)
    1301. enc->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
    1302. if (debug_ts) {
    1303. av_log(NULL, AV_LOG_INFO, "filter -> pts:%s pts_time:%s exact:%f time_base:%d/%d\n",
    1304. av_ts2str(filtered_frame->pts), av_ts2timestr(filtered_frame->pts, &enc->time_base),
    1305. float_pts,
    1306. enc->time_base.num, enc->time_base.den);
    1307. }
    1308. do_video_out(of, ost, filtered_frame, float_pts);
    1309. break;
    1310. case AVMEDIA_TYPE_AUDIO:
    1311. if (!(enc->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE) &&
    1312. enc->channels != av_frame_get_channels(filtered_frame)) {
    1313. av_log(NULL, AV_LOG_ERROR,
    1314. "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
    1315. break;
    1316. }
    1317. do_audio_out(of, ost, filtered_frame);
    1318. break;
    1319. default:
    1320. // TODO support subtitle filters
    1321. av_assert0(0);
    1322. }
    1323. av_frame_unref(filtered_frame);
    1324. }
    1325. }
    1326. return 0;
    1327. }
    1328. static void print_final_stats(int64_t total_size)
    1329. {
    1330. uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
    1331. uint64_t subtitle_size = 0;
    1332. uint64_t data_size = 0;
    1333. float percent = -1.0;
    1334. int i, j;
    1335. int pass1_used = 1;
    1336. for (i = 0; i < nb_output_streams; i++) {
    1337. OutputStream *ost = output_streams[i];
    1338. switch (ost->enc_ctx->codec_type) {
    1339. case AVMEDIA_TYPE_VIDEO: video_size += ost->data_size; break;
    1340. case AVMEDIA_TYPE_AUDIO: audio_size += ost->data_size; break;
    1341. case AVMEDIA_TYPE_SUBTITLE: subtitle_size += ost->data_size; break;
    1342. default: other_size += ost->data_size; break;
    1343. }
    1344. extra_size += ost->enc_ctx->extradata_size;
    1345. data_size += ost->data_size;
    1346. if ( (ost->enc_ctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2))
    1347. != AV_CODEC_FLAG_PASS1)
    1348. pass1_used = 0;
    1349. }
    1350. if (data_size && total_size>0 && total_size >= data_size)
    1351. percent = 100.0 * (total_size - data_size) / data_size;
    1352. av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0fkB other streams:%1.0fkB global headers:%1.0fkB muxing overhead: ",
    1353. video_size / 1024.0,
    1354. audio_size / 1024.0,
    1355. subtitle_size / 1024.0,
    1356. other_size / 1024.0,
    1357. extra_size / 1024.0);
    1358. if (percent >= 0.0)
    1359. av_log(NULL, AV_LOG_INFO, "%f%%", percent);
    1360. else
    1361. av_log(NULL, AV_LOG_INFO, "unknown");
    1362. av_log(NULL, AV_LOG_INFO, "\n");
    1363. /* print verbose per-stream stats */
    1364. for (i = 0; i < nb_input_files; i++) {
    1365. InputFile *f = input_files[i];
    1366. uint64_t total_packets = 0, total_size = 0;
    1367. av_log(NULL, AV_LOG_VERBOSE, "Input file #%d (%s):\n",
    1368. i, f->ctx->filename);
    1369. for (j = 0; j < f->nb_streams; j++) {
    1370. InputStream *ist = input_streams[f->ist_index + j];
    1371. enum AVMediaType type = ist->dec_ctx->codec_type;
    1372. total_size += ist->data_size;
    1373. total_packets += ist->nb_packets;
    1374. av_log(NULL, AV_LOG_VERBOSE, " Input stream #%d:%d (%s): ",
    1375. i, j, media_type_string(type));
    1376. av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets read (%"PRIu64" bytes); ",
    1377. ist->nb_packets, ist->data_size);
    1378. if (ist->decoding_needed) {
    1379. av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames decoded",
    1380. ist->frames_decoded);
    1381. if (type == AVMEDIA_TYPE_AUDIO)
    1382. av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ist->samples_decoded);
    1383. av_log(NULL, AV_LOG_VERBOSE, "; ");
    1384. }
    1385. av_log(NULL, AV_LOG_VERBOSE, "\n");
    1386. }
    1387. av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) demuxed\n",
    1388. total_packets, total_size);
    1389. }
    1390. for (i = 0; i < nb_output_files; i++) {
    1391. OutputFile *of = output_files[i];
    1392. uint64_t total_packets = 0, total_size = 0;
    1393. av_log(NULL, AV_LOG_VERBOSE, "Output file #%d (%s):\n",
    1394. i, of->ctx->filename);
    1395. for (j = 0; j < of->ctx->nb_streams; j++) {
    1396. OutputStream *ost = output_streams[of->ost_index + j];
    1397. enum AVMediaType type = ost->enc_ctx->codec_type;
    1398. total_size += ost->data_size;
    1399. total_packets += ost->packets_written;
    1400. av_log(NULL, AV_LOG_VERBOSE, " Output stream #%d:%d (%s): ",
    1401. i, j, media_type_string(type));
    1402. if (ost->encoding_needed) {
    1403. av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames encoded",
    1404. ost->frames_encoded);
    1405. if (type == AVMEDIA_TYPE_AUDIO)
    1406. av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ost->samples_encoded);
    1407. av_log(NULL, AV_LOG_VERBOSE, "; ");
    1408. }
    1409. av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets muxed (%"PRIu64" bytes); ",
    1410. ost->packets_written, ost->data_size);
    1411. av_log(NULL, AV_LOG_VERBOSE, "\n");
    1412. }
    1413. av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) muxed\n",
    1414. total_packets, total_size);
    1415. }
    1416. if(video_size + data_size + audio_size + subtitle_size + extra_size == 0){
    1417. av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded ");
    1418. if (pass1_used) {
    1419. av_log(NULL, AV_LOG_WARNING, "\n");
    1420. } else {
    1421. av_log(NULL, AV_LOG_WARNING, "(check -ss / -t / -frames parameters if used)\n");
    1422. }
    1423. }
    1424. }
    1425. //打印输出信息的方法
    1426. static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time,void(call_back)(int current,int total))
    1427. {
    1428. char buf[1024];
    1429. AVBPrint buf_script;
    1430. OutputStream *ost;
    1431. AVFormatContext *oc;
    1432. int64_t total_size;
    1433. AVCodecContext *enc;
    1434. int frame_number, vid, i;
    1435. double bitrate;
    1436. double speed;
    1437. int64_t pts = INT64_MIN + 1;
    1438. static int64_t last_time = -1;
    1439. static int qp_histogram[52];
    1440. int hours, mins, secs, us;
    1441. int ret;
    1442. float t;
    1443. if (!print_stats && !is_last_report && !progress_avio)
    1444. return;
    1445. if (!is_last_report) {
    1446. if (last_time == -1) {
    1447. last_time = cur_time;
    1448. return;
    1449. }
    1450. if ((cur_time - last_time) < 500000)
    1451. return;
    1452. last_time = cur_time;
    1453. }
    1454. t = (cur_time-timer_start) / 1000000.0;
    1455. oc = output_files[0]->ctx;
    1456. total_size = avio_size(oc->pb);
    1457. if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
    1458. total_size = avio_tell(oc->pb);
    1459. buf[0] = '\0';
    1460. vid = 0;
    1461. av_bprint_init(&buf_script, 0, 1);
    1462. for (i = 0; i < nb_output_streams; i++) {
    1463. float q = -1;
    1464. ost = output_streams[i];
    1465. enc = ost->enc_ctx;
    1466. if (!ost->stream_copy)
    1467. q = ost->quality / (float) FF_QP2LAMBDA;
    1468. if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
    1469. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
    1470. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
    1471. ost->file_index, ost->index, q);
    1472. }
    1473. if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
    1474. float fps;
    1475. frame_number = ost->frame_number;
    1476. fps = t > 1 ? frame_number / t : 0;
    1477. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
    1478. frame_number, fps < 9.95, fps, q);
    1479. av_bprintf(&buf_script, "frame=%d\n", frame_number);
    1480. av_bprintf(&buf_script, "fps=%.1f\n", fps);
    1481. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
    1482. ost->file_index, ost->index, q);
    1483. //__android_log_print(ANDROID_LOG_ERROR,"JNI_TAG","当前压缩帧:%d",frame_number);
    1484. int total_frame_number=input_files[0]->ctx->streams[0]->nb_frames;
    1485. call_back(frame_number,total_frame_number);
    1486. if (is_last_report)
    1487. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
    1488. if (qp_hist) {
    1489. int j;
    1490. int qp = lrintf(q);
    1491. if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
    1492. qp_histogram[qp]++;
    1493. for (j = 0; j < 32; j++)
    1494. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", av_log2(qp_histogram[j] + 1));
    1495. }
    1496. if ((enc->flags & AV_CODEC_FLAG_PSNR) && (ost->pict_type != AV_PICTURE_TYPE_NONE || is_last_report)) {
    1497. int j;
    1498. double error, error_sum = 0;
    1499. double scale, scale_sum = 0;
    1500. double p;
    1501. char type[3] = { 'Y','U','V' };
    1502. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
    1503. for (j = 0; j < 3; j++) {
    1504. if (is_last_report) {
    1505. error = enc->error[j];
    1506. scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
    1507. } else {
    1508. error = ost->error[j];
    1509. scale = enc->width * enc->height * 255.0 * 255.0;
    1510. }
    1511. if (j)
    1512. scale /= 4;
    1513. error_sum += error;
    1514. scale_sum += scale;
    1515. p = psnr(error / scale);
    1516. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);
    1517. av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
    1518. ost->file_index, ost->index, type[j] | 32, p);
    1519. }
    1520. p = psnr(error_sum / scale_sum);
    1521. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
    1522. av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
    1523. ost->file_index, ost->index, p);
    1524. }
    1525. vid = 1;
    1526. }
    1527. /* compute min output value */
    1528. if (av_stream_get_end_pts(ost->st) != AV_NOPTS_VALUE)
    1529. pts = FFMAX(pts, av_rescale_q(av_stream_get_end_pts(ost->st),
    1530. ost->st->time_base, AV_TIME_BASE_Q));
    1531. if (is_last_report)
    1532. nb_frames_drop += ost->last_dropped;
    1533. }
    1534. secs = FFABS(pts) / AV_TIME_BASE;
    1535. us = FFABS(pts) % AV_TIME_BASE;
    1536. mins = secs / 60;
    1537. secs %= 60;
    1538. hours = mins / 60;
    1539. mins %= 60;
    1540. bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
    1541. speed = t != 0.0 ? (double)pts / AV_TIME_BASE / t : -1;
    1542. if (total_size < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
    1543. "size=N/A time=");
    1544. else snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
    1545. "size=%8.0fkB time=", total_size / 1024.0);
    1546. if (pts < 0)
    1547. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "-");
    1548. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
    1549. "%02d:%02d:%02d.%02d ", hours, mins, secs,
    1550. (100 * us) / AV_TIME_BASE);
    1551. if (bitrate < 0) {
    1552. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),"bitrate=N/A");
    1553. av_bprintf(&buf_script, "bitrate=N/A\n");
    1554. }else{
    1555. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),"bitrate=%6.1fkbits/s", bitrate);
    1556. av_bprintf(&buf_script, "bitrate=%6.1fkbits/s\n", bitrate);
    1557. }
    1558. if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
    1559. else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
    1560. av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
    1561. av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
    1562. hours, mins, secs, us);
    1563. if (nb_frames_dup || nb_frames_drop)
    1564. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
    1565. nb_frames_dup, nb_frames_drop);
    1566. av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
    1567. av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
    1568. if (speed < 0) {
    1569. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf)," speed=N/A");
    1570. av_bprintf(&buf_script, "speed=N/A\n");
    1571. } else {
    1572. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf)," speed=%4.3gx", speed);
    1573. av_bprintf(&buf_script, "speed=%4.3gx\n", speed);
    1574. }
    1575. if (print_stats || is_last_report) {
    1576. const char end = is_last_report ? '\n' : '\r';
    1577. if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
    1578. fprintf(stderr, "%s %c", buf, end);
    1579. } else
    1580. av_log(NULL, AV_LOG_INFO, "%s %c", buf, end);
    1581. fflush(stderr);
    1582. }
    1583. if (progress_avio) {
    1584. av_bprintf(&buf_script, "progress=%s\n",
    1585. is_last_report ? "end" : "continue");
    1586. avio_write(progress_avio, buf_script.str,
    1587. FFMIN(buf_script.len, buf_script.size - 1));
    1588. avio_flush(progress_avio);
    1589. av_bprint_finalize(&buf_script, NULL);
    1590. if (is_last_report) {
    1591. if ((ret = avio_closep(&progress_avio)) < 0)
    1592. av_log(NULL, AV_LOG_ERROR,
    1593. "Error closing progress log, loss of information possible: %s\n", av_err2str(ret));
    1594. }
    1595. }
    1596. if (is_last_report)
    1597. print_final_stats(total_size);
    1598. }
    1599. static void flush_encoders(void)
    1600. {
    1601. int i, ret;
    1602. for (i = 0; i < nb_output_streams; i++) {
    1603. OutputStream *ost = output_streams[i];
    1604. AVCodecContext *enc = ost->enc_ctx;
    1605. OutputFile *of = output_files[ost->file_index];
    1606. if (!ost->encoding_needed)
    1607. continue;
    1608. // Try to enable encoding with no input frames.
    1609. // Maybe we should just let encoding fail instead.
    1610. if (!ost->initialized) {
    1611. FilterGraph *fg = ost->filter->graph;
    1612. char error[1024] = "";
    1613. av_log(NULL, AV_LOG_WARNING,
    1614. "Finishing stream %d:%d without any data written to it.\n",
    1615. ost->file_index, ost->st->index);
    1616. if (ost->filter && !fg->graph) {
    1617. int x;
    1618. for (x = 0; x < fg->nb_inputs; x++) {
    1619. InputFilter *ifilter = fg->inputs[x];
    1620. if (ifilter->format < 0) {
    1621. AVCodecParameters *par = ifilter->ist->st->codecpar;
    1622. // We never got any input. Set a fake format, which will
    1623. // come from libavformat.
    1624. ifilter->format = par->format;
    1625. ifilter->sample_rate = par->sample_rate;
    1626. ifilter->channels = par->channels;
    1627. ifilter->channel_layout = par->channel_layout;
    1628. ifilter->width = par->width;
    1629. ifilter->height = par->height;
    1630. ifilter->sample_aspect_ratio = par->sample_aspect_ratio;
    1631. }
    1632. }
    1633. if (!ifilter_has_all_input_formats(fg))
    1634. continue;
    1635. ret = configure_filtergraph(fg);
    1636. if (ret < 0) {
    1637. av_log(NULL, AV_LOG_ERROR, "Error configuring filter graph\n");
    1638. exit_program(1);
    1639. }
    1640. finish_output_stream(ost);
    1641. }
    1642. ret = init_output_stream(ost, error, sizeof(error));
    1643. if (ret < 0) {
    1644. av_log(NULL, AV_LOG_ERROR, "Error initializing output stream %d:%d -- %s\n",
    1645. ost->file_index, ost->index, error);
    1646. exit_program(1);
    1647. }
    1648. }
    1649. if (enc->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
    1650. continue;
    1651. #if FF_API_LAVF_FMT_RAWPICTURE
    1652. if (enc->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
    1653. continue;
    1654. #endif
    1655. if (enc->codec_type != AVMEDIA_TYPE_VIDEO && enc->codec_type != AVMEDIA_TYPE_AUDIO)
    1656. continue;
    1657. for (;;) {
    1658. const char *desc = NULL;
    1659. AVPacket pkt;
    1660. int pkt_size;
    1661. switch (enc->codec_type) {
    1662. case AVMEDIA_TYPE_AUDIO:
    1663. desc = "audio";
    1664. break;
    1665. case AVMEDIA_TYPE_VIDEO:
    1666. desc = "video";
    1667. break;
    1668. default:
    1669. av_assert0(0);
    1670. }
    1671. av_init_packet(&pkt);
    1672. pkt.data = NULL;
    1673. pkt.size = 0;
    1674. update_benchmark(NULL);
    1675. while ((ret = avcodec_receive_packet(enc, &pkt)) == AVERROR(EAGAIN)) {
    1676. ret = avcodec_send_frame(enc, NULL);
    1677. if (ret < 0) {
    1678. av_log(NULL, AV_LOG_FATAL, "%s encoding failed: %s\n",
    1679. desc,
    1680. av_err2str(ret));
    1681. exit_program(1);
    1682. }
    1683. }
    1684. update_benchmark("flush_%s %d.%d", desc, ost->file_index, ost->index);
    1685. if (ret < 0 && ret != AVERROR_EOF) {
    1686. av_log(NULL, AV_LOG_FATAL, "%s encoding failed: %s\n",
    1687. desc,
    1688. av_err2str(ret));
    1689. exit_program(1);
    1690. }
    1691. if (ost->logfile && enc->stats_out) {
    1692. fprintf(ost->logfile, "%s", enc->stats_out);
    1693. }
    1694. if (ret == AVERROR_EOF) {
    1695. break;
    1696. }
    1697. if (ost->finished & MUXER_FINISHED) {
    1698. av_packet_unref(&pkt);
    1699. continue;
    1700. }
    1701. av_packet_rescale_ts(&pkt, enc->time_base, ost->mux_timebase);
    1702. pkt_size = pkt.size;
    1703. output_packet(of, &pkt, ost);
    1704. if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO && vstats_filename) {
    1705. do_video_stats(ost, pkt_size);
    1706. }
    1707. }
    1708. }
    1709. }
    1710. /*
    1711. * Check whether a packet from ist should be written into ost at this time
    1712. */
    1713. static int check_output_constraints(InputStream *ist, OutputStream *ost)
    1714. {
    1715. OutputFile *of = output_files[ost->file_index];
    1716. int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
    1717. if (ost->source_index != ist_index)
    1718. return 0;
    1719. if (ost->finished)
    1720. return 0;
    1721. if (of->start_time != AV_NOPTS_VALUE && ist->pts < of->start_time)
    1722. return 0;
    1723. return 1;
    1724. }
    1725. static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
    1726. {
    1727. OutputFile *of = output_files[ost->file_index];
    1728. InputFile *f = input_files [ist->file_index];
    1729. int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
    1730. int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->mux_timebase);
    1731. AVPicture pict;
    1732. AVPacket opkt;
    1733. av_init_packet(&opkt);
    1734. if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
    1735. !ost->copy_initial_nonkeyframes)
    1736. return;
    1737. if (!ost->frame_number && !ost->copy_prior_start) {
    1738. int64_t comp_start = start_time;
    1739. if (copy_ts && f->start_time != AV_NOPTS_VALUE)
    1740. comp_start = FFMAX(start_time, f->start_time + f->ts_offset);
    1741. if (pkt->pts == AV_NOPTS_VALUE ?
    1742. ist->pts < comp_start :
    1743. pkt->pts < av_rescale_q(comp_start, AV_TIME_BASE_Q, ist->st->time_base))
    1744. return;
    1745. }
    1746. if (of->recording_time != INT64_MAX &&
    1747. ist->pts >= of->recording_time + start_time) {
    1748. close_output_stream(ost);
    1749. return;
    1750. }
    1751. if (f->recording_time != INT64_MAX) {
    1752. start_time = f->ctx->start_time;
    1753. if (f->start_time != AV_NOPTS_VALUE && copy_ts)
    1754. start_time += f->start_time;
    1755. if (ist->pts >= f->recording_time + start_time) {
    1756. close_output_stream(ost);
    1757. return;
    1758. }
    1759. }
    1760. /* force the input stream PTS */
    1761. if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
    1762. ost->sync_opts++;
    1763. if (pkt->pts != AV_NOPTS_VALUE)
    1764. opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->mux_timebase) - ost_tb_start_time;
    1765. else
    1766. opkt.pts = AV_NOPTS_VALUE;
    1767. if (pkt->dts == AV_NOPTS_VALUE)
    1768. opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->mux_timebase);
    1769. else
    1770. opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->mux_timebase);
    1771. opkt.dts -= ost_tb_start_time;
    1772. if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
    1773. int duration = av_get_audio_frame_duration(ist->dec_ctx, pkt->size);
    1774. if(!duration)
    1775. duration = ist->dec_ctx->frame_size;
    1776. opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
    1777. (AVRational){1, ist->dec_ctx->sample_rate}, duration, &ist->filter_in_rescale_delta_last,
    1778. ost->mux_timebase) - ost_tb_start_time;
    1779. }
    1780. opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->mux_timebase);
    1781. opkt.flags = pkt->flags;
    1782. // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
    1783. if ( ost->st->codecpar->codec_id != AV_CODEC_ID_H264
    1784. && ost->st->codecpar->codec_id != AV_CODEC_ID_MPEG1VIDEO
    1785. && ost->st->codecpar->codec_id != AV_CODEC_ID_MPEG2VIDEO
    1786. && ost->st->codecpar->codec_id != AV_CODEC_ID_VC1
    1787. ) {
    1788. int ret = av_parser_change(ost->parser, ost->parser_avctx,
    1789. &opkt.data, &opkt.size,
    1790. pkt->data, pkt->size,
    1791. pkt->flags & AV_PKT_FLAG_KEY);
    1792. if (ret < 0) {
    1793. av_log(NULL, AV_LOG_FATAL, "av_parser_change failed: %s\n",
    1794. av_err2str(ret));
    1795. exit_program(1);
    1796. }
    1797. if (ret) {
    1798. opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
    1799. if (!opkt.buf)
    1800. exit_program(1);
    1801. }
    1802. } else {
    1803. opkt.data = pkt->data;
    1804. opkt.size = pkt->size;
    1805. }
    1806. av_copy_packet_side_data(&opkt, pkt);
    1807. #if FF_API_LAVF_FMT_RAWPICTURE
    1808. if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
    1809. ost->st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO &&
    1810. (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
    1811. /* store AVPicture in AVPacket, as expected by the output format */
    1812. int ret = avpicture_fill(&pict, opkt.data, ost->st->codecpar->format, ost->st->codecpar->width, ost->st->codecpar->height);
    1813. if (ret < 0) {
    1814. av_log(NULL, AV_LOG_FATAL, "avpicture_fill failed: %s\n",
    1815. av_err2str(ret));
    1816. exit_program(1);
    1817. }
    1818. opkt.data = (uint8_t *)&pict;
    1819. opkt.size = sizeof(AVPicture);
    1820. opkt.flags |= AV_PKT_FLAG_KEY;
    1821. }
    1822. #endif
    1823. output_packet(of, &opkt, ost);
    1824. }
    1825. int guess_input_channel_layout(InputStream *ist)
    1826. {
    1827. AVCodecContext *dec = ist->dec_ctx;
    1828. if (!dec->channel_layout) {
    1829. char layout_name[256];
    1830. if (dec->channels > ist->guess_layout_max)
    1831. return 0;
    1832. dec->channel_layout = av_get_default_channel_layout(dec->channels);
    1833. if (!dec->channel_layout)
    1834. return 0;
    1835. av_get_channel_layout_string(layout_name, sizeof(layout_name),
    1836. dec->channels, dec->channel_layout);
    1837. av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
    1838. "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
    1839. }
    1840. return 1;
    1841. }
    1842. static void check_decode_result(InputStream *ist, int *got_output, int ret)
    1843. {
    1844. if (*got_output || ret<0)
    1845. decode_error_stat[ret<0] ++;
    1846. if (ret < 0 && exit_on_error)
    1847. exit_program(1);
    1848. if (exit_on_error && *got_output && ist) {
    1849. if (av_frame_get_decode_error_flags(ist->decoded_frame) || (ist->decoded_frame->flags & AV_FRAME_FLAG_CORRUPT)) {
    1850. av_log(NULL, AV_LOG_FATAL, "%s: corrupt decoded frame in stream %d\n", input_files[ist->file_index]->ctx->filename, ist->st->index);
    1851. exit_program(1);
    1852. }
    1853. }
    1854. }
    1855. // Filters can be configured only if the formats of all inputs are known.
    1856. static int ifilter_has_all_input_formats(FilterGraph *fg)
    1857. {
    1858. int i;
    1859. for (i = 0; i < fg->nb_inputs; i++) {
    1860. if (fg->inputs[i]->format < 0 && (fg->inputs[i]->type == AVMEDIA_TYPE_AUDIO ||
    1861. fg->inputs[i]->type == AVMEDIA_TYPE_VIDEO))
    1862. return 0;
    1863. }
    1864. return 1;
    1865. }
    1866. static int ifilter_send_frame(InputFilter *ifilter, AVFrame *frame)
    1867. {
    1868. FilterGraph *fg = ifilter->graph;
    1869. int need_reinit, ret, i;
    1870. /* determine if the parameters for this input changed */
    1871. need_reinit = ifilter->format != frame->format;
    1872. switch (ifilter->ist->st->codecpar->codec_type) {
    1873. case AVMEDIA_TYPE_AUDIO:
    1874. need_reinit |= ifilter->sample_rate != frame->sample_rate ||
    1875. ifilter->channels != frame->channels ||
    1876. ifilter->channel_layout != frame->channel_layout;
    1877. break;
    1878. case AVMEDIA_TYPE_VIDEO:
    1879. need_reinit |= ifilter->width != frame->width ||
    1880. ifilter->height != frame->height;
    1881. break;
    1882. }
    1883. if (!ifilter->ist->reinit_filters && fg->graph)
    1884. need_reinit = 0;
    1885. if (!!ifilter->hw_frames_ctx != !!frame->hw_frames_ctx ||
    1886. (ifilter->hw_frames_ctx && ifilter->hw_frames_ctx->data != frame->hw_frames_ctx->data))
    1887. need_reinit = 1;
    1888. if (need_reinit) {
    1889. ret = ifilter_parameters_from_frame(ifilter, frame);
    1890. if (ret < 0)
    1891. return ret;
    1892. }
    1893. /* (re)init the graph if possible, otherwise buffer the frame and return */
    1894. if (need_reinit || !fg->graph) {
    1895. for (i = 0; i < fg->nb_inputs; i++) {
    1896. if (!ifilter_has_all_input_formats(fg)) {
    1897. AVFrame *tmp = av_frame_clone(frame);
    1898. if (!tmp)
    1899. return AVERROR(ENOMEM);
    1900. av_frame_unref(frame);
    1901. if (!av_fifo_space(ifilter->frame_queue)) {
    1902. ret = av_fifo_realloc2(ifilter->frame_queue, 2 * av_fifo_size(ifilter->frame_queue));
    1903. if (ret < 0) {
    1904. av_frame_free(&tmp);
    1905. return ret;
    1906. }
    1907. }
    1908. av_fifo_generic_write(ifilter->frame_queue, &tmp, sizeof(tmp), NULL);
    1909. return 0;
    1910. }
    1911. }
    1912. ret = reap_filters(1);
    1913. if (ret < 0 && ret != AVERROR_EOF) {
    1914. char errbuf[128];
    1915. av_strerror(ret, errbuf, sizeof(errbuf));
    1916. av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
    1917. return ret;
    1918. }
    1919. ret = configure_filtergraph(fg);
    1920. if (ret < 0) {
    1921. av_log(NULL, AV_LOG_ERROR, "Error reinitializing filters!\n");
    1922. return ret;
    1923. }
    1924. }
    1925. ret = av_buffersrc_add_frame_flags(ifilter->filter, frame, AV_BUFFERSRC_FLAG_PUSH);
    1926. if (ret < 0) {
    1927. av_log(NULL, AV_LOG_ERROR, "Error while filtering\n");
    1928. return ret;
    1929. }
    1930. return 0;
    1931. }
    1932. static int ifilter_send_eof(InputFilter *ifilter)
    1933. {
    1934. int i, j, ret;
    1935. ifilter->eof = 1;
    1936. if (ifilter->filter) {
    1937. ret = av_buffersrc_add_frame_flags(ifilter->filter, NULL, AV_BUFFERSRC_FLAG_PUSH);
    1938. if (ret < 0)
    1939. return ret;
    1940. } else {
    1941. // the filtergraph was never configured
    1942. FilterGraph *fg = ifilter->graph;
    1943. for (i = 0; i < fg->nb_inputs; i++)
    1944. if (!fg->inputs[i]->eof)
    1945. break;
    1946. if (i == fg->nb_inputs) {
    1947. // All the input streams have finished without the filtergraph
    1948. // ever being configured.
    1949. // Mark the output streams as finished.
    1950. for (j = 0; j < fg->nb_outputs; j++)
    1951. finish_output_stream(fg->outputs[j]->ost);
    1952. }
    1953. }
    1954. return 0;
    1955. }
    1956. // This does not quite work like avcodec_decode_audio4/avcodec_decode_video2.
    1957. // There is the following difference: if you got a frame, you must call
    1958. // it again with pkt=NULL. pkt==NULL is treated differently from pkt.size==0
    1959. // (pkt==NULL means get more output, pkt.size==0 is a flush/drain packet)
    1960. static int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt)
    1961. {
    1962. int ret;
    1963. *got_frame = 0;
    1964. if (pkt) {
    1965. ret = avcodec_send_packet(avctx, pkt);
    1966. // In particular, we don't expect AVERROR(EAGAIN), because we read all
    1967. // decoded frames with avcodec_receive_frame() until done.
    1968. if (ret < 0 && ret != AVERROR_EOF)
    1969. return ret;
    1970. }
    1971. ret = avcodec_receive_frame(avctx, frame);
    1972. if (ret < 0 && ret != AVERROR(EAGAIN))
    1973. return ret;
    1974. if (ret >= 0)
    1975. *got_frame = 1;
    1976. return 0;
    1977. }
    1978. static int send_frame_to_filters(InputStream *ist, AVFrame *decoded_frame)
    1979. {
    1980. int i, ret;
    1981. AVFrame *f;
    1982. av_assert1(ist->nb_filters > 0); /* ensure ret is initialized */
    1983. for (i = 0; i < ist->nb_filters; i++) {
    1984. if (i < ist->nb_filters - 1) {
    1985. f = ist->filter_frame;
    1986. ret = av_frame_ref(f, decoded_frame);
    1987. if (ret < 0)
    1988. break;
    1989. } else
    1990. f = decoded_frame;
    1991. ret = ifilter_send_frame(ist->filters[i], f);
    1992. if (ret == AVERROR_EOF)
    1993. ret = 0; /* ignore */
    1994. if (ret < 0) {
    1995. av_log(NULL, AV_LOG_ERROR,
    1996. "Failed to inject frame into filter network: %s\n", av_err2str(ret));
    1997. break;
    1998. }
    1999. }
    2000. return ret;
    2001. }
    2002. static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output,
    2003. int *decode_failed)
    2004. {
    2005. AVFrame *decoded_frame;
    2006. AVCodecContext *avctx = ist->dec_ctx;
    2007. int ret, err = 0;
    2008. AVRational decoded_frame_tb;
    2009. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
    2010. return AVERROR(ENOMEM);
    2011. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
    2012. return AVERROR(ENOMEM);
    2013. decoded_frame = ist->decoded_frame;
    2014. update_benchmark(NULL);
    2015. ret = decode(avctx, decoded_frame, got_output, pkt);
    2016. update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
    2017. if (ret < 0)
    2018. *decode_failed = 1;
    2019. if (ret >= 0 && avctx->sample_rate <= 0) {
    2020. av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
    2021. ret = AVERROR_INVALIDDATA;
    2022. }
    2023. if (ret != AVERROR_EOF)
    2024. check_decode_result(ist, got_output, ret);
    2025. if (!*got_output || ret < 0)
    2026. return ret;
    2027. ist->samples_decoded += decoded_frame->nb_samples;
    2028. ist->frames_decoded++;
    2029. #if 1
    2030. /* increment next_dts to use for the case where the input stream does not
    2031. have timestamps or there are multiple frames in the packet */
    2032. ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
    2033. avctx->sample_rate;
    2034. ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
    2035. avctx->sample_rate;
    2036. #endif
    2037. if (decoded_frame->pts != AV_NOPTS_VALUE) {
    2038. decoded_frame_tb = ist->st->time_base;
    2039. } else if (pkt && pkt->pts != AV_NOPTS_VALUE) {
    2040. decoded_frame->pts = pkt->pts;
    2041. decoded_frame_tb = ist->st->time_base;
    2042. }else {
    2043. decoded_frame->pts = ist->dts;
    2044. decoded_frame_tb = AV_TIME_BASE_Q;
    2045. }
    2046. if (decoded_frame->pts != AV_NOPTS_VALUE)
    2047. decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
    2048. (AVRational){1, avctx->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
    2049. (AVRational){1, avctx->sample_rate});
    2050. ist->nb_samples = decoded_frame->nb_samples;
    2051. err = send_frame_to_filters(ist, decoded_frame);
    2052. av_frame_unref(ist->filter_frame);
    2053. av_frame_unref(decoded_frame);
    2054. return err < 0 ? err : ret;
    2055. }
    2056. static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output, int eof,
    2057. int *decode_failed)
    2058. {
    2059. AVFrame *decoded_frame;
    2060. int i, ret = 0, err = 0;
    2061. int64_t best_effort_timestamp;
    2062. int64_t dts = AV_NOPTS_VALUE;
    2063. AVPacket avpkt;
    2064. // With fate-indeo3-2, we're getting 0-sized packets before EOF for some
    2065. // reason. This seems like a semi-critical bug. Don't trigger EOF, and
    2066. // skip the packet.
    2067. if (!eof && pkt && pkt->size == 0)
    2068. return 0;
    2069. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
    2070. return AVERROR(ENOMEM);
    2071. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
    2072. return AVERROR(ENOMEM);
    2073. decoded_frame = ist->decoded_frame;
    2074. if (ist->dts != AV_NOPTS_VALUE)
    2075. dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
    2076. if (pkt) {
    2077. avpkt = *pkt;
    2078. avpkt.dts = dts; // ffmpeg.c probably shouldn't do this
    2079. }
    2080. // The old code used to set dts on the drain packet, which does not work
    2081. // with the new API anymore.
    2082. if (eof) {
    2083. void *new = av_realloc_array(ist->dts_buffer, ist->nb_dts_buffer + 1, sizeof(ist->dts_buffer[0]));
    2084. if (!new)
    2085. return AVERROR(ENOMEM);
    2086. ist->dts_buffer = new;
    2087. ist->dts_buffer[ist->nb_dts_buffer++] = dts;
    2088. }
    2089. update_benchmark(NULL);
    2090. ret = decode(ist->dec_ctx, decoded_frame, got_output, pkt ? &avpkt : NULL);
    2091. update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
    2092. if (ret < 0)
    2093. *decode_failed = 1;
    2094. // The following line may be required in some cases where there is no parser
    2095. // or the parser does not has_b_frames correctly
    2096. if (ist->st->codecpar->video_delay < ist->dec_ctx->has_b_frames) {
    2097. if (ist->dec_ctx->codec_id == AV_CODEC_ID_H264) {
    2098. ist->st->codecpar->video_delay = ist->dec_ctx->has_b_frames;
    2099. } else
    2100. av_log(ist->dec_ctx, AV_LOG_WARNING,
    2101. "video_delay is larger in decoder than demuxer %d > %d.\n"
    2102. "If you want to help, upload a sample "
    2103. "of this file to ftp://upload.ffmpeg.org/incoming/ "
    2104. "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)\n",
    2105. ist->dec_ctx->has_b_frames,
    2106. ist->st->codecpar->video_delay);
    2107. }
    2108. if (ret != AVERROR_EOF)
    2109. check_decode_result(ist, got_output, ret);
    2110. if (*got_output && ret >= 0) {
    2111. if (ist->dec_ctx->width != decoded_frame->width ||
    2112. ist->dec_ctx->height != decoded_frame->height ||
    2113. ist->dec_ctx->pix_fmt != decoded_frame->format) {
    2114. av_log(NULL, AV_LOG_DEBUG, "Frame parameters mismatch context %d,%d,%d != %d,%d,%d\n",
    2115. decoded_frame->width,
    2116. decoded_frame->height,
    2117. decoded_frame->format,
    2118. ist->dec_ctx->width,
    2119. ist->dec_ctx->height,
    2120. ist->dec_ctx->pix_fmt);
    2121. }
    2122. }
    2123. if (!*got_output || ret < 0)
    2124. return ret;
    2125. if(ist->top_field_first>=0)
    2126. decoded_frame->top_field_first = ist->top_field_first;
    2127. ist->frames_decoded++;
    2128. if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) {
    2129. err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame);
    2130. if (err < 0)
    2131. goto fail;
    2132. }
    2133. ist->hwaccel_retrieved_pix_fmt = decoded_frame->format;
    2134. best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
    2135. if (ist->framerate.num)
    2136. best_effort_timestamp = ist->cfr_next_pts++;
    2137. if (eof && best_effort_timestamp == AV_NOPTS_VALUE && ist->nb_dts_buffer > 0) {
    2138. best_effort_timestamp = ist->dts_buffer[0];
    2139. for (i = 0; i < ist->nb_dts_buffer - 1; i++)
    2140. ist->dts_buffer[i] = ist->dts_buffer[i + 1];
    2141. ist->nb_dts_buffer--;
    2142. }
    2143. if(best_effort_timestamp != AV_NOPTS_VALUE) {
    2144. int64_t ts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
    2145. if (ts != AV_NOPTS_VALUE)
    2146. ist->next_pts = ist->pts = ts;
    2147. }
    2148. if (debug_ts) {
    2149. av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
    2150. "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d time_base:%d/%d\n",
    2151. ist->st->index, av_ts2str(decoded_frame->pts),
    2152. av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
    2153. best_effort_timestamp,
    2154. av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
    2155. decoded_frame->key_frame, decoded_frame->pict_type,
    2156. ist->st->time_base.num, ist->st->time_base.den);
    2157. }
    2158. if (ist->st->sample_aspect_ratio.num)
    2159. decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
    2160. err = send_frame_to_filters(ist, decoded_frame);
    2161. fail:
    2162. av_frame_unref(ist->filter_frame);
    2163. av_frame_unref(decoded_frame);
    2164. return err < 0 ? err : ret;
    2165. }
    2166. static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output,
    2167. int *decode_failed)
    2168. {
    2169. AVSubtitle subtitle;
    2170. int free_sub = 1;
    2171. int i, ret = avcodec_decode_subtitle2(ist->dec_ctx,
    2172. &subtitle, got_output, pkt);
    2173. check_decode_result(NULL, got_output, ret);
    2174. if (ret < 0 || !*got_output) {
    2175. *decode_failed = 1;
    2176. if (!pkt->size)
    2177. sub2video_flush(ist);
    2178. return ret;
    2179. }
    2180. if (ist->fix_sub_duration) {
    2181. int end = 1;
    2182. if (ist->prev_sub.got_output) {
    2183. end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
    2184. 1000, AV_TIME_BASE);
    2185. if (end < ist->prev_sub.subtitle.end_display_time) {
    2186. av_log(ist->dec_ctx, AV_LOG_DEBUG,
    2187. "Subtitle duration reduced from %"PRId32" to %d%s\n",
    2188. ist->prev_sub.subtitle.end_display_time, end,
    2189. end <= 0 ? ", dropping it" : "");
    2190. ist->prev_sub.subtitle.end_display_time = end;
    2191. }
    2192. }
    2193. FFSWAP(int, *got_output, ist->prev_sub.got_output);
    2194. FFSWAP(int, ret, ist->prev_sub.ret);
    2195. FFSWAP(AVSubtitle, subtitle, ist->prev_sub.subtitle);
    2196. if (end <= 0)
    2197. goto out;
    2198. }
    2199. if (!*got_output)
    2200. return ret;
    2201. if (ist->sub2video.frame) {
    2202. sub2video_update(ist, &subtitle);
    2203. } else if (ist->nb_filters) {
    2204. if (!ist->sub2video.sub_queue)
    2205. ist->sub2video.sub_queue = av_fifo_alloc(8 * sizeof(AVSubtitle));
    2206. if (!ist->sub2video.sub_queue)
    2207. exit_program(1);
    2208. if (!av_fifo_space(ist->sub2video.sub_queue)) {
    2209. ret = av_fifo_realloc2(ist->sub2video.sub_queue, 2 * av_fifo_size(ist->sub2video.sub_queue));
    2210. if (ret < 0)
    2211. exit_program(1);
    2212. }
    2213. av_fifo_generic_write(ist->sub2video.sub_queue, &subtitle, sizeof(subtitle), NULL);
    2214. free_sub = 0;
    2215. }
    2216. if (!subtitle.num_rects)
    2217. goto out;
    2218. ist->frames_decoded++;
    2219. for (i = 0; i < nb_output_streams; i++) {
    2220. OutputStream *ost = output_streams[i];
    2221. if (!check_output_constraints(ist, ost) || !ost->encoding_needed
    2222. || ost->enc->type != AVMEDIA_TYPE_SUBTITLE)
    2223. continue;
    2224. do_subtitle_out(output_files[ost->file_index], ost, &subtitle);
    2225. }
    2226. out:
    2227. if (free_sub)
    2228. avsubtitle_free(&subtitle);
    2229. return ret;
    2230. }
    2231. static int send_filter_eof(InputStream *ist)
    2232. {
    2233. int i, ret;
    2234. for (i = 0; i < ist->nb_filters; i++) {
    2235. ret = ifilter_send_eof(ist->filters[i]);
    2236. if (ret < 0)
    2237. return ret;
    2238. }
    2239. return 0;
    2240. }
    2241. /* pkt = NULL means EOF (needed to flush decoder buffers) */
    2242. static int process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
    2243. {
    2244. int ret = 0, i;
    2245. int repeating = 0;
    2246. int eof_reached = 0;
    2247. AVPacket avpkt;
    2248. if (!ist->saw_first_ts) {
    2249. ist->dts = ist->st->avg_frame_rate.num ? - ist->dec_ctx->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
    2250. ist->pts = 0;
    2251. if (pkt && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
    2252. ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
    2253. ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
    2254. }
    2255. ist->saw_first_ts = 1;
    2256. }
    2257. if (ist->next_dts == AV_NOPTS_VALUE)
    2258. ist->next_dts = ist->dts;
    2259. if (ist->next_pts == AV_NOPTS_VALUE)
    2260. ist->next_pts = ist->pts;
    2261. if (!pkt) {
    2262. /* EOF handling */
    2263. av_init_packet(&avpkt);
    2264. avpkt.data = NULL;
    2265. avpkt.size = 0;
    2266. } else {
    2267. avpkt = *pkt;
    2268. }
    2269. if (pkt && pkt->dts != AV_NOPTS_VALUE) {
    2270. ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
    2271. if (ist->dec_ctx->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
    2272. ist->next_pts = ist->pts = ist->dts;
    2273. }
    2274. // while we have more to decode or while the decoder did output something on EOF
    2275. while (ist->decoding_needed) {
    2276. int duration = 0;
    2277. int got_output = 0;
    2278. int decode_failed = 0;
    2279. ist->pts = ist->next_pts;
    2280. ist->dts = ist->next_dts;
    2281. switch (ist->dec_ctx->codec_type) {
    2282. case AVMEDIA_TYPE_AUDIO:
    2283. ret = decode_audio (ist, repeating ? NULL : &avpkt, &got_output,
    2284. &decode_failed);
    2285. break;
    2286. case AVMEDIA_TYPE_VIDEO:
    2287. ret = decode_video (ist, repeating ? NULL : &avpkt, &got_output, !pkt,
    2288. &decode_failed);
    2289. if (!repeating || !pkt || got_output) {
    2290. if (pkt && pkt->duration) {
    2291. duration = av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
    2292. } else if(ist->dec_ctx->framerate.num != 0 && ist->dec_ctx->framerate.den != 0) {
    2293. int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict+1 : ist->dec_ctx->ticks_per_frame;
    2294. duration = ((int64_t)AV_TIME_BASE *
    2295. ist->dec_ctx->framerate.den * ticks) /
    2296. ist->dec_ctx->framerate.num / ist->dec_ctx->ticks_per_frame;
    2297. }
    2298. if(ist->dts != AV_NOPTS_VALUE && duration) {
    2299. ist->next_dts += duration;
    2300. }else
    2301. ist->next_dts = AV_NOPTS_VALUE;
    2302. }
    2303. if (got_output)
    2304. ist->next_pts += duration; //FIXME the duration is not correct in some cases
    2305. break;
    2306. case AVMEDIA_TYPE_SUBTITLE:
    2307. if (repeating)
    2308. break;
    2309. ret = transcode_subtitles(ist, &avpkt, &got_output, &decode_failed);
    2310. if (!pkt && ret >= 0)
    2311. ret = AVERROR_EOF;
    2312. break;
    2313. default:
    2314. return -1;
    2315. }
    2316. if (ret == AVERROR_EOF) {
    2317. eof_reached = 1;
    2318. break;
    2319. }
    2320. if (ret < 0) {
    2321. if (decode_failed) {
    2322. av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
    2323. ist->file_index, ist->st->index, av_err2str(ret));
    2324. } else {
    2325. av_log(NULL, AV_LOG_FATAL, "Error while processing the decoded "
    2326. "data for stream #%d:%d\n", ist->file_index, ist->st->index);
    2327. }
    2328. if (!decode_failed || exit_on_error)
    2329. exit_program(1);
    2330. break;
    2331. }
    2332. if (got_output)
    2333. ist->got_output = 1;
    2334. if (!got_output)
    2335. break;
    2336. // During draining, we might get multiple output frames in this loop.
    2337. // ffmpeg.c does not drain the filter chain on configuration changes,
    2338. // which means if we send multiple frames at once to the filters, and
    2339. // one of those frames changes configuration, the buffered frames will
    2340. // be lost. This can upset certain FATE tests.
    2341. // Decode only 1 frame per call on EOF to appease these FATE tests.
    2342. // The ideal solution would be to rewrite decoding to use the new
    2343. // decoding API in a better way.
    2344. if (!pkt)
    2345. break;
    2346. repeating = 1;
    2347. }
    2348. /* after flushing, send an EOF on all the filter inputs attached to the stream */
    2349. /* except when looping we need to flush but not to send an EOF */
    2350. if (!pkt && ist->decoding_needed && eof_reached && !no_eof) {
    2351. int ret = send_filter_eof(ist);
    2352. if (ret < 0) {
    2353. av_log(NULL, AV_LOG_FATAL, "Error marking filters as finished\n");
    2354. exit_program(1);
    2355. }
    2356. }
    2357. /* handle stream copy */
    2358. if (!ist->decoding_needed) {
    2359. ist->dts = ist->next_dts;
    2360. switch (ist->dec_ctx->codec_type) {
    2361. case AVMEDIA_TYPE_AUDIO:
    2362. if (ist->dec_ctx->sample_rate) {
    2363. ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) /
    2364. ist->dec_ctx->sample_rate;
    2365. } else {
    2366. ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
    2367. }
    2368. break;
    2369. case AVMEDIA_TYPE_VIDEO:
    2370. if (ist->framerate.num) {
    2371. // TODO: Remove work-around for c99-to-c89 issue 7
    2372. AVRational time_base_q = AV_TIME_BASE_Q;
    2373. int64_t next_dts = av_rescale_q(ist->next_dts, time_base_q, av_inv_q(ist->framerate));
    2374. ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), time_base_q);
    2375. } else if (pkt->duration) {
    2376. ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
    2377. } else if(ist->dec_ctx->framerate.num != 0) {
    2378. int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;
    2379. ist->next_dts += ((int64_t)AV_TIME_BASE *
    2380. ist->dec_ctx->framerate.den * ticks) /
    2381. ist->dec_ctx->framerate.num / ist->dec_ctx->ticks_per_frame;
    2382. }
    2383. break;
    2384. }
    2385. ist->pts = ist->dts;
    2386. ist->next_pts = ist->next_dts;
    2387. }
    2388. for (i = 0; pkt && i < nb_output_streams; i++) {
    2389. OutputStream *ost = output_streams[i];
    2390. if (!check_output_constraints(ist, ost) || ost->encoding_needed)
    2391. continue;
    2392. do_streamcopy(ist, ost, pkt);
    2393. }
    2394. return !eof_reached;
    2395. }
    2396. static void print_sdp(void)
    2397. {
    2398. char sdp[16384];
    2399. int i;
    2400. int j;
    2401. AVIOContext *sdp_pb;
    2402. AVFormatContext **avc;
    2403. for (i = 0; i < nb_output_files; i++) {
    2404. if (!output_files[i]->header_written)
    2405. return;
    2406. }
    2407. avc = av_malloc_array(nb_output_files, sizeof(*avc));
    2408. if (!avc)
    2409. exit_program(1);
    2410. for (i = 0, j = 0; i < nb_output_files; i++) {
    2411. if (!strcmp(output_files[i]->ctx->oformat->name, "rtp")) {
    2412. avc[j] = output_files[i]->ctx;
    2413. j++;
    2414. }
    2415. }
    2416. if (!j)
    2417. goto fail;
    2418. av_sdp_create(avc, j, sdp, sizeof(sdp));
    2419. if (!sdp_filename) {
    2420. printf("SDP:\n%s\n", sdp);
    2421. fflush(stdout);
    2422. } else {
    2423. if (avio_open2(&sdp_pb, sdp_filename, AVIO_FLAG_WRITE, &int_cb, NULL) < 0) {
    2424. av_log(NULL, AV_LOG_ERROR, "Failed to open sdp file '%s'\n", sdp_filename);
    2425. } else {
    2426. avio_printf(sdp_pb, "SDP:\n%s", sdp);
    2427. avio_closep(&sdp_pb);
    2428. av_freep(&sdp_filename);
    2429. }
    2430. }
    2431. fail:
    2432. av_freep(&avc);
    2433. }
    2434. static const HWAccel *get_hwaccel(enum AVPixelFormat pix_fmt)
    2435. {
    2436. int i;
    2437. for (i = 0; hwaccels[i].name; i++)
    2438. if (hwaccels[i].pix_fmt == pix_fmt)
    2439. return &hwaccels[i];
    2440. return NULL;
    2441. }
    2442. static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
    2443. {
    2444. InputStream *ist = s->opaque;
    2445. const enum AVPixelFormat *p;
    2446. int ret;
    2447. for (p = pix_fmts; *p != -1; p++) {
    2448. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
    2449. const HWAccel *hwaccel;
    2450. if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
    2451. break;
    2452. hwaccel = get_hwaccel(*p);
    2453. if (!hwaccel ||
    2454. (ist->active_hwaccel_id && ist->active_hwaccel_id != hwaccel->id) ||
    2455. (ist->hwaccel_id != HWACCEL_AUTO && ist->hwaccel_id != hwaccel->id))
    2456. continue;
    2457. ret = hwaccel->init(s);
    2458. if (ret < 0) {
    2459. if (ist->hwaccel_id == hwaccel->id) {
    2460. av_log(NULL, AV_LOG_FATAL,
    2461. "%s hwaccel requested for input stream #%d:%d, "
    2462. "but cannot be initialized.\n", hwaccel->name,
    2463. ist->file_index, ist->st->index);
    2464. return AV_PIX_FMT_NONE;
    2465. }
    2466. continue;
    2467. }
    2468. if (ist->hw_frames_ctx) {
    2469. s->hw_frames_ctx = av_buffer_ref(ist->hw_frames_ctx);
    2470. if (!s->hw_frames_ctx)
    2471. return AV_PIX_FMT_NONE;
    2472. }
    2473. ist->active_hwaccel_id = hwaccel->id;
    2474. ist->hwaccel_pix_fmt = *p;
    2475. break;
    2476. }
    2477. return *p;
    2478. }
    2479. static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
    2480. {
    2481. InputStream *ist = s->opaque;
    2482. if (ist->hwaccel_get_buffer && frame->format == ist->hwaccel_pix_fmt)
    2483. return ist->hwaccel_get_buffer(s, frame, flags);
    2484. return avcodec_default_get_buffer2(s, frame, flags);
    2485. }
    2486. static int init_input_stream(int ist_index, char *error, int error_len)
    2487. {
    2488. int ret;
    2489. InputStream *ist = input_streams[ist_index];
    2490. if (ist->decoding_needed) {
    2491. AVCodec *codec = ist->dec;
    2492. if (!codec) {
    2493. snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
    2494. avcodec_get_name(ist->dec_ctx->codec_id), ist->file_index, ist->st->index);
    2495. return AVERROR(EINVAL);
    2496. }
    2497. ist->dec_ctx->opaque = ist;
    2498. ist->dec_ctx->get_format = get_format;
    2499. ist->dec_ctx->get_buffer2 = get_buffer;
    2500. ist->dec_ctx->thread_safe_callbacks = 1;
    2501. av_opt_set_int(ist->dec_ctx, "refcounted_frames", 1, 0);
    2502. if (ist->dec_ctx->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
    2503. (ist->decoding_needed & DECODING_FOR_OST)) {
    2504. av_dict_set(&ist->decoder_opts, "compute_edt", "1", AV_DICT_DONT_OVERWRITE);
    2505. if (ist->decoding_needed & DECODING_FOR_FILTER)
    2506. av_log(NULL, AV_LOG_WARNING, "Warning using DVB subtitles for filtering and output at the same time is not fully supported, also see -compute_edt [0|1]\n");
    2507. }
    2508. av_dict_set(&ist->decoder_opts, "sub_text_format", "ass", AV_DICT_DONT_OVERWRITE);
    2509. /* Useful for subtitles retiming by lavf (FIXME), skipping samples in
    2510. * audio, and video decoders such as cuvid or mediacodec */
    2511. av_codec_set_pkt_timebase(ist->dec_ctx, ist->st->time_base);
    2512. if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
    2513. av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
    2514. if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
    2515. if (ret == AVERROR_EXPERIMENTAL)
    2516. abort_codec_experimental(codec, 0);
    2517. snprintf(error, error_len,
    2518. "Error while opening decoder for input stream "
    2519. "#%d:%d : %s",
    2520. ist->file_index, ist->st->index, av_err2str(ret));
    2521. return ret;
    2522. }
    2523. assert_avoptions(ist->decoder_opts);
    2524. }
    2525. ist->next_pts = AV_NOPTS_VALUE;
    2526. ist->next_dts = AV_NOPTS_VALUE;
    2527. return 0;
    2528. }
    2529. static InputStream *get_input_stream(OutputStream *ost)
    2530. {
    2531. if (ost->source_index >= 0)
    2532. return input_streams[ost->source_index];
    2533. return NULL;
    2534. }
    2535. static int compare_int64(const void *a, const void *b)
    2536. {
    2537. return FFDIFFSIGN(*(const int64_t *)a, *(const int64_t *)b);
    2538. }
    2539. /* open the muxer when all the streams are initialized */
    2540. static int check_init_output_file(OutputFile *of, int file_index)
    2541. {
    2542. int ret, i;
    2543. for (i = 0; i < of->ctx->nb_streams; i++) {
    2544. OutputStream *ost = output_streams[of->ost_index + i];
    2545. if (!ost->initialized)
    2546. return 0;
    2547. }
    2548. of->ctx->interrupt_callback = int_cb;
    2549. ret = avformat_write_header(of->ctx, &of->opts);
    2550. if (ret < 0) {
    2551. av_log(NULL, AV_LOG_ERROR,
    2552. "Could not write header for output file #%d "
    2553. "(incorrect codec parameters ?): %s\n",
    2554. file_index, av_err2str(ret));
    2555. return ret;
    2556. }
    2557. //assert_avoptions(of->opts);
    2558. of->header_written = 1;
    2559. av_dump_format(of->ctx, file_index, of->ctx->filename, 1);
    2560. if (sdp_filename || want_sdp)
    2561. print_sdp();
    2562. /* flush the muxing queues */
    2563. for (i = 0; i < of->ctx->nb_streams; i++) {
    2564. OutputStream *ost = output_streams[of->ost_index + i];
    2565. /* try to improve muxing time_base (only possible if nothing has been written yet) */
    2566. if (!av_fifo_size(ost->muxing_queue))
    2567. ost->mux_timebase = ost->st->time_base;
    2568. while (av_fifo_size(ost->muxing_queue)) {
    2569. AVPacket pkt;
    2570. av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
    2571. write_packet(of, &pkt, ost, 1);
    2572. }
    2573. }
    2574. return 0;
    2575. }
    2576. static int init_output_bsfs(OutputStream *ost)
    2577. {
    2578. AVBSFContext *ctx;
    2579. int i, ret;
    2580. if (!ost->nb_bitstream_filters)
    2581. return 0;
    2582. for (i = 0; i < ost->nb_bitstream_filters; i++) {
    2583. ctx = ost->bsf_ctx[i];
    2584. ret = avcodec_parameters_copy(ctx->par_in,
    2585. i ? ost->bsf_ctx[i - 1]->par_out : ost->st->codecpar);
    2586. if (ret < 0)
    2587. return ret;
    2588. ctx->time_base_in = i ? ost->bsf_ctx[i - 1]->time_base_out : ost->st->time_base;
    2589. ret = av_bsf_init(ctx);
    2590. if (ret < 0) {
    2591. av_log(NULL, AV_LOG_ERROR, "Error initializing bitstream filter: %s\n",
    2592. ost->bsf_ctx[i]->filter->name);
    2593. return ret;
    2594. }
    2595. }
    2596. ctx = ost->bsf_ctx[ost->nb_bitstream_filters - 1];
    2597. ret = avcodec_parameters_copy(ost->st->codecpar, ctx->par_out);
    2598. if (ret < 0)
    2599. return ret;
    2600. ost->st->time_base = ctx->time_base_out;
    2601. return 0;
    2602. }
    2603. static int init_output_stream_streamcopy(OutputStream *ost)
    2604. {
    2605. OutputFile *of = output_files[ost->file_index];
    2606. InputStream *ist = get_input_stream(ost);
    2607. AVCodecParameters *par_dst = ost->st->codecpar;
    2608. AVCodecParameters *par_src = ost->ref_par;
    2609. AVRational sar;
    2610. int i, ret;
    2611. uint32_t codec_tag = par_dst->codec_tag;
    2612. av_assert0(ist && !ost->filter);
    2613. ret = avcodec_parameters_to_context(ost->enc_ctx, ist->st->codecpar);
    2614. if (ret >= 0)
    2615. ret = av_opt_set_dict(ost->enc_ctx, &ost->encoder_opts);
    2616. if (ret < 0) {
    2617. av_log(NULL, AV_LOG_FATAL,
    2618. "Error setting up codec context options.\n");
    2619. return ret;
    2620. }
    2621. avcodec_parameters_from_context(par_src, ost->enc_ctx);
    2622. if (!codec_tag) {
    2623. unsigned int codec_tag_tmp;
    2624. if (!of->ctx->oformat->codec_tag ||
    2625. av_codec_get_id (of->ctx->oformat->codec_tag, par_src->codec_tag) == par_src->codec_id ||
    2626. !av_codec_get_tag2(of->ctx->oformat->codec_tag, par_src->codec_id, &codec_tag_tmp))
    2627. codec_tag = par_src->codec_tag;
    2628. }
    2629. ret = avcodec_parameters_copy(par_dst, par_src);
    2630. if (ret < 0)
    2631. return ret;
    2632. par_dst->codec_tag = codec_tag;
    2633. if (!ost->frame_rate.num)
    2634. ost->frame_rate = ist->framerate;
    2635. ost->st->avg_frame_rate = ost->frame_rate;
    2636. ret = avformat_transfer_internal_stream_timing_info(of->ctx->oformat, ost->st, ist->st, copy_tb);
    2637. if (ret < 0)
    2638. return ret;
    2639. // copy timebase while removing common factors
    2640. if (ost->st->time_base.num <= 0 || ost->st->time_base.den <= 0)
    2641. ost->st->time_base = av_add_q(av_stream_get_codec_timebase(ost->st), (AVRational){0, 1});
    2642. // copy estimated duration as a hint to the muxer
    2643. if (ost->st->duration <= 0 && ist->st->duration > 0)
    2644. ost->st->duration = av_rescale_q(ist->st->duration, ist->st->time_base, ost->st->time_base);
    2645. // copy disposition
    2646. ost->st->disposition = ist->st->disposition;
    2647. if (ist->st->nb_side_data) {
    2648. ost->st->side_data = av_realloc_array(NULL, ist->st->nb_side_data,
    2649. sizeof(*ist->st->side_data));
    2650. if (!ost->st->side_data)
    2651. return AVERROR(ENOMEM);
    2652. ost->st->nb_side_data = 0;
    2653. for (i = 0; i < ist->st->nb_side_data; i++) {
    2654. const AVPacketSideData *sd_src = &ist->st->side_data[i];
    2655. AVPacketSideData *sd_dst = &ost->st->side_data[ost->st->nb_side_data];
    2656. sd_dst->data = av_malloc(sd_src->size);
    2657. if (!sd_dst->data)
    2658. return AVERROR(ENOMEM);
    2659. memcpy(sd_dst->data, sd_src->data, sd_src->size);
    2660. sd_dst->size = sd_src->size;
    2661. sd_dst->type = sd_src->type;
    2662. ost->st->nb_side_data++;
    2663. }
    2664. }
    2665. if (ost->rotate_overridden) {
    2666. uint8_t *sd = av_stream_new_side_data(ost->st, AV_PKT_DATA_DISPLAYMATRIX,
    2667. sizeof(int32_t) * 9);
    2668. if (sd)
    2669. av_display_rotation_set((int32_t *)sd, -ost->rotate_override_value);
    2670. }
    2671. ost->parser = av_parser_init(par_dst->codec_id);
    2672. ost->parser_avctx = avcodec_alloc_context3(NULL);
    2673. if (!ost->parser_avctx)
    2674. return AVERROR(ENOMEM);
    2675. switch (par_dst->codec_type) {
    2676. case AVMEDIA_TYPE_AUDIO:
    2677. if (audio_volume != 256) {
    2678. av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
    2679. exit_program(1);
    2680. }
    2681. if((par_dst->block_align == 1 || par_dst->block_align == 1152 || par_dst->block_align == 576) && par_dst->codec_id == AV_CODEC_ID_MP3)
    2682. par_dst->block_align= 0;
    2683. if(par_dst->codec_id == AV_CODEC_ID_AC3)
    2684. par_dst->block_align= 0;
    2685. break;
    2686. case AVMEDIA_TYPE_VIDEO:
    2687. if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
    2688. sar =
    2689. av_mul_q(ost->frame_aspect_ratio,
    2690. (AVRational){ par_dst->height, par_dst->width });
    2691. av_log(NULL, AV_LOG_WARNING, "Overriding aspect ratio "
    2692. "with stream copy may produce invalid files\n");
    2693. }
    2694. else if (ist->st->sample_aspect_ratio.num)
    2695. sar = ist->st->sample_aspect_ratio;
    2696. else
    2697. sar = par_src->sample_aspect_ratio;
    2698. ost->st->sample_aspect_ratio = par_dst->sample_aspect_ratio = sar;
    2699. ost->st->avg_frame_rate = ist->st->avg_frame_rate;
    2700. ost->st->r_frame_rate = ist->st->r_frame_rate;
    2701. break;
    2702. }
    2703. ost->mux_timebase = ist->st->time_base;
    2704. return 0;
    2705. }
    2706. static void set_encoder_id(OutputFile *of, OutputStream *ost)
    2707. {
    2708. AVDictionaryEntry *e;
    2709. uint8_t *encoder_string;
    2710. int encoder_string_len;
    2711. int format_flags = 0;
    2712. int codec_flags = 0;
    2713. if (av_dict_get(ost->st->metadata, "encoder", NULL, 0))
    2714. return;
    2715. e = av_dict_get(of->opts, "fflags", NULL, 0);
    2716. if (e) {
    2717. const AVOption *o = av_opt_find(of->ctx, "fflags", NULL, 0, 0);
    2718. if (!o)
    2719. return;
    2720. av_opt_eval_flags(of->ctx, o, e->value, &format_flags);
    2721. }
    2722. e = av_dict_get(ost->encoder_opts, "flags", NULL, 0);
    2723. if (e) {
    2724. const AVOption *o = av_opt_find(ost->enc_ctx, "flags", NULL, 0, 0);
    2725. if (!o)
    2726. return;
    2727. av_opt_eval_flags(ost->enc_ctx, o, e->value, &codec_flags);
    2728. }
    2729. encoder_string_len = sizeof(LIBAVCODEC_IDENT) + strlen(ost->enc->name) + 2;
    2730. encoder_string = av_mallocz(encoder_string_len);
    2731. if (!encoder_string)
    2732. exit_program(1);
    2733. if (!(format_flags & AVFMT_FLAG_BITEXACT) && !(codec_flags & AV_CODEC_FLAG_BITEXACT))
    2734. av_strlcpy(encoder_string, LIBAVCODEC_IDENT " ", encoder_string_len);
    2735. else
    2736. av_strlcpy(encoder_string, "Lavc ", encoder_string_len);
    2737. av_strlcat(encoder_string, ost->enc->name, encoder_string_len);
    2738. av_dict_set(&ost->st->metadata, "encoder", encoder_string,
    2739. AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
    2740. }
    2741. static void parse_forced_key_frames(char *kf, OutputStream *ost,
    2742. AVCodecContext *avctx)
    2743. {
    2744. char *p;
    2745. int n = 1, i, size, index = 0;
    2746. int64_t t, *pts;
    2747. for (p = kf; *p; p++)
    2748. if (*p == ',')
    2749. n++;
    2750. size = n;
    2751. pts = av_malloc_array(size, sizeof(*pts));
    2752. if (!pts) {
    2753. av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
    2754. exit_program(1);
    2755. }
    2756. p = kf;
    2757. for (i = 0; i < n; i++) {
    2758. char *next = strchr(p, ',');
    2759. if (next)
    2760. *next++ = 0;
    2761. if (!memcmp(p, "chapters", 8)) {
    2762. AVFormatContext *avf = output_files[ost->file_index]->ctx;
    2763. int j;
    2764. if (avf->nb_chapters > INT_MAX - size ||
    2765. !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
    2766. sizeof(*pts)))) {
    2767. av_log(NULL, AV_LOG_FATAL,
    2768. "Could not allocate forced key frames array.\n");
    2769. exit_program(1);
    2770. }
    2771. t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
    2772. t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
    2773. for (j = 0; j < avf->nb_chapters; j++) {
    2774. AVChapter *c = avf->chapters[j];
    2775. av_assert1(index < size);
    2776. pts[index++] = av_rescale_q(c->start, c->time_base,
    2777. avctx->time_base) + t;
    2778. }
    2779. } else {
    2780. t = parse_time_or_die("force_key_frames", p, 1);
    2781. av_assert1(index < size);
    2782. pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
    2783. }
    2784. p = next;
    2785. }
    2786. av_assert0(index == size);
    2787. qsort(pts, size, sizeof(*pts), compare_int64);
    2788. ost->forced_kf_count = size;
    2789. ost->forced_kf_pts = pts;
    2790. }
    2791. static int init_output_stream_encode(OutputStream *ost)
    2792. {
    2793. InputStream *ist = get_input_stream(ost);
    2794. AVCodecContext *enc_ctx = ost->enc_ctx;
    2795. AVCodecContext *dec_ctx = NULL;
    2796. AVFormatContext *oc = output_files[ost->file_index]->ctx;
    2797. int j, ret;
    2798. set_encoder_id(output_files[ost->file_index], ost);
    2799. // Muxers use AV_PKT_DATA_DISPLAYMATRIX to signal rotation. On the other
    2800. // hand, the legacy API makes demuxers set "rotate" metadata entries,
    2801. // which have to be filtered out to prevent leaking them to output files.
    2802. av_dict_set(&ost->st->metadata, "rotate", NULL, 0);
    2803. if (ist) {
    2804. ost->st->disposition = ist->st->disposition;
    2805. dec_ctx = ist->dec_ctx;
    2806. enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location;
    2807. } else {
    2808. for (j = 0; j < oc->nb_streams; j++) {
    2809. AVStream *st = oc->streams[j];
    2810. if (st != ost->st && st->codecpar->codec_type == ost->st->codecpar->codec_type)
    2811. break;
    2812. }
    2813. if (j == oc->nb_streams)
    2814. if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ||
    2815. ost->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
    2816. ost->st->disposition = AV_DISPOSITION_DEFAULT;
    2817. }
    2818. if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
    2819. if (!ost->frame_rate.num)
    2820. ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
    2821. if (ist && !ost->frame_rate.num)
    2822. ost->frame_rate = ist->framerate;
    2823. if (ist && !ost->frame_rate.num)
    2824. ost->frame_rate = ist->st->r_frame_rate;
    2825. if (ist && !ost->frame_rate.num) {
    2826. ost->frame_rate = (AVRational){25, 1};
    2827. av_log(NULL, AV_LOG_WARNING,
    2828. "No information "
    2829. "about the input framerate is available. Falling "
    2830. "back to a default value of 25fps for output stream #%d:%d. Use the -r option "
    2831. "if you want a different framerate.\n",
    2832. ost->file_index, ost->index);
    2833. }
    2834. // ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
    2835. if (ost->enc->supported_framerates && !ost->force_fps) {
    2836. int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
    2837. ost->frame_rate = ost->enc->supported_framerates[idx];
    2838. }
    2839. // reduce frame rate for mpeg4 to be within the spec limits
    2840. if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) {
    2841. av_reduce(&ost->frame_rate.num, &ost->frame_rate.den,
    2842. ost->frame_rate.num, ost->frame_rate.den, 65535);
    2843. }
    2844. }
    2845. switch (enc_ctx->codec_type) {
    2846. case AVMEDIA_TYPE_AUDIO:
    2847. enc_ctx->sample_fmt = av_buffersink_get_format(ost->filter->filter);
    2848. if (dec_ctx)
    2849. enc_ctx->bits_per_raw_sample = FFMIN(dec_ctx->bits_per_raw_sample,
    2850. av_get_bytes_per_sample(enc_ctx->sample_fmt) << 3);
    2851. enc_ctx->sample_rate = av_buffersink_get_sample_rate(ost->filter->filter);
    2852. enc_ctx->channel_layout = av_buffersink_get_channel_layout(ost->filter->filter);
    2853. enc_ctx->channels = av_buffersink_get_channels(ost->filter->filter);
    2854. enc_ctx->time_base = (AVRational){ 1, enc_ctx->sample_rate };
    2855. break;
    2856. case AVMEDIA_TYPE_VIDEO:
    2857. enc_ctx->time_base = av_inv_q(ost->frame_rate);
    2858. if (!(enc_ctx->time_base.num && enc_ctx->time_base.den))
    2859. enc_ctx->time_base = av_buffersink_get_time_base(ost->filter->filter);
    2860. if ( av_q2d(enc_ctx->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
    2861. && (video_sync_method == VSYNC_CFR || video_sync_method == VSYNC_VSCFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
    2862. av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
    2863. "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
    2864. }
    2865. for (j = 0; j < ost->forced_kf_count; j++)
    2866. ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
    2867. AV_TIME_BASE_Q,
    2868. enc_ctx->time_base);
    2869. enc_ctx->width = av_buffersink_get_w(ost->filter->filter);
    2870. enc_ctx->height = av_buffersink_get_h(ost->filter->filter);
    2871. enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =
    2872. ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option
    2873. av_mul_q(ost->frame_aspect_ratio, (AVRational){ enc_ctx->height, enc_ctx->width }) :
    2874. av_buffersink_get_sample_aspect_ratio(ost->filter->filter);
    2875. if (!strncmp(ost->enc->name, "libx264", 7) &&
    2876. enc_ctx->pix_fmt == AV_PIX_FMT_NONE &&
    2877. av_buffersink_get_format(ost->filter->filter) != AV_PIX_FMT_YUV420P)
    2878. av_log(NULL, AV_LOG_WARNING,
    2879. "No pixel format specified, %s for H.264 encoding chosen.\n"
    2880. "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
    2881. av_get_pix_fmt_name(av_buffersink_get_format(ost->filter->filter)));
    2882. if (!strncmp(ost->enc->name, "mpeg2video", 10) &&
    2883. enc_ctx->pix_fmt == AV_PIX_FMT_NONE &&
    2884. av_buffersink_get_format(ost->filter->filter) != AV_PIX_FMT_YUV420P)
    2885. av_log(NULL, AV_LOG_WARNING,
    2886. "No pixel format specified, %s for MPEG-2 encoding chosen.\n"
    2887. "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
    2888. av_get_pix_fmt_name(av_buffersink_get_format(ost->filter->filter)));
    2889. enc_ctx->pix_fmt = av_buffersink_get_format(ost->filter->filter);
    2890. if (dec_ctx)
    2891. enc_ctx->bits_per_raw_sample = FFMIN(dec_ctx->bits_per_raw_sample,
    2892. av_pix_fmt_desc_get(enc_ctx->pix_fmt)->comp[0].depth);
    2893. enc_ctx->framerate = ost->frame_rate;
    2894. ost->st->avg_frame_rate = ost->frame_rate;
    2895. if (!dec_ctx ||
    2896. enc_ctx->width != dec_ctx->width ||
    2897. enc_ctx->height != dec_ctx->height ||
    2898. enc_ctx->pix_fmt != dec_ctx->pix_fmt) {
    2899. enc_ctx->bits_per_raw_sample = frame_bits_per_raw_sample;
    2900. }
    2901. if (ost->forced_keyframes) {
    2902. if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
    2903. ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,
    2904. forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
    2905. if (ret < 0) {
    2906. av_log(NULL, AV_LOG_ERROR,
    2907. "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
    2908. return ret;
    2909. }
    2910. ost->forced_keyframes_expr_const_values[FKF_N] = 0;
    2911. ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;
    2912. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;
    2913. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;
    2914. // Don't parse the 'forced_keyframes' in case of 'keep-source-keyframes',
    2915. // parse it only for static kf timings
    2916. } else if(strncmp(ost->forced_keyframes, "source", 6)) {
    2917. parse_forced_key_frames(ost->forced_keyframes, ost, ost->enc_ctx);
    2918. }
    2919. }
    2920. break;
    2921. case AVMEDIA_TYPE_SUBTITLE:
    2922. enc_ctx->time_base = AV_TIME_BASE_Q;
    2923. if (!enc_ctx->width) {
    2924. enc_ctx->width = input_streams[ost->source_index]->st->codecpar->width;
    2925. enc_ctx->height = input_streams[ost->source_index]->st->codecpar->height;
    2926. }
    2927. break;
    2928. case AVMEDIA_TYPE_DATA:
    2929. break;
    2930. default:
    2931. abort();
    2932. break;
    2933. }
    2934. ost->mux_timebase = enc_ctx->time_base;
    2935. return 0;
    2936. }
    2937. static int init_output_stream(OutputStream *ost, char *error, int error_len)
    2938. {
    2939. int ret = 0;
    2940. if (ost->encoding_needed) {
    2941. AVCodec *codec = ost->enc;
    2942. AVCodecContext *dec = NULL;
    2943. InputStream *ist;
    2944. ret = init_output_stream_encode(ost);
    2945. if (ret < 0)
    2946. return ret;
    2947. if ((ist = get_input_stream(ost)))
    2948. dec = ist->dec_ctx;
    2949. if (dec && dec->subtitle_header) {
    2950. /* ASS code assumes this buffer is null terminated so add extra byte. */
    2951. ost->enc_ctx->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
    2952. if (!ost->enc_ctx->subtitle_header)
    2953. return AVERROR(ENOMEM);
    2954. memcpy(ost->enc_ctx->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
    2955. ost->enc_ctx->subtitle_header_size = dec->subtitle_header_size;
    2956. }
    2957. if (!av_dict_get(ost->encoder_opts, "threads", NULL, 0))
    2958. av_dict_set(&ost->encoder_opts, "threads", "auto", 0);
    2959. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
    2960. !codec->defaults &&
    2961. !av_dict_get(ost->encoder_opts, "b", NULL, 0) &&
    2962. !av_dict_get(ost->encoder_opts, "ab", NULL, 0))
    2963. av_dict_set(&ost->encoder_opts, "b", "128000", 0);
    2964. if (ost->filter && av_buffersink_get_hw_frames_ctx(ost->filter->filter) &&
    2965. ((AVHWFramesContext*)av_buffersink_get_hw_frames_ctx(ost->filter->filter)->data)->format ==
    2966. av_buffersink_get_format(ost->filter->filter)) {
    2967. ost->enc_ctx->hw_frames_ctx = av_buffer_ref(av_buffersink_get_hw_frames_ctx(ost->filter->filter));
    2968. if (!ost->enc_ctx->hw_frames_ctx)
    2969. return AVERROR(ENOMEM);
    2970. }
    2971. if ((ret = avcodec_open2(ost->enc_ctx, codec, &ost->encoder_opts)) < 0) {
    2972. if (ret == AVERROR_EXPERIMENTAL)
    2973. abort_codec_experimental(codec, 1);
    2974. snprintf(error, error_len,
    2975. "Error while opening encoder for output stream #%d:%d - "
    2976. "maybe incorrect parameters such as bit_rate, rate, width or height",
    2977. ost->file_index, ost->index);
    2978. return ret;
    2979. }
    2980. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
    2981. !(ost->enc->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
    2982. av_buffersink_set_frame_size(ost->filter->filter,
    2983. ost->enc_ctx->frame_size);
    2984. assert_avoptions(ost->encoder_opts);
    2985. if (ost->enc_ctx->bit_rate && ost->enc_ctx->bit_rate < 1000)
    2986. av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
    2987. " It takes bits/s as argument, not kbits/s\n");
    2988. ret = avcodec_parameters_from_context(ost->st->codecpar, ost->enc_ctx);
    2989. if (ret < 0) {
    2990. av_log(NULL, AV_LOG_FATAL,
    2991. "Error initializing the output stream codec context.\n");
    2992. exit_program(1);
    2993. }
    2994. /*
    2995. * FIXME: ost->st->codec should't be needed here anymore.
    2996. */
    2997. ret = avcodec_copy_context(ost->st->codec, ost->enc_ctx);
    2998. if (ret < 0)
    2999. return ret;
    3000. if (ost->enc_ctx->nb_coded_side_data) {
    3001. int i;
    3002. ost->st->side_data = av_realloc_array(NULL, ost->enc_ctx->nb_coded_side_data,
    3003. sizeof(*ost->st->side_data));
    3004. if (!ost->st->side_data)
    3005. return AVERROR(ENOMEM);
    3006. for (i = 0; i < ost->enc_ctx->nb_coded_side_data; i++) {
    3007. const AVPacketSideData *sd_src = &ost->enc_ctx->coded_side_data[i];
    3008. AVPacketSideData *sd_dst = &ost->st->side_data[i];
    3009. sd_dst->data = av_malloc(sd_src->size);
    3010. if (!sd_dst->data)
    3011. return AVERROR(ENOMEM);
    3012. memcpy(sd_dst->data, sd_src->data, sd_src->size);
    3013. sd_dst->size = sd_src->size;
    3014. sd_dst->type = sd_src->type;
    3015. ost->st->nb_side_data++;
    3016. }
    3017. }
    3018. /*
    3019. * Add global input side data. For now this is naive, and copies it
    3020. * from the input stream's global side data. All side data should
    3021. * really be funneled over AVFrame and libavfilter, then added back to
    3022. * packet side data, and then potentially using the first packet for
    3023. * global side data.
    3024. */
    3025. if (ist) {
    3026. int i;
    3027. for (i = 0; i < ist->st->nb_side_data; i++) {
    3028. AVPacketSideData *sd = &ist->st->side_data[i];
    3029. uint8_t *dst = av_stream_new_side_data(ost->st, sd->type, sd->size);
    3030. if (!dst)
    3031. return AVERROR(ENOMEM);
    3032. memcpy(dst, sd->data, sd->size);
    3033. if (ist->autorotate && sd->type == AV_PKT_DATA_DISPLAYMATRIX)
    3034. av_display_rotation_set((uint32_t *)dst, 0);
    3035. }
    3036. }
    3037. // copy timebase while removing common factors
    3038. if (ost->st->time_base.num <= 0 || ost->st->time_base.den <= 0)
    3039. ost->st->time_base = av_add_q(ost->enc_ctx->time_base, (AVRational){0, 1});
    3040. // copy estimated duration as a hint to the muxer
    3041. if (ost->st->duration <= 0 && ist && ist->st->duration > 0)
    3042. ost->st->duration = av_rescale_q(ist->st->duration, ist->st->time_base, ost->st->time_base);
    3043. ost->st->codec->codec= ost->enc_ctx->codec;
    3044. } else if (ost->stream_copy) {
    3045. ret = init_output_stream_streamcopy(ost);
    3046. if (ret < 0)
    3047. return ret;
    3048. /*
    3049. * FIXME: will the codec context used by the parser during streamcopy
    3050. * This should go away with the new parser API.
    3051. */
    3052. ret = avcodec_parameters_to_context(ost->parser_avctx, ost->st->codecpar);
    3053. if (ret < 0)
    3054. return ret;
    3055. }
    3056. // parse user provided disposition, and update stream values
    3057. if (ost->disposition) {
    3058. static const AVOption opts[] = {
    3059. { "disposition" , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, INT64_MAX, .unit = "flags" },
    3060. { "default" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEFAULT }, .unit = "flags" },
    3061. { "dub" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DUB }, .unit = "flags" },
    3062. { "original" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ORIGINAL }, .unit = "flags" },
    3063. { "comment" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_COMMENT }, .unit = "flags" },
    3064. { "lyrics" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_LYRICS }, .unit = "flags" },
    3065. { "karaoke" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_KARAOKE }, .unit = "flags" },
    3066. { "forced" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_FORCED }, .unit = "flags" },
    3067. { "hearing_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_HEARING_IMPAIRED }, .unit = "flags" },
    3068. { "visual_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_VISUAL_IMPAIRED }, .unit = "flags" },
    3069. { "clean_effects" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CLEAN_EFFECTS }, .unit = "flags" },
    3070. { "captions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CAPTIONS }, .unit = "flags" },
    3071. { "descriptions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DESCRIPTIONS }, .unit = "flags" },
    3072. { "metadata" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_METADATA }, .unit = "flags" },
    3073. { NULL },
    3074. };
    3075. static const AVClass class = {
    3076. .class_name = "",
    3077. .item_name = av_default_item_name,
    3078. .option = opts,
    3079. .version = LIBAVUTIL_VERSION_INT,
    3080. };
    3081. const AVClass *pclass = &class;
    3082. ret = av_opt_eval_flags(&pclass, &opts[0], ost->disposition, &ost->st->disposition);
    3083. if (ret < 0)
    3084. return ret;
    3085. }
    3086. /* initialize bitstream filters for the output stream
    3087. * needs to be done here, because the codec id for streamcopy is not
    3088. * known until now */
    3089. ret = init_output_bsfs(ost);
    3090. if (ret < 0)
    3091. return ret;
    3092. ost->initialized = 1;
    3093. ret = check_init_output_file(output_files[ost->file_index], ost->file_index);
    3094. if (ret < 0)
    3095. return ret;
    3096. return ret;
    3097. }
    3098. static void report_new_stream(int input_index, AVPacket *pkt)
    3099. {
    3100. InputFile *file = input_files[input_index];
    3101. AVStream *st = file->ctx->streams[pkt->stream_index];
    3102. if (pkt->stream_index < file->nb_streams_warn)
    3103. return;
    3104. av_log(file->ctx, AV_LOG_WARNING,
    3105. "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
    3106. av_get_media_type_string(st->codecpar->codec_type),
    3107. input_index, pkt->stream_index,
    3108. pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
    3109. file->nb_streams_warn = pkt->stream_index + 1;
    3110. }
    3111. static int transcode_init(void)
    3112. {
    3113. int ret = 0, i, j, k;
    3114. AVFormatContext *oc;
    3115. OutputStream *ost;
    3116. InputStream *ist;
    3117. char error[1024] = {0};
    3118. for (i = 0; i < nb_filtergraphs; i++) {
    3119. FilterGraph *fg = filtergraphs[i];
    3120. for (j = 0; j < fg->nb_outputs; j++) {
    3121. OutputFilter *ofilter = fg->outputs[j];
    3122. if (!ofilter->ost || ofilter->ost->source_index >= 0)
    3123. continue;
    3124. if (fg->nb_inputs != 1)
    3125. continue;
    3126. for (k = nb_input_streams-1; k >= 0 ; k--)
    3127. if (fg->inputs[0]->ist == input_streams[k])
    3128. break;
    3129. ofilter->ost->source_index = k;
    3130. }
    3131. }
    3132. /* init framerate emulation */
    3133. for (i = 0; i < nb_input_files; i++) {
    3134. InputFile *ifile = input_files[i];
    3135. if (ifile->rate_emu)
    3136. for (j = 0; j < ifile->nb_streams; j++)
    3137. input_streams[j + ifile->ist_index]->start = av_gettime_relative();
    3138. }
    3139. /* init input streams */
    3140. for (i = 0; i < nb_input_streams; i++)
    3141. if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
    3142. for (i = 0; i < nb_output_streams; i++) {
    3143. ost = output_streams[i];
    3144. avcodec_close(ost->enc_ctx);
    3145. }
    3146. goto dump_format;
    3147. }
    3148. /* open each encoder */
    3149. for (i = 0; i < nb_output_streams; i++) {
    3150. // skip streams fed from filtergraphs until we have a frame for them
    3151. if (output_streams[i]->filter)
    3152. continue;
    3153. ret = init_output_stream(output_streams[i], error, sizeof(error));
    3154. if (ret < 0)
    3155. goto dump_format;
    3156. }
    3157. /* discard unused programs */
    3158. for (i = 0; i < nb_input_files; i++) {
    3159. InputFile *ifile = input_files[i];
    3160. for (j = 0; j < ifile->ctx->nb_programs; j++) {
    3161. AVProgram *p = ifile->ctx->programs[j];
    3162. int discard = AVDISCARD_ALL;
    3163. for (k = 0; k < p->nb_stream_indexes; k++)
    3164. if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
    3165. discard = AVDISCARD_DEFAULT;
    3166. break;
    3167. }
    3168. p->discard = discard;
    3169. }
    3170. }
    3171. /* write headers for files with no streams */
    3172. for (i = 0; i < nb_output_files; i++) {
    3173. oc = output_files[i]->ctx;
    3174. if (oc->oformat->flags & AVFMT_NOSTREAMS && oc->nb_streams == 0) {
    3175. ret = check_init_output_file(output_files[i], i);
    3176. if (ret < 0)
    3177. goto dump_format;
    3178. }
    3179. }
    3180. dump_format:
    3181. /* dump the stream mapping */
    3182. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
    3183. for (i = 0; i < nb_input_streams; i++) {
    3184. ist = input_streams[i];
    3185. for (j = 0; j < ist->nb_filters; j++) {
    3186. if (!filtergraph_is_simple(ist->filters[j]->graph)) {
    3187. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
    3188. ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
    3189. ist->filters[j]->name);
    3190. if (nb_filtergraphs > 1)
    3191. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
    3192. av_log(NULL, AV_LOG_INFO, "\n");
    3193. }
    3194. }
    3195. }
    3196. for (i = 0; i < nb_output_streams; i++) {
    3197. ost = output_streams[i];
    3198. if (ost->attachment_filename) {
    3199. /* an attached file */
    3200. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
    3201. ost->attachment_filename, ost->file_index, ost->index);
    3202. continue;
    3203. }
    3204. if (ost->filter && !filtergraph_is_simple(ost->filter->graph)) {
    3205. /* output from a complex graph */
    3206. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
    3207. if (nb_filtergraphs > 1)
    3208. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
    3209. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
    3210. ost->index, ost->enc ? ost->enc->name : "?");
    3211. continue;
    3212. }
    3213. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
    3214. input_streams[ost->source_index]->file_index,
    3215. input_streams[ost->source_index]->st->index,
    3216. ost->file_index,
    3217. ost->index);
    3218. if (ost->sync_ist != input_streams[ost->source_index])
    3219. av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
    3220. ost->sync_ist->file_index,
    3221. ost->sync_ist->st->index);
    3222. if (ost->stream_copy)
    3223. av_log(NULL, AV_LOG_INFO, " (copy)");
    3224. else {
    3225. const AVCodec *in_codec = input_streams[ost->source_index]->dec;
    3226. const AVCodec *out_codec = ost->enc;
    3227. const char *decoder_name = "?";
    3228. const char *in_codec_name = "?";
    3229. const char *encoder_name = "?";
    3230. const char *out_codec_name = "?";
    3231. const AVCodecDescriptor *desc;
    3232. if (in_codec) {
    3233. decoder_name = in_codec->name;
    3234. desc = avcodec_descriptor_get(in_codec->id);
    3235. if (desc)
    3236. in_codec_name = desc->name;
    3237. if (!strcmp(decoder_name, in_codec_name))
    3238. decoder_name = "native";
    3239. }
    3240. if (out_codec) {
    3241. encoder_name = out_codec->name;
    3242. desc = avcodec_descriptor_get(out_codec->id);
    3243. if (desc)
    3244. out_codec_name = desc->name;
    3245. if (!strcmp(encoder_name, out_codec_name))
    3246. encoder_name = "native";
    3247. }
    3248. av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
    3249. in_codec_name, decoder_name,
    3250. out_codec_name, encoder_name);
    3251. }
    3252. av_log(NULL, AV_LOG_INFO, "\n");
    3253. }
    3254. if (ret) {
    3255. av_log(NULL, AV_LOG_ERROR, "%s\n", error);
    3256. return ret;
    3257. }
    3258. atomic_store(&transcode_init_done, 1);
    3259. return 0;
    3260. }
    3261. /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
    3262. static int need_output(void)
    3263. {
    3264. int i;
    3265. for (i = 0; i < nb_output_streams; i++) {
    3266. OutputStream *ost = output_streams[i];
    3267. OutputFile *of = output_files[ost->file_index];
    3268. AVFormatContext *os = output_files[ost->file_index]->ctx;
    3269. if (ost->finished ||
    3270. (os->pb && avio_tell(os->pb) >= of->limit_filesize))
    3271. continue;
    3272. if (ost->frame_number >= ost->max_frames) {
    3273. int j;
    3274. for (j = 0; j < of->ctx->nb_streams; j++)
    3275. close_output_stream(output_streams[of->ost_index + j]);
    3276. continue;
    3277. }
    3278. return 1;
    3279. }
    3280. return 0;
    3281. }
    3282. /**
    3283. * Select the output stream to process.
    3284. *
    3285. * @return selected output stream, or NULL if none available
    3286. */
    3287. static OutputStream *choose_output(void)
    3288. {
    3289. int i;
    3290. int64_t opts_min = INT64_MAX;
    3291. OutputStream *ost_min = NULL;
    3292. for (i = 0; i < nb_output_streams; i++) {
    3293. OutputStream *ost = output_streams[i];
    3294. int64_t opts = ost->st->cur_dts == AV_NOPTS_VALUE ? INT64_MIN :
    3295. av_rescale_q(ost->st->cur_dts, ost->st->time_base,
    3296. AV_TIME_BASE_Q);
    3297. if (ost->st->cur_dts == AV_NOPTS_VALUE)
    3298. av_log(NULL, AV_LOG_DEBUG, "cur_dts is invalid (this is harmless if it occurs once at the start per stream)\n");
    3299. if (!ost->initialized && !ost->inputs_done)
    3300. return ost;
    3301. if (!ost->finished && opts < opts_min) {
    3302. opts_min = opts;
    3303. ost_min = ost->unavailable ? NULL : ost;
    3304. }
    3305. }
    3306. return ost_min;
    3307. }
    3308. static void set_tty_echo(int on)
    3309. {
    3310. #if HAVE_TERMIOS_H
    3311. struct termios tty;
    3312. if (tcgetattr(0, &tty) == 0) {
    3313. if (on) tty.c_lflag |= ECHO;
    3314. else tty.c_lflag &= ~ECHO;
    3315. tcsetattr(0, TCSANOW, &tty);
    3316. }
    3317. #endif
    3318. }
    3319. static int check_keyboard_interaction(int64_t cur_time)
    3320. {
    3321. int i, ret, key;
    3322. static int64_t last_time;
    3323. if (received_nb_signals)
    3324. return AVERROR_EXIT;
    3325. /* read_key() returns 0 on EOF */
    3326. if(cur_time - last_time >= 100000 && !run_as_daemon){
    3327. key = read_key();
    3328. last_time = cur_time;
    3329. }else
    3330. key = -1;
    3331. if (key == 'q')
    3332. return AVERROR_EXIT;
    3333. if (key == '+') av_log_set_level(av_log_get_level()+10);
    3334. if (key == '-') av_log_set_level(av_log_get_level()-10);
    3335. if (key == 's') qp_hist ^= 1;
    3336. if (key == 'h'){
    3337. if (do_hex_dump){
    3338. do_hex_dump = do_pkt_dump = 0;
    3339. } else if(do_pkt_dump){
    3340. do_hex_dump = 1;
    3341. } else
    3342. do_pkt_dump = 1;
    3343. av_log_set_level(AV_LOG_DEBUG);
    3344. }
    3345. if (key == 'c' || key == 'C'){
    3346. char buf[4096], target[64], command[256], arg[256] = {0};
    3347. double time;
    3348. int k, n = 0;
    3349. fprintf(stderr, "\nEnter command: |all );
    3350. i = 0;
    3351. set_tty_echo(1);
    3352. while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
    3353. if (k > 0)
    3354. buf[i++] = k;
    3355. buf[i] = 0;
    3356. set_tty_echo(0);
    3357. fprintf(stderr, "\n");
    3358. if (k > 0 &&
    3359. (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
    3360. av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
    3361. target, time, command, arg);
    3362. for (i = 0; i < nb_filtergraphs; i++) {
    3363. FilterGraph *fg = filtergraphs[i];
    3364. if (fg->graph) {
    3365. if (time < 0) {
    3366. ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
    3367. key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
    3368. fprintf(stderr, "Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
    3369. } else if (key == 'c') {
    3370. fprintf(stderr, "Queuing commands only on filters supporting the specific command is unsupported\n");
    3371. ret = AVERROR_PATCHWELCOME;
    3372. } else {
    3373. ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
    3374. if (ret < 0)
    3375. fprintf(stderr, "Queuing command failed with error %s\n", av_err2str(ret));
    3376. }
    3377. }
    3378. }
    3379. } else {
    3380. av_log(NULL, AV_LOG_ERROR,
    3381. "Parse error, at least 3 arguments were expected, "
    3382. "only %d given in string '%s'\n", n, buf);
    3383. }
    3384. }
    3385. if (key == 'd' || key == 'D'){
    3386. int debug=0;
    3387. if(key == 'D') {
    3388. debug = input_streams[0]->st->codec->debug<<1;
    3389. if(!debug) debug = 1;
    3390. while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
    3391. debug += debug;
    3392. }else{
    3393. char buf[32];
    3394. int k = 0;
    3395. i = 0;
    3396. set_tty_echo(1);
    3397. while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
    3398. if (k > 0)
    3399. buf[i++] = k;
    3400. buf[i] = 0;
    3401. set_tty_echo(0);
    3402. fprintf(stderr, "\n");
    3403. if (k <= 0 || sscanf(buf, "%d", &debug)!=1)
    3404. fprintf(stderr,"error parsing debug value\n");
    3405. }
    3406. for(i=0;i
    3407. input_streams[i]->st->codec->debug = debug;
    3408. }
    3409. for(i=0;i
    3410. OutputStream *ost = output_streams[i];
    3411. ost->enc_ctx->debug = debug;
    3412. }
    3413. if(debug) av_log_set_level(AV_LOG_DEBUG);
    3414. fprintf(stderr,"debug=%d\n", debug);
    3415. }
    3416. if (key == '?'){
    3417. fprintf(stderr, "key function\n"
    3418. "? show this help\n"
    3419. "+ increase verbosity\n"
    3420. "- decrease verbosity\n"
    3421. "c Send command to first matching filter supporting it\n"
    3422. "C Send/Queue command to all matching filters\n"
    3423. "D cycle through available debug modes\n"
    3424. "h dump packets/hex press to cycle through the 3 states\n"
    3425. "q quit\n"
    3426. "s Show QP histogram\n"
    3427. );
    3428. }
    3429. return 0;
    3430. }
    3431. #if HAVE_PTHREADS
    3432. static void *input_thread(void *arg)
    3433. {
    3434. InputFile *f = arg;
    3435. unsigned flags = f->non_blocking ? AV_THREAD_MESSAGE_NONBLOCK : 0;
    3436. int ret = 0;
    3437. while (1) {
    3438. AVPacket pkt;
    3439. ret = av_read_frame(f->ctx, &pkt);
    3440. if (ret == AVERROR(EAGAIN)) {
    3441. av_usleep(10000);
    3442. continue;
    3443. }
    3444. if (ret < 0) {
    3445. av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
    3446. break;
    3447. }
    3448. ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
    3449. if (flags && ret == AVERROR(EAGAIN)) {
    3450. flags = 0;
    3451. ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
    3452. av_log(f->ctx, AV_LOG_WARNING,
    3453. "Thread message queue blocking; consider raising the "
    3454. "thread_queue_size option (current value: %d)\n",
    3455. f->thread_queue_size);
    3456. }
    3457. if (ret < 0) {
    3458. if (ret != AVERROR_EOF)
    3459. av_log(f->ctx, AV_LOG_ERROR,
    3460. "Unable to send packet to main thread: %s\n",
    3461. av_err2str(ret));
    3462. av_packet_unref(&pkt);
    3463. av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
    3464. break;
    3465. }
    3466. }
    3467. return NULL;
    3468. }
    3469. static void free_input_threads(void)
    3470. {
    3471. int i;
    3472. for (i = 0; i < nb_input_files; i++) {
    3473. InputFile *f = input_files[i];
    3474. AVPacket pkt;
    3475. if (!f || !f->in_thread_queue)
    3476. continue;
    3477. av_thread_message_queue_set_err_send(f->in_thread_queue, AVERROR_EOF);
    3478. while (av_thread_message_queue_recv(f->in_thread_queue, &pkt, 0) >= 0)
    3479. av_packet_unref(&pkt);
    3480. pthread_join(f->thread, NULL);
    3481. f->joined = 1;
    3482. av_thread_message_queue_free(&f->in_thread_queue);
    3483. }
    3484. }
    3485. static int init_input_threads(void)
    3486. {
    3487. int i, ret;
    3488. if (nb_input_files == 1)
    3489. return 0;
    3490. for (i = 0; i < nb_input_files; i++) {
    3491. InputFile *f = input_files[i];
    3492. if (f->ctx->pb ? !f->ctx->pb->seekable :
    3493. strcmp(f->ctx->iformat->name, "lavfi"))
    3494. f->non_blocking = 1;
    3495. ret = av_thread_message_queue_alloc(&f->in_thread_queue,
    3496. f->thread_queue_size, sizeof(AVPacket));
    3497. if (ret < 0)
    3498. return ret;
    3499. if ((ret = pthread_create(&f->thread, NULL, input_thread, f))) {
    3500. av_log(NULL, AV_LOG_ERROR, "pthread_create failed: %s. Try to increase `ulimit -v` or decrease `ulimit -s`.\n", strerror(ret));
    3501. av_thread_message_queue_free(&f->in_thread_queue);
    3502. return AVERROR(ret);
    3503. }
    3504. }
    3505. return 0;
    3506. }
    3507. static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
    3508. {
    3509. return av_thread_message_queue_recv(f->in_thread_queue, pkt,
    3510. f->non_blocking ?
    3511. AV_THREAD_MESSAGE_NONBLOCK : 0);
    3512. }
    3513. #endif
    3514. static int get_input_packet(InputFile *f, AVPacket *pkt)
    3515. {
    3516. if (f->rate_emu) {
    3517. int i;
    3518. for (i = 0; i < f->nb_streams; i++) {
    3519. InputStream *ist = input_streams[f->ist_index + i];
    3520. int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
    3521. int64_t now = av_gettime_relative() - ist->start;
    3522. if (pts > now)
    3523. return AVERROR(EAGAIN);
    3524. }
    3525. }
    3526. #if HAVE_PTHREADS
    3527. if (nb_input_files > 1)
    3528. return get_input_packet_mt(f, pkt);
    3529. #endif
    3530. return av_read_frame(f->ctx, pkt);
    3531. }
    3532. static int got_eagain(void)
    3533. {
    3534. int i;
    3535. for (i = 0; i < nb_output_streams; i++)
    3536. if (output_streams[i]->unavailable)
    3537. return 1;
    3538. return 0;
    3539. }
    3540. static void reset_eagain(void)
    3541. {
    3542. int i;
    3543. for (i = 0; i < nb_input_files; i++)
    3544. input_files[i]->eagain = 0;
    3545. for (i = 0; i < nb_output_streams; i++)
    3546. output_streams[i]->unavailable = 0;
    3547. }
    3548. // set duration to max(tmp, duration) in a proper time base and return duration's time_base
    3549. static AVRational duration_max(int64_t tmp, int64_t *duration, AVRational tmp_time_base,
    3550. AVRational time_base)
    3551. {
    3552. int ret;
    3553. if (!*duration) {
    3554. *duration = tmp;
    3555. return tmp_time_base;
    3556. }
    3557. ret = av_compare_ts(*duration, time_base, tmp, tmp_time_base);
    3558. if (ret < 0) {
    3559. *duration = tmp;
    3560. return tmp_time_base;
    3561. }
    3562. return time_base;
    3563. }
    3564. static int seek_to_start(InputFile *ifile, AVFormatContext *is)
    3565. {
    3566. InputStream *ist;
    3567. AVCodecContext *avctx;
    3568. int i, ret, has_audio = 0;
    3569. int64_t duration = 0;
    3570. ret = av_seek_frame(is, -1, is->start_time, 0);
    3571. if (ret < 0)
    3572. return ret;
    3573. for (i = 0; i < ifile->nb_streams; i++) {
    3574. ist = input_streams[ifile->ist_index + i];
    3575. avctx = ist->dec_ctx;
    3576. // flush decoders
    3577. if (ist->decoding_needed) {
    3578. process_input_packet(ist, NULL, 1);
    3579. avcodec_flush_buffers(avctx);
    3580. }
    3581. /* duration is the length of the last frame in a stream
    3582. * when audio stream is present we don't care about
    3583. * last video frame length because it's not defined exactly */
    3584. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples)
    3585. has_audio = 1;
    3586. }
    3587. for (i = 0; i < ifile->nb_streams; i++) {
    3588. ist = input_streams[ifile->ist_index + i];
    3589. avctx = ist->dec_ctx;
    3590. if (has_audio) {
    3591. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples) {
    3592. AVRational sample_rate = {1, avctx->sample_rate};
    3593. duration = av_rescale_q(ist->nb_samples, sample_rate, ist->st->time_base);
    3594. } else
    3595. continue;
    3596. } else {
    3597. if (ist->framerate.num) {
    3598. duration = av_rescale_q(1, ist->framerate, ist->st->time_base);
    3599. } else if (ist->st->avg_frame_rate.num) {
    3600. duration = av_rescale_q(1, ist->st->avg_frame_rate, ist->st->time_base);
    3601. } else duration = 1;
    3602. }
    3603. if (!ifile->duration)
    3604. ifile->time_base = ist->st->time_base;
    3605. /* the total duration of the stream, max_pts - min_pts is
    3606. * the duration of the stream without the last frame */
    3607. duration += ist->max_pts - ist->min_pts;
    3608. ifile->time_base = duration_max(duration, &ifile->duration, ist->st->time_base,
    3609. ifile->time_base);
    3610. }
    3611. if (ifile->loop > 0)
    3612. ifile->loop--;
    3613. return ret;
    3614. }
    3615. /*
    3616. * Return
    3617. * - 0 -- one packet was read and processed
    3618. * - AVERROR(EAGAIN) -- no packets were available for selected file,
    3619. * this function should be called again
    3620. * - AVERROR_EOF -- this function should not be called again
    3621. */
    3622. static int process_input(int file_index)
    3623. {
    3624. InputFile *ifile = input_files[file_index];
    3625. AVFormatContext *is;
    3626. InputStream *ist;
    3627. AVPacket pkt;
    3628. int ret, i, j;
    3629. int64_t duration;
    3630. int64_t pkt_dts;
    3631. is = ifile->ctx;
    3632. ret = get_input_packet(ifile, &pkt);
    3633. if (ret == AVERROR(EAGAIN)) {
    3634. ifile->eagain = 1;
    3635. return ret;
    3636. }
    3637. if (ret < 0 && ifile->loop) {
    3638. if ((ret = seek_to_start(ifile, is)) < 0)
    3639. return ret;
    3640. ret = get_input_packet(ifile, &pkt);
    3641. if (ret == AVERROR(EAGAIN)) {
    3642. ifile->eagain = 1;
    3643. return ret;
    3644. }
    3645. }
    3646. if (ret < 0) {
    3647. if (ret != AVERROR_EOF) {
    3648. print_error(is->filename, ret);
    3649. if (exit_on_error)
    3650. exit_program(1);
    3651. }
    3652. for (i = 0; i < ifile->nb_streams; i++) {
    3653. ist = input_streams[ifile->ist_index + i];
    3654. if (ist->decoding_needed) {
    3655. ret = process_input_packet(ist, NULL, 0);
    3656. if (ret>0)
    3657. return 0;
    3658. }
    3659. /* mark all outputs that don't go through lavfi as finished */
    3660. for (j = 0; j < nb_output_streams; j++) {
    3661. OutputStream *ost = output_streams[j];
    3662. if (ost->source_index == ifile->ist_index + i &&
    3663. (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
    3664. finish_output_stream(ost);
    3665. }
    3666. }
    3667. ifile->eof_reached = 1;
    3668. return AVERROR(EAGAIN);
    3669. }
    3670. reset_eagain();
    3671. if (do_pkt_dump) {
    3672. av_pkt_dump_log2(NULL, AV_LOG_INFO, &pkt, do_hex_dump,
    3673. is->streams[pkt.stream_index]);
    3674. }
    3675. /* the following test is needed in case new streams appear
    3676. dynamically in stream : we ignore them */
    3677. if (pkt.stream_index >= ifile->nb_streams) {
    3678. report_new_stream(file_index, &pkt);
    3679. goto discard_packet;
    3680. }
    3681. ist = input_streams[ifile->ist_index + pkt.stream_index];
    3682. ist->data_size += pkt.size;
    3683. ist->nb_packets++;
    3684. if (ist->discard)
    3685. goto discard_packet;
    3686. if (exit_on_error && (pkt.flags & AV_PKT_FLAG_CORRUPT)) {
    3687. av_log(NULL, AV_LOG_FATAL, "%s: corrupt input packet in stream %d\n", is->filename, pkt.stream_index);
    3688. exit_program(1);
    3689. }
    3690. if (debug_ts) {
    3691. av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
    3692. "next_dts:%s next_dts_time:%s next_pts:%s next_pts_time:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",
    3693. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
    3694. av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
    3695. av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
    3696. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
    3697. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
    3698. av_ts2str(input_files[ist->file_index]->ts_offset),
    3699. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
    3700. }
    3701. if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
    3702. int64_t stime, stime2;
    3703. // Correcting starttime based on the enabled streams
    3704. // FIXME this ideally should be done before the first use of starttime but we do not know which are the enabled streams at that point.
    3705. // so we instead do it here as part of discontinuity handling
    3706. if ( ist->next_dts == AV_NOPTS_VALUE
    3707. && ifile->ts_offset == -is->start_time
    3708. && (is->iformat->flags & AVFMT_TS_DISCONT)) {
    3709. int64_t new_start_time = INT64_MAX;
    3710. for (i=0; inb_streams; i++) {
    3711. AVStream *st = is->streams[i];
    3712. if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
    3713. continue;
    3714. new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
    3715. }
    3716. if (new_start_time > is->start_time) {
    3717. av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
    3718. ifile->ts_offset = -new_start_time;
    3719. }
    3720. }
    3721. stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
    3722. stime2= stime + (1ULL<st->pts_wrap_bits);
    3723. ist->wrap_correction_done = 1;
    3724. if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
    3725. pkt.dts -= 1ULL<st->pts_wrap_bits;
    3726. ist->wrap_correction_done = 0;
    3727. }
    3728. if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
    3729. pkt.pts -= 1ULL<st->pts_wrap_bits;
    3730. ist->wrap_correction_done = 0;
    3731. }
    3732. }
    3733. /* add the stream-global side data to the first packet */
    3734. if (ist->nb_packets == 1) {
    3735. for (i = 0; i < ist->st->nb_side_data; i++) {
    3736. AVPacketSideData *src_sd = &ist->st->side_data[i];
    3737. uint8_t *dst_data;
    3738. if (src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
    3739. continue;
    3740. if (av_packet_get_side_data(&pkt, src_sd->type, NULL))
    3741. continue;
    3742. dst_data = av_packet_new_side_data(&pkt, src_sd->type, src_sd->size);
    3743. if (!dst_data)
    3744. exit_program(1);
    3745. memcpy(dst_data, src_sd->data, src_sd->size);
    3746. }
    3747. }
    3748. if (pkt.dts != AV_NOPTS_VALUE)
    3749. pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
    3750. if (pkt.pts != AV_NOPTS_VALUE)
    3751. pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
    3752. if (pkt.pts != AV_NOPTS_VALUE)
    3753. pkt.pts *= ist->ts_scale;
    3754. if (pkt.dts != AV_NOPTS_VALUE)
    3755. pkt.dts *= ist->ts_scale;
    3756. pkt_dts = av_rescale_q_rnd(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
    3757. if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
    3758. ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
    3759. pkt_dts != AV_NOPTS_VALUE && ist->next_dts == AV_NOPTS_VALUE && !copy_ts
    3760. && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->last_ts != AV_NOPTS_VALUE) {
    3761. int64_t delta = pkt_dts - ifile->last_ts;
    3762. if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
    3763. delta > 1LL*dts_delta_threshold*AV_TIME_BASE){
    3764. ifile->ts_offset -= delta;
    3765. av_log(NULL, AV_LOG_DEBUG,
    3766. "Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
    3767. delta, ifile->ts_offset);
    3768. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
    3769. if (pkt.pts != AV_NOPTS_VALUE)
    3770. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
    3771. }
    3772. }
    3773. duration = av_rescale_q(ifile->duration, ifile->time_base, ist->st->time_base);
    3774. if (pkt.pts != AV_NOPTS_VALUE) {
    3775. pkt.pts += duration;
    3776. ist->max_pts = FFMAX(pkt.pts, ist->max_pts);
    3777. ist->min_pts = FFMIN(pkt.pts, ist->min_pts);
    3778. }
    3779. if (pkt.dts != AV_NOPTS_VALUE)
    3780. pkt.dts += duration;
    3781. pkt_dts = av_rescale_q_rnd(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
    3782. if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
    3783. ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
    3784. pkt_dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
    3785. !copy_ts) {
    3786. int64_t delta = pkt_dts - ist->next_dts;
    3787. if (is->iformat->flags & AVFMT_TS_DISCONT) {
    3788. if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
    3789. delta > 1LL*dts_delta_threshold*AV_TIME_BASE ||
    3790. pkt_dts + AV_TIME_BASE/10 < FFMAX(ist->pts, ist->dts)) {
    3791. ifile->ts_offset -= delta;
    3792. av_log(NULL, AV_LOG_DEBUG,
    3793. "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
    3794. delta, ifile->ts_offset);
    3795. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
    3796. if (pkt.pts != AV_NOPTS_VALUE)
    3797. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
    3798. }
    3799. } else {
    3800. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
    3801. delta > 1LL*dts_error_threshold*AV_TIME_BASE) {
    3802. av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
    3803. pkt.dts = AV_NOPTS_VALUE;
    3804. }
    3805. if (pkt.pts != AV_NOPTS_VALUE){
    3806. int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
    3807. delta = pkt_pts - ist->next_dts;
    3808. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
    3809. delta > 1LL*dts_error_threshold*AV_TIME_BASE) {
    3810. av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
    3811. pkt.pts = AV_NOPTS_VALUE;
    3812. }
    3813. }
    3814. }
    3815. }
    3816. if (pkt.dts != AV_NOPTS_VALUE)
    3817. ifile->last_ts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
    3818. if (debug_ts) {
    3819. av_log(NULL, AV_LOG_INFO, "demuxer+ffmpeg -> ist_index:%d type:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",
    3820. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
    3821. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
    3822. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
    3823. av_ts2str(input_files[ist->file_index]->ts_offset),
    3824. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
    3825. }
    3826. sub2video_heartbeat(ist, pkt.pts);
    3827. process_input_packet(ist, &pkt, 0);
    3828. discard_packet:
    3829. av_packet_unref(&pkt);
    3830. return 0;
    3831. }
    3832. /**
    3833. * Perform a step of transcoding for the specified filter graph.
    3834. *
    3835. * @param[in] graph filter graph to consider
    3836. * @param[out] best_ist input stream where a frame would allow to continue
    3837. * @return 0 for success, <0 for error
    3838. */
    3839. static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
    3840. {
    3841. int i, ret;
    3842. int nb_requests, nb_requests_max = 0;
    3843. InputFilter *ifilter;
    3844. InputStream *ist;
    3845. *best_ist = NULL;
    3846. ret = avfilter_graph_request_oldest(graph->graph);
    3847. if (ret >= 0)
    3848. return reap_filters(0);
    3849. if (ret == AVERROR_EOF) {
    3850. ret = reap_filters(1);
    3851. for (i = 0; i < graph->nb_outputs; i++)
    3852. close_output_stream(graph->outputs[i]->ost);
    3853. return ret;
    3854. }
    3855. if (ret != AVERROR(EAGAIN))
    3856. return ret;
    3857. for (i = 0; i < graph->nb_inputs; i++) {
    3858. ifilter = graph->inputs[i];
    3859. ist = ifilter->ist;
    3860. if (input_files[ist->file_index]->eagain ||
    3861. input_files[ist->file_index]->eof_reached)
    3862. continue;
    3863. nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
    3864. if (nb_requests > nb_requests_max) {
    3865. nb_requests_max = nb_requests;
    3866. *best_ist = ist;
    3867. }
    3868. }
    3869. if (!*best_ist)
    3870. for (i = 0; i < graph->nb_outputs; i++)
    3871. graph->outputs[i]->ost->unavailable = 1;
    3872. return 0;
    3873. }
    3874. /**
    3875. * Run a single step of transcoding.
    3876. *
    3877. * @return 0 for success, <0 for error
    3878. */
    3879. static int transcode_step(void)
    3880. {
    3881. OutputStream *ost;
    3882. InputStream *ist = NULL;
    3883. int ret;
    3884. ost = choose_output();
    3885. if (!ost) {
    3886. if (got_eagain()) {
    3887. reset_eagain();
    3888. av_usleep(10000);
    3889. return 0;
    3890. }
    3891. av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
    3892. return AVERROR_EOF;
    3893. }
    3894. if (ost->filter && !ost->filter->graph->graph) {
    3895. if (ifilter_has_all_input_formats(ost->filter->graph)) {
    3896. ret = configure_filtergraph(ost->filter->graph);
    3897. if (ret < 0) {
    3898. av_log(NULL, AV_LOG_ERROR, "Error reinitializing filters!\n");
    3899. return ret;
    3900. }
    3901. }
    3902. }
    3903. if (ost->filter && ost->filter->graph->graph) {
    3904. if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
    3905. return ret;
    3906. if (!ist)
    3907. return 0;
    3908. } else if (ost->filter) {
    3909. int i;
    3910. for (i = 0; i < ost->filter->graph->nb_inputs; i++) {
    3911. InputFilter *ifilter = ost->filter->graph->inputs[i];
    3912. if (!ifilter->ist->got_output && !input_files[ifilter->ist->file_index]->eof_reached) {
    3913. ist = ifilter->ist;
    3914. break;
    3915. }
    3916. }
    3917. if (!ist) {
    3918. ost->inputs_done = 1;
    3919. return 0;
    3920. }
    3921. } else {
    3922. av_assert0(ost->source_index >= 0);
    3923. ist = input_streams[ost->source_index];
    3924. }
    3925. ret = process_input(ist->file_index);
    3926. if (ret == AVERROR(EAGAIN)) {
    3927. if (input_files[ist->file_index]->eagain)
    3928. ost->unavailable = 1;
    3929. return 0;
    3930. }
    3931. if (ret < 0)
    3932. return ret == AVERROR_EOF ? 0 : ret;
    3933. return reap_filters(0);
    3934. }
    3935. /*
    3936. * The following code is the main loop of the file converter
    3937. */
    3938. static int transcode(void(call_back)(int current,int total))
    3939. {
    3940. int ret, i;
    3941. AVFormatContext *os;
    3942. OutputStream *ost;
    3943. InputStream *ist;
    3944. int64_t timer_start;
    3945. int64_t total_packets_written = 0;
    3946. ret = transcode_init();
    3947. if (ret < 0)
    3948. goto fail;
    3949. if (stdin_interaction) {
    3950. av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
    3951. }
    3952. timer_start = av_gettime_relative();
    3953. #if HAVE_PTHREADS
    3954. if ((ret = init_input_threads()) < 0)
    3955. goto fail;
    3956. #endif
    3957. while (!received_sigterm) {
    3958. int64_t cur_time= av_gettime_relative();
    3959. /* if 'q' pressed, exits */
    3960. if (stdin_interaction)
    3961. if (check_keyboard_interaction(cur_time) < 0)
    3962. break;
    3963. /* check if there's any stream where output is still needed */
    3964. if (!need_output()) {
    3965. av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
    3966. break;
    3967. }
    3968. ret = transcode_step();
    3969. if (ret < 0 && ret != AVERROR_EOF) {
    3970. char errbuf[128];
    3971. av_strerror(ret, errbuf, sizeof(errbuf));
    3972. av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
    3973. break;
    3974. }
    3975. /* dump report by using the output first video and audio streams */
    3976. print_report(0, timer_start, cur_time,call_back);
    3977. }
    3978. #if HAVE_PTHREADS
    3979. free_input_threads();
    3980. #endif
    3981. /* at the end of stream, we must flush the decoder buffers */
    3982. for (i = 0; i < nb_input_streams; i++) {
    3983. ist = input_streams[i];
    3984. if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
    3985. process_input_packet(ist, NULL, 0);
    3986. }
    3987. }
    3988. flush_encoders();
    3989. term_exit();
    3990. /* write the trailer if needed and close file */
    3991. for (i = 0; i < nb_output_files; i++) {
    3992. os = output_files[i]->ctx;
    3993. if (!output_files[i]->header_written) {
    3994. av_log(NULL, AV_LOG_ERROR,
    3995. "Nothing was written into output file %d (%s), because "
    3996. "at least one of its streams received no packets.\n",
    3997. i, os->filename);
    3998. continue;
    3999. }
    4000. if ((ret = av_write_trailer(os)) < 0) {
    4001. av_log(NULL, AV_LOG_ERROR, "Error writing trailer of %s: %s\n", os->filename, av_err2str(ret));
    4002. if (exit_on_error)
    4003. exit_program(1);
    4004. }
    4005. }
    4006. /* dump report by using the first video and audio streams */
    4007. print_report(1, timer_start, av_gettime_relative(),call_back);
    4008. /* close each encoder */
    4009. for (i = 0; i < nb_output_streams; i++) {
    4010. ost = output_streams[i];
    4011. if (ost->encoding_needed) {
    4012. av_freep(&ost->enc_ctx->stats_in);
    4013. }
    4014. total_packets_written += ost->packets_written;
    4015. }
    4016. if (!total_packets_written && (abort_on_flags & ABORT_ON_FLAG_EMPTY_OUTPUT)) {
    4017. av_log(NULL, AV_LOG_FATAL, "Empty output\n");
    4018. exit_program(1);
    4019. }
    4020. /* close each decoder */
    4021. for (i = 0; i < nb_input_streams; i++) {
    4022. ist = input_streams[i];
    4023. if (ist->decoding_needed) {
    4024. avcodec_close(ist->dec_ctx);
    4025. if (ist->hwaccel_uninit)
    4026. ist->hwaccel_uninit(ist->dec_ctx);
    4027. }
    4028. }
    4029. av_buffer_unref(&hw_device_ctx);
    4030. /* finished ! */
    4031. ret = 0;
    4032. fail:
    4033. #if HAVE_PTHREADS
    4034. free_input_threads();
    4035. #endif
    4036. if (output_streams) {
    4037. for (i = 0; i < nb_output_streams; i++) {
    4038. ost = output_streams[i];
    4039. if (ost) {
    4040. if (ost->logfile) {
    4041. if (fclose(ost->logfile))
    4042. av_log(NULL, AV_LOG_ERROR,
    4043. "Error closing logfile, loss of information possible: %s\n",
    4044. av_err2str(AVERROR(errno)));
    4045. ost->logfile = NULL;
    4046. }
    4047. av_freep(&ost->forced_kf_pts);
    4048. av_freep(&ost->apad);
    4049. av_freep(&ost->disposition);
    4050. av_dict_free(&ost->encoder_opts);
    4051. av_dict_free(&ost->sws_dict);
    4052. av_dict_free(&ost->swr_opts);
    4053. av_dict_free(&ost->resample_opts);
    4054. }
    4055. }
    4056. }
    4057. return ret;
    4058. }
    4059. static int64_t getutime(void)
    4060. {
    4061. #if HAVE_GETRUSAGE
    4062. struct rusage rusage;
    4063. getrusage(RUSAGE_SELF, &rusage);
    4064. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
    4065. #elif HAVE_GETPROCESSTIMES
    4066. HANDLE proc;
    4067. FILETIME c, e, k, u;
    4068. proc = GetCurrentProcess();
    4069. GetProcessTimes(proc, &c, &e, &k, &u);
    4070. return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
    4071. #else
    4072. return av_gettime_relative();
    4073. #endif
    4074. }
    4075. static int64_t getmaxrss(void)
    4076. {
    4077. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
    4078. struct rusage rusage;
    4079. getrusage(RUSAGE_SELF, &rusage);
    4080. return (int64_t)rusage.ru_maxrss * 1024;
    4081. #elif HAVE_GETPROCESSMEMORYINFO
    4082. HANDLE proc;
    4083. PROCESS_MEMORY_COUNTERS memcounters;
    4084. proc = GetCurrentProcess();
    4085. memcounters.cb = sizeof(memcounters);
    4086. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
    4087. return memcounters.PeakPagefileUsage;
    4088. #else
    4089. return 0;
    4090. #endif
    4091. }
    4092. static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
    4093. {
    4094. }
    4095. //命令函数的入口
    4096. int run_ffmpeg_command(int argc, char **argv,void(call_back)(int current,int total))
    4097. {
    4098. int i, ret;
    4099. int64_t ti;
    4100. init_dynload();
    4101. register_exit(ffmpeg_cleanup);
    4102. setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
    4103. av_log_set_flags(AV_LOG_SKIP_REPEATED);
    4104. parse_loglevel(argc, argv, options);
    4105. if(argc>1 && !strcmp(argv[1], "-d")){
    4106. run_as_daemon=1;
    4107. av_log_set_callback(log_callback_null);
    4108. argc--;
    4109. argv++;
    4110. }
    4111. avcodec_register_all();
    4112. #if CONFIG_AVDEVICE
    4113. avdevice_register_all();
    4114. #endif
    4115. avfilter_register_all();
    4116. av_register_all();
    4117. avformat_network_init();
    4118. show_banner(argc, argv, options);
    4119. /* parse options and open all input/output files */
    4120. ret = ffmpeg_parse_options(argc, argv);
    4121. if (ret < 0)
    4122. exit_program(1);
    4123. if (nb_output_files <= 0 && nb_input_files == 0) {
    4124. show_usage();
    4125. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
    4126. exit_program(1);
    4127. }
    4128. /* file converter / grab */
    4129. if (nb_output_files <= 0) {
    4130. av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
    4131. exit_program(1);
    4132. }
    4133. // if (nb_input_files == 0) {
    4134. // av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
    4135. // exit_program(1);
    4136. // }
    4137. for (i = 0; i < nb_output_files; i++) {
    4138. if (strcmp(output_files[i]->ctx->oformat->name, "rtp"))
    4139. want_sdp = 0;
    4140. }
    4141. current_time = ti = getutime();
    4142. if (transcode(call_back) < 0)
    4143. exit_program(1);
    4144. ti = getutime() - ti;
    4145. if (do_benchmark) {
    4146. av_log(NULL, AV_LOG_INFO, "bench: utime=%0.3fs\n", ti / 1000000.0);
    4147. }
    4148. av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
    4149. decode_error_stat[0], decode_error_stat[1]);
    4150. if ((decode_error_stat[0] + decode_error_stat[1]) * max_error_rate < decode_error_stat[1])
    4151. exit_program(69);
    4152. //注释掉此行代码 如果不注释掉该行代码,命令执行完会导致app退出
    4153. //exit_program(received_nb_signals ? 255 : main_return_code);
    4154. //添加如下代码如果不添加再次执行run_ffmpeg_command 直接崩溃 因为没有赋初始值
    4155. nb_filtergraphs = 0;
    4156. nb_input_streams = 0;
    4157. nb_input_files = 0;
    4158. progress_avio = NULL;
    4159. input_streams = NULL;
    4160. nb_input_streams = 0;
    4161. input_files = NULL;
    4162. nb_input_files = 0;
    4163. output_streams = NULL;
    4164. nb_output_streams = 0;
    4165. output_files = NULL;
    4166. nb_output_files = 0;
    4167. return main_return_code;
    4168. }

    修改native-lib.cpp内容

     

     native-lib.cpp内容如下:

    1. #include
    2. #include
    3. #include
    4. #define TAG "JNI_TAG"
    5. #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG,__VA_ARGS__);
    6. extern "C" {
    7. #include "libavutil/avutil.h"
    8. //声明方法 argc命令的个数 argv 二维数组
    9. int run_ffmpeg_command(int argc, char **argv,void(call_back)(int current,int total));
    10. //回调函数
    11. static jobject call_back_jobj;//call_back_jobj 对应于VideoCompress类中的CompressCallback
    12. static JNIEnv *myEnv;
    13. void call_back(int current,int total){
    14. //LOGE("压缩进度:%d/%d",current,total);
    15. //把进度回调出去,对象是jobject callback
    16. if(myEnv!=NULL&&call_back_jobj!=NULL){
    17. //获取j_mid是会被多次执行
    18. jclass j_clazz=myEnv->GetObjectClass(call_back_jobj);
    19. //方法 onCompress对象的方法名 对应VideoCompress类中的CompressCallback接口的onCompress方法
    20. //(II)V(方法签名 利用javap命令也能打印) --(public void onCompress(int current,int total);onCompress的两个参数都为int类型 onCompress方法的返回值为void)
    21. jmethodID j_mid=myEnv->GetMethodID(j_clazz,"onCompress","(II)V");
    22. //调用对象的方法 如果写CallObjectMethod报错,因为知道是无返回值的方法,所以改成CallVoidMethod
    23. myEnv->CallVoidMethod(call_back_jobj,j_mid,current,total);
    24. }
    25. }
    26. }
    27. extern "C" JNIEXPORT jstring JNICALL
    28. Java_com_suoer_ndk_ffmpegtestapplication_MainActivity_stringFromJNI(
    29. JNIEnv* env,
    30. jobject /* this */) {
    31. //std::string hello = "Hello from C++";
    32. return env->NewStringUTF(av_version_info());
    33. }extern "C"
    34. JNIEXPORT void JNICALL
    35. Java_com_suoer_ndk_ffmpegtestapplication_VideoCompress_compressVideo(JNIEnv *env, jobject thiz,
    36. jobjectArray compress_command,
    37. jobject callback) {
    38. myEnv=env;
    39. call_back_jobj=env->NewGlobalRef(callback);
    40. //ffmpeg 处理视频压缩
    41. //arm这个里面的so都是用来处理音视频的,include都是头文件
    42. //还有几个没有被打包编译成so,因为这些不算是音视频的处理代码,只是我们现在支持命令(封装)
    43. //1.获取命令个数
    44. int argc=env->GetArrayLength(compress_command);
    45. //2.给char **argv填充数据
    46. char **argv=(char **)malloc(sizeof(char*)*argc);
    47. for (int i = 0; i
    48. jstring j_param=(jstring)env->GetObjectArrayElement(compress_command,i);
    49. argv[i]= (char *)(env->GetStringUTFChars(j_param, NULL));
    50. LOGE("参数:%s",argv[i]);
    51. }
    52. //3.调用命令函数去压缩
    53. run_ffmpeg_command(argc,argv,call_back);
    54. //4.释放内存
    55. for (int i = 0; i
    56. free(argv[i]);
    57. }
    58. free(argv);
    59. env->DeleteGlobalRef(call_back_jobj);
    60. }

    5.MainActivity界面优化处理

    首先需要把assets目录中的test.mp4放置手机中

     

     修改MainActivity内容:

    压缩之前首先判断压缩后的文件out.mp4是否存在,如果已经存在,则删除此文件。如果压缩文件已经存在再次压缩会导致崩溃。

     

     

    压缩过程中展示进度条,压缩过程中不允许再次点击压缩按钮

     

    进度弹窗背景: bg_4radius.xml

    1. "1.0" encoding="utf-8"?>
    2. <selector xmlns:android="http://schemas.android.com/apk/res/android">
    3. <item>
    4. <shape android:shape="rectangle">
    5. <solid android:color="@color/white" />
    6. <corners android:topLeftRadius="4dp" android:topRightRadius="4dp" android:bottomLeftRadius="4dp" android:bottomRightRadius="4dp"/>
    7. shape>
    8. item>
    9. selector>

    进度条进度背景:compress_progressbar.xml

    1. "1.0" encoding="utf-8"?>
    2. <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    3. <item android:id="@android:id/background">
    4. <shape>
    5. <corners android:radius="6dp" />
    6. <solid android:color="#ffeeeeee">solid>
    7. shape>
    8. item>
    9. <item android:id="@android:id/secondaryProgress">
    10. <clip>
    11. <shape>
    12. <corners android:radius="6dp" />
    13. <gradient
    14. android:type="linear"
    15. android:useLevel="true"
    16. android:angle="270"
    17. android:endColor="@color/purple_500"
    18. android:startColor="@color/purple_200" />
    19. shape>
    20. clip>
    21. item>
    22. <item android:id="@android:id/progress">
    23. <clip>
    24. <shape>
    25. <corners android:radius="6dp" />
    26. <gradient
    27. android:type="linear"
    28. android:useLevel="true"
    29. android:angle="270"
    30. android:endColor="@color/purple_500"
    31. android:startColor="@color/purple_200" />
    32. shape>
    33. clip>
    34. item>
    35. layer-list>

    进度弹窗布局文件dialog_progress.xml

    1. "1.0" encoding="utf-8"?>
    2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. android:layout_width="wrap_content"
    4. android:layout_height="320dp"
    5. android:layout_gravity="center"
    6. android:background="@drawable/bg_4radius">
    7. <RelativeLayout
    8. android:layout_width="match_parent"
    9. android:layout_height="match_parent"
    10. >
    11. <LinearLayout
    12. android:layout_centerInParent="true"
    13. android:layout_width="match_parent"
    14. android:layout_height="wrap_content"
    15. android:gravity="center_horizontal"
    16. android:orientation="vertical">
    17. <TextView
    18. android:id="@+id/tv_dialog_compress_progress"
    19. android:layout_width="wrap_content"
    20. android:layout_height="wrap_content"
    21. android:textColor="@color/purple_500"
    22. android:textSize="24sp" />
    23. <ProgressBar
    24. android:id="@+id/compress_progressbar"
    25. android:layout_marginLeft="40dp"
    26. android:layout_marginRight="40dp"
    27. style="?android:attr/progressBarStyleHorizontal"
    28. android:layout_width="match_parent"
    29. android:max="100"
    30. android:min="0"
    31. android:progressDrawable="@drawable/compress_progressbar"
    32. android:layout_height="12dp" />
    33. <TextView
    34. android:layout_marginBottom="20dp"
    35. android:text="视频正在压缩,请稍等…"
    36. android:layout_marginTop="40dp"
    37. android:textSize="14sp"
    38. android:textColor="#CCCCCC"
    39. android:layout_width="wrap_content"
    40. android:layout_height="wrap_content" />
    41. LinearLayout>
    42. RelativeLayout>
    43. RelativeLayout>

    弹窗样式styles.xml

    1. "1.0" encoding="utf-8"?>
    2. <resources>
    3. <style name="normal_dialog" parent="android:Theme.Dialog">
    4. <item name="android:background">@android:color/transparentitem>
    5. <item name="android:windowBackground">@android:color/transparentitem>
    6. <item name="android:windowNoTitle">trueitem>
    7. <item name="android:backgroundDimAmount">0.8item>
    8. style>
    9. resources>

    弹窗ProgressDialog.java

    1. package com.suoer.ndk.ffmpegtestapplication;
    2. import android.app.Dialog;
    3. import android.content.Context;
    4. import android.widget.ProgressBar;
    5. import android.widget.TextView;
    6. import androidx.annotation.NonNull;
    7. public class ProgressDialog extends Dialog {
    8. private TextView tvProgress;
    9. private ProgressBar compress_progressbar;
    10. public ProgressDialog(@NonNull Context context) {
    11. this(context, R.style.normal_dialog);
    12. setContentView(R.layout.dialog_progress);
    13. tvProgress = findViewById(R.id.tv_dialog_compress_progress);
    14. compress_progressbar =findViewById(R.id.compress_progressbar);
    15. }
    16. private ProgressDialog(@NonNull Context context, int themeResId) {
    17. super(context, themeResId);
    18. }
    19. public void setProgress(int progress) {
    20. if (progress < 0) {
    21. progress = 0;
    22. } else if (progress > 100) {
    23. progress = 100;
    24. }
    25. tvProgress.setText(progress + "%");
    26. compress_progressbar.setProgress(progress);
    27. }
    28. }

    最终的MainActivity.java

    1. package com.suoer.ndk.ffmpegtestapplication;
    2. import android.Manifest;
    3. import android.os.Bundle;
    4. import android.os.Environment;
    5. import android.util.Log;
    6. import android.view.View;
    7. import android.widget.TextView;
    8. import android.widget.Toast;
    9. import com.tbruyelle.rxpermissions3.RxPermissions;
    10. import java.io.File;
    11. import androidx.appcompat.app.AppCompatActivity;
    12. import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
    13. import io.reactivex.rxjava3.core.Observable;
    14. import io.reactivex.rxjava3.functions.Consumer;
    15. import io.reactivex.rxjava3.functions.Function;
    16. import io.reactivex.rxjava3.schedulers.Schedulers;
    17. public class MainActivity extends AppCompatActivity {
    18. private File mInFile=new File(Environment.getExternalStorageDirectory(),"test.mp4");//mInFile 需要压缩的文件路径
    19. private File mOutFile=new File(Environment.getExternalStorageDirectory(),"out.mp4");//mOutFile压缩后的文件路径
    20. private ProgressDialog mProgressDialog;//进度弹窗
    21. // Used to load the 'native-lib' library on application startup.
    22. static {
    23. System.loadLibrary("native-lib");
    24. }
    25. @Override
    26. protected void onCreate(Bundle savedInstanceState) {
    27. super.onCreate(savedInstanceState);
    28. setContentView(R.layout.activity_main);
    29. if (mProgressDialog == null) {
    30. mProgressDialog = new ProgressDialog(this);
    31. }
    32. mProgressDialog.setCancelable(false);
    33. mProgressDialog.setProgress(0);
    34. // Example of a call to a native method
    35. TextView tv = findViewById(R.id.sample_text);
    36. //tv.setText("ffmpeg版本:"+stringFromJNI());
    37. tv.setText("压缩");
    38. //tv的点击事件 点击按钮实现视频压缩
    39. tv.setOnClickListener(new View.OnClickListener() {
    40. @Override
    41. public void onClick(View v) {
    42. // 压缩文件 需要读写文件权限 申请权限
    43. RxPermissions rxPermissions=new RxPermissions(MainActivity.this);
    44. rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Consumer() {
    45. @Override
    46. public void accept(Boolean aBoolean) throws Throwable {
    47. if(aBoolean){
    48. //权限已经获取 压缩视频
    49. //如果手机中不存在test.mp4的文件则提示
    50. if(!mInFile.exists()){
    51. Toast.makeText(MainActivity.this,"请把assert目录中的test.mp4拷贝至手机中!",Toast.LENGTH_LONG).show();
    52. return;
    53. }
    54. if(mOutFile.exists()){
    55. mOutFile.delete();
    56. }
    57. compressVideo();
    58. }
    59. }
    60. });
    61. }
    62. });
    63. }
    64. /**
    65. * 开启子线程处理耗时压缩问题
    66. */
    67. private void compressVideo() {
    68. //ffmpeg的压缩命令:ffmpeg -i test.mp4 -b:v 1024k out.mp4
    69. //ffmpeg -i test.mp4 -b:v 1024k out.mp4
    70. //-b:v 1024k 1024k为码率 码率越高视频越清晰,而且视频越大
    71. //test.mp4需要压缩的文件
    72. //out.mp4 压缩之后的文件
    73. if(mProgressDialog!=null&&!mProgressDialog.isShowing()){
    74. mProgressDialog.show();
    75. }
    76. String[] compressCommand={"ffmpeg","-i",mInFile.getAbsolutePath(),"-b:v","1024k",mOutFile.getAbsolutePath()};
    77. //压缩是耗时的,需要子线程处理
    78. Observable.just(compressCommand).map(new Function() {
    79. @Override
    80. public File apply(String[] compressCommand) throws Throwable {
    81. //子线程
    82. VideoCompress videoCompress=new VideoCompress();
    83. videoCompress.compressVideo(compressCommand, new VideoCompress.CompressCallback() {
    84. @Override
    85. public void onCompress(int current, int total) {
    86. Log.e("TAG", "onCompress: 压缩进度:"+current+"/"+total);
    87. runOnUiThread(new Runnable() {
    88. @Override
    89. public void run() {
    90. if(mProgressDialog!=null){
    91. mProgressDialog.setProgress(100 * current / total);
    92. }
    93. }
    94. });
    95. }
    96. });
    97. return mOutFile;
    98. }
    99. }).subscribeOn(Schedulers.io())
    100. .observeOn(AndroidSchedulers.mainThread())
    101. .subscribe(new Consumer() {
    102. @Override
    103. public void accept(File file) throws Throwable {
    104. // 主线程 压缩完成
    105. Log.e("TAG", "accept: 压缩完成!" );
    106. if(mProgressDialog!=null){
    107. mProgressDialog.dismiss();
    108. }
    109. }
    110. });
    111. }
    112. /**
    113. * A native method that is implemented by the 'native-lib' native library,
    114. * which is packaged with this application.
    115. */
    116. public native String stringFromJNI();
    117. @Override
    118. protected void onDestroy() {
    119. super.onDestroy();
    120. if (mProgressDialog != null) {
    121. mProgressDialog.cancel();
    122. mProgressDialog = null;
    123. }
    124. }
    125. }

  • 相关阅读:
    Python实验项目6 :文件操作与模块化
    使用HTML制作一个端午赛龙舟小游戏
    python 获取下载文件的后缀
    IDEA 新建 Maven 项目没有文件结构 pom 文件为空 解决方法
    QT项目:网络聊天室
    springcloud - ribbon 饥饿加载
    云栖大会,未来万物皆是计算机?
    【AI应用探讨】—知识图谱(KG)应用场景
    MAC帧
    【U8+】用友U8+客户端登录账套的时候, 提示: 已成功与服务器建立连接,但是在登录过程中发生错误; 指定的网络名不再可用。
  • 原文地址:https://blog.csdn.net/Jushuzhan/article/details/126497340