示例#1
0
int
main(int argc, char **argv)
{
  int option;
  char *configfile;
  int background;
  int mdns_no_rsp;
  int mdns_no_daap;
  int loglevel;
  char *logdomains;
  char *logfile;
  char *ffid;
  char *pidfile;
  const char *gcry_version;
  sigset_t sigs;
  int sigfd;
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
  struct kevent ke_sigs[4];
#endif
  int ret;

  struct option option_map[] =
    {
      { "ffid",         1, NULL, 'b' },
      { "debug",        1, NULL, 'd' },
      { "logdomains",   1, NULL, 'D' },
      { "foreground",   0, NULL, 'f' },
      { "config",       1, NULL, 'c' },
      { "pidfile",      1, NULL, 'P' },
      { "version",      0, NULL, 'v' },

      { "mdns-no-rsp",  0, NULL, 512 },
      { "mdns-no-daap", 0, NULL, 513 },

      { NULL,           0, NULL, 0 }
    };

  configfile = CONFFILE;
  pidfile = PIDFILE;
  loglevel = -1;
  logdomains = NULL;
  logfile = NULL;
  background = 1;
  ffid = NULL;
  mdns_no_rsp = 0;
  mdns_no_daap = 0;

  while ((option = getopt_long(argc, argv, "D:d:c:P:fb:v", option_map, NULL)) != -1)
    {
      switch (option)
	{
	  case 512:
	    mdns_no_rsp = 1;
	    break;

	  case 513:
	    mdns_no_daap = 1;
	    break;

	  case 'b':
            ffid = optarg;
            break;

	  case 'd':
	    ret = safe_atoi32(optarg, &option);
	    if (ret < 0)
	      fprintf(stderr, "Error: loglevel must be an integer in '-d %s'\n", optarg);
	    else
	      loglevel = option;
            break;

	  case 'D':
	    logdomains = optarg;
            break;

          case 'f':
            background = 0;
            break;

          case 'c':
            configfile = optarg;
            break;

          case 'P':
	    pidfile = optarg;
            break;

          case 'v':
	    version();
            return EXIT_SUCCESS;
            break;

          default:
            usage(argv[0]);
            return EXIT_FAILURE;
            break;
        }
    }

  ret = logger_init(NULL, NULL, (loglevel < 0) ? E_LOG : loglevel);
  if (ret != 0)
    {
      fprintf(stderr, "Could not initialize log facility\n");

      return EXIT_FAILURE;
    }

  ret = conffile_load(configfile);
  if (ret != 0)
    {
      DPRINTF(E_FATAL, L_MAIN, "Config file errors; please fix your config\n");

      logger_deinit();
      return EXIT_FAILURE;
    }

  logger_deinit();

  /* Reinit log facility with configfile values */
  if (loglevel < 0)
    loglevel = cfg_getint(cfg_getsec(cfg, "general"), "loglevel");

  logfile = cfg_getstr(cfg_getsec(cfg, "general"), "logfile");

  ret = logger_init(logfile, logdomains, loglevel);
  if (ret != 0)
    {
      fprintf(stderr, "Could not reinitialize log facility with config file settings\n");

      conffile_unload();
      return EXIT_FAILURE;
    }

  /* Set up libevent logging callback */
  event_set_log_callback(logger_libevent);

  DPRINTF(E_LOG, L_MAIN, "Forked Media Server Version %s taking off\n", VERSION);

  /* Initialize ffmpeg */
  avcodec_init();

  ret = av_lockmgr_register(ffmpeg_lockmgr);
  if (ret < 0)
    {
      DPRINTF(E_FATAL, L_MAIN, "Could not register ffmpeg lock manager callback\n");

      ret = EXIT_FAILURE;
      goto ffmpeg_init_fail;
    }

  av_register_all();
  av_log_set_callback(logger_ffmpeg);
#if LIBAVFORMAT_VERSION_MAJOR < 53
  register_ffmpeg_evbuffer_url_protocol();
#endif

  /* Initialize libgcrypt */
  gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);

  gcry_version = gcry_check_version(GCRYPT_VERSION);
  if (!gcry_version)
    {
      DPRINTF(E_FATAL, L_MAIN, "libgcrypt version mismatch\n");

      ret = EXIT_FAILURE;
      goto gcrypt_init_fail;
    }

  /* We aren't handling anything sensitive, so give up on secure
   * memory, which is a scarce system resource.
   */
  gcry_control(GCRYCTL_DISABLE_SECMEM, 0);

  gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);

  DPRINTF(E_DBG, L_MAIN, "Initialized with gcrypt %s\n", gcry_version);

  /* Block signals for all threads except the main one */
  sigemptyset(&sigs);
  sigaddset(&sigs, SIGINT);
  sigaddset(&sigs, SIGHUP);
  sigaddset(&sigs, SIGCHLD);
  sigaddset(&sigs, SIGTERM);
  sigaddset(&sigs, SIGPIPE);
  ret = pthread_sigmask(SIG_BLOCK, &sigs, NULL);
  if (ret != 0)
    {
      DPRINTF(E_LOG, L_MAIN, "Error setting signal set\n");

      ret = EXIT_FAILURE;
      goto signal_block_fail;
    }

  /* Daemonize and drop privileges */
  ret = daemonize(background, pidfile);
  if (ret < 0)
    {
      DPRINTF(E_LOG, L_MAIN, "Could not initialize server\n");

      ret = EXIT_FAILURE;
      goto daemon_fail;
    }

  /* Initialize libevent (after forking) */
  evbase_main = event_init();

  DPRINTF(E_LOG, L_MAIN, "mDNS init\n");
  ret = mdns_init();
  if (ret != 0)
    {
      DPRINTF(E_FATAL, L_MAIN, "mDNS init failed\n");

      ret = EXIT_FAILURE;
      goto mdns_fail;
    }

  /* Initialize the database before starting */
  DPRINTF(E_INFO, L_MAIN, "Initializing database\n");
  ret = db_init();
  if (ret < 0)
    {
      DPRINTF(E_FATAL, L_MAIN, "Database init failed\n");

      ret = EXIT_FAILURE;
      goto db_fail;
    }

  /* Open a DB connection for the main thread */
  ret = db_perthread_init();
  if (ret < 0)
    {
      DPRINTF(E_FATAL, L_MAIN, "Could not perform perthread DB init for main\n");

      ret = EXIT_FAILURE;
      goto db_fail;
    }

  /* Spawn file scanner thread */
  ret = filescanner_init();
  if (ret != 0)
    {
      DPRINTF(E_FATAL, L_MAIN, "File scanner thread failed to start\n");

      ret = EXIT_FAILURE;
      goto filescanner_fail;
    }

  /* Spawn player thread */
  ret = player_init();
  if (ret != 0)
    {
      DPRINTF(E_FATAL, L_MAIN, "Player thread failed to start\n");

      ret = EXIT_FAILURE;
      goto player_fail;
    }

  /* Spawn HTTPd thread */
  ret = httpd_init();
  if (ret != 0)
    {
      DPRINTF(E_FATAL, L_MAIN, "HTTPd thread failed to start\n");

      ret = EXIT_FAILURE;
      goto httpd_fail;
    }

  /* Start Remote pairing service */
  ret = remote_pairing_init();
  if (ret != 0)
    {
      DPRINTF(E_FATAL, L_MAIN, "Remote pairing service failed to start\n");

      ret = EXIT_FAILURE;
      goto remote_fail;
    }

  /* Register mDNS services */
  ret = register_services(ffid, mdns_no_rsp, mdns_no_daap);
  if (ret < 0)
    {
      ret = EXIT_FAILURE;
      goto mdns_reg_fail;
    }

#if defined(__linux__)
  /* Set up signal fd */
  sigfd = signalfd(-1, &sigs, SFD_NONBLOCK | SFD_CLOEXEC);
  if (sigfd < 0)
    {
      DPRINTF(E_FATAL, L_MAIN, "Could not setup signalfd: %s\n", strerror(errno));

      ret = EXIT_FAILURE;
      goto signalfd_fail;
    }

  event_set(&sig_event, sigfd, EV_READ, signal_signalfd_cb, NULL);

#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
  sigfd = kqueue();
  if (sigfd < 0)
    {
      DPRINTF(E_FATAL, L_MAIN, "Could not setup kqueue: %s\n", strerror(errno));

      ret = EXIT_FAILURE;
      goto signalfd_fail;
    }

  EV_SET(&ke_sigs[0], SIGINT, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
  EV_SET(&ke_sigs[1], SIGTERM, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
  EV_SET(&ke_sigs[2], SIGHUP, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
  EV_SET(&ke_sigs[3], SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);

  ret = kevent(sigfd, ke_sigs, 4, NULL, 0, NULL);
  if (ret < 0)
    {
      DPRINTF(E_FATAL, L_MAIN, "Could not register signal events: %s\n", strerror(errno));

      ret = EXIT_FAILURE;
      goto signalfd_fail;
    }

  event_set(&sig_event, sigfd, EV_READ, signal_kqueue_cb, NULL);
#endif

  event_base_set(evbase_main, &sig_event);
  event_add(&sig_event, NULL);

  /* Run the loop */
  event_base_dispatch(evbase_main);

  DPRINTF(E_LOG, L_MAIN, "Stopping gracefully\n");
  ret = EXIT_SUCCESS;

  /*
   * On a clean shutdown, bring mDNS down first to give a chance
   * to the clients to perform a clean shutdown on their end
   */
  DPRINTF(E_LOG, L_MAIN, "mDNS deinit\n");
  mdns_deinit();

 signalfd_fail:
 mdns_reg_fail:
  DPRINTF(E_LOG, L_MAIN, "Remote pairing deinit\n");
  remote_pairing_deinit();

 remote_fail:
  DPRINTF(E_LOG, L_MAIN, "HTTPd deinit\n");
  httpd_deinit();

 httpd_fail:
  DPRINTF(E_LOG, L_MAIN, "Player deinit\n");
  player_deinit();

 player_fail:
  DPRINTF(E_LOG, L_MAIN, "File scanner deinit\n");
  filescanner_deinit();

 filescanner_fail:
  DPRINTF(E_LOG, L_MAIN, "Database deinit\n");
  db_perthread_deinit();
  db_deinit();
 db_fail:
  if (ret == EXIT_FAILURE)
    {
      DPRINTF(E_LOG, L_MAIN, "mDNS deinit\n");
      mdns_deinit();
    }

 mdns_fail:
 daemon_fail:
  if (background)
    {
      ret = seteuid(0);
      if (ret < 0)
	DPRINTF(E_LOG, L_MAIN, "seteuid() failed: %s\n", strerror(errno));
      else
	{
	  ret = unlink(pidfile);
	  if (ret < 0)
	    DPRINTF(E_LOG, L_MAIN, "Could not unlink PID file %s: %s\n", pidfile, strerror(errno));
	}
    }

 signal_block_fail:
 gcrypt_init_fail:
  av_lockmgr_register(NULL);

 ffmpeg_init_fail:
  DPRINTF(E_LOG, L_MAIN, "Exiting.\n");
  conffile_unload();
  logger_deinit();

  return ret;
}
示例#2
0
void init_dumper( int width, int height )
{  
  double fps = Machine->drv->frames_per_second / (double)frame_halver;

  avcodec_init();
  avcodec_register_all();
#ifdef AVICAPTURE_DEBUG
  av_log_set_level (99);
#endif

  avc = avcodec_find_encoder( CODEC_ID_MPEG1VIDEO );
  if (avc == NULL)
  {
  	  printf ("cannot find MPEG encoder\n");
     exit (1);
  }

  avctx = avcodec_alloc_context();
    
  /* sample parameters */
  avctx->me_method = ME_LOG;
  avctx->pix_fmt = PIX_FMT_YUV420P;
  avctx->bit_rate = 2500000;
  avctx->width = width;
  avctx->height = height;
  avctx->time_base.num = 1;
  avctx->time_base.den = fps;
  avctx->gop_size=10;
  avctx->max_b_frames=1;
  avctx->draw_horiz_band = NULL;
  avctx->idct_algo = FF_IDCT_AUTO;

  int ret = avcodec_open( avctx, avc );
  if (ret)
    {
      printf("FAILED TO OPEN ENCODER, ret=%d, errno=%d\n", ret, errno);
      exit( 1 );
    }
  
  int size=height*width;
  
  pic = avcodec_alloc_frame();
  
  output_buffer=(char *)malloc(BUFFSIZE); /* Find where this value comes from */
  
  outpic.data[0]=(unsigned char *)malloc(size*3/2); /* YUV 420 Planar */
  outpic.data[1]=outpic.data[0]+size;
  outpic.data[2]=outpic.data[1]+size/4;
  outpic.data[3]=NULL;
  outpic.linesize[0]=width;
  outpic.linesize[1]=outpic.linesize[2]=width/2;
  outpic.linesize[3]=0;
  
  pic->data[0]=outpic.data[0];  /* Points to data portion of outpic     */
  pic->data[1]=outpic.data[1];  /* Since encode_video takes an AVFrame, */
  pic->data[2]=outpic.data[2];  /* and img_convert takes an AVPicture   */
  pic->data[3]=outpic.data[3];
  
  pic->linesize[0]=outpic.linesize[0]; /* This doesn't change */
  pic->linesize[1]=outpic.linesize[1];
  pic->linesize[2]=outpic.linesize[2];
  pic->linesize[3]=outpic.linesize[3];
  
  inpic.data[0]=(unsigned char *)malloc(size*3); /* RGB24 packed in 1 plane */
  inpic.data[1]=inpic.data[2]=inpic.data[3]=NULL;
  inpic.linesize[0]=width*3;
  inpic.linesize[1]=inpic.linesize[2]=inpic.linesize[3]=0;

  video_outf = fopen("video.outf","wb");
  if (video_outf == NULL)
  {
    printf ("failed to open output video file\n");
    exit (1);
  }
}
void AVCodecInitialisation::Check() {
   if (!isInitialised) {
      avcodec_init();
      avcodec_register_all();
   }
}
/** The Constructor
 */
OMX_ERRORTYPE omx_amr_audiodec_component_Constructor(OMX_COMPONENTTYPE *openmaxStandComp,OMX_STRING cComponentName) {

    OMX_ERRORTYPE err = OMX_ErrorNone;
    omx_amr_audiodec_component_PrivateType* omx_amr_audiodec_component_Private;
    omx_base_audio_PortType *pPort;
    OMX_U32 i;

    if (!openmaxStandComp->pComponentPrivate) {
        DEBUG(DEB_LEV_FUNCTION_NAME,"In %s, allocating component\n",__func__);
        openmaxStandComp->pComponentPrivate = calloc(1, sizeof(omx_amr_audiodec_component_PrivateType));
        if(openmaxStandComp->pComponentPrivate==NULL)
            return OMX_ErrorInsufficientResources;
    }
    else
        DEBUG(DEB_LEV_FUNCTION_NAME,"In %s, Error Component %x Already Allocated\n",__func__, (int)openmaxStandComp->pComponentPrivate);

    omx_amr_audiodec_component_Private = openmaxStandComp->pComponentPrivate;
    omx_amr_audiodec_component_Private->ports = NULL;

    /** Calling base filter constructor */
    err = omx_base_filter_Constructor(openmaxStandComp,cComponentName);

    omx_amr_audiodec_component_Private->sPortTypesParam[OMX_PortDomainAudio].nStartPortNumber = 0;
    omx_amr_audiodec_component_Private->sPortTypesParam[OMX_PortDomainAudio].nPorts = 2;

    /** Allocate Ports and call port constructor. */
    if (omx_amr_audiodec_component_Private->sPortTypesParam[OMX_PortDomainAudio].nPorts && !omx_amr_audiodec_component_Private->ports) {
        omx_amr_audiodec_component_Private->ports = calloc(omx_amr_audiodec_component_Private->sPortTypesParam[OMX_PortDomainAudio].nPorts, sizeof(omx_base_PortType *));
        if (!omx_amr_audiodec_component_Private->ports) {
            return OMX_ErrorInsufficientResources;
        }
        for (i=0; i < omx_amr_audiodec_component_Private->sPortTypesParam[OMX_PortDomainAudio].nPorts; i++) {
            omx_amr_audiodec_component_Private->ports[i] = calloc(1, sizeof(omx_base_audio_PortType));
            if (!omx_amr_audiodec_component_Private->ports[i]) {
                return OMX_ErrorInsufficientResources;
            }
        }
    }

    base_audio_port_Constructor(openmaxStandComp, &omx_amr_audiodec_component_Private->ports[0], 0, OMX_TRUE);
    base_audio_port_Constructor(openmaxStandComp, &omx_amr_audiodec_component_Private->ports[1], 1, OMX_FALSE);

    /** Domain specific section for the ports. */
    // first we set the parameter common to both formats
    //common parameters related to input port
    omx_amr_audiodec_component_Private->ports[OMX_BASE_FILTER_INPUTPORT_INDEX]->sPortParam.nBufferSize = DEFAULT_IN_BUFFER_SIZE;

    //common parameters related to output port
    pPort = (omx_base_audio_PortType *) omx_amr_audiodec_component_Private->ports[OMX_BASE_FILTER_OUTPUTPORT_INDEX];
    pPort->sAudioParam.nIndex    = OMX_IndexParamAudioPcm;
    pPort->sAudioParam.eEncoding = OMX_AUDIO_CodingPCM;
    pPort->sPortParam.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
    pPort->sPortParam.nBufferSize            = DEFAULT_OUT_BUFFER_SIZE;

    // now it's time to know the audio coding type of the component
    if(!strcmp(cComponentName, AUDIO_DEC_AMR_NAME))   // AMR format encoder
        omx_amr_audiodec_component_Private->audio_coding_type = OMX_AUDIO_CodingAMR;

    else  // IL client specified an invalid component name
        return OMX_ErrorInvalidComponentName;

    //set internal port parameters
    omx_amr_audiodec_component_SetInternalParameters(openmaxStandComp);

    //general configuration irrespective of any audio formats
    //setting other parameters of omx_amr_audiodec_component_private
    omx_amr_audiodec_component_Private->avCodec         = NULL;
    omx_amr_audiodec_component_Private->avCodecContext  = NULL;
    omx_amr_audiodec_component_Private->avcodecReady    = OMX_FALSE;
    omx_amr_audiodec_component_Private->extradata       = NULL;
    omx_amr_audiodec_component_Private->extradata_size  = 0;
    omx_amr_audiodec_component_Private->isFirstBuffer       = OMX_TRUE;

    omx_amr_audiodec_component_Private->BufferMgmtCallback = omx_amr_audiodec_component_BufferMgmtCallback;

    /** first initializing the codec context etc that was done earlier by ffmpeglibinit function */
    avcodec_init();
    av_register_all();
    omx_amr_audiodec_component_Private->avCodecContext = avcodec_alloc_context();

    omx_amr_audiodec_component_Private->messageHandler = omx_amr_audiodec_component_MessageHandler;
    omx_amr_audiodec_component_Private->destructor = omx_amr_audiodec_component_Destructor;
    openmaxStandComp->SetParameter = omx_amr_audiodec_component_SetParameter;
    openmaxStandComp->GetParameter = omx_amr_audiodec_component_GetParameter;
    openmaxStandComp->ComponentRoleEnum = omx_amr_audiodec_component_ComponentRoleEnum;

    noAudioDecInstance++;

    if(noAudioDecInstance>MAX_COMPONENT_AMR_AUDIODEC)
        return OMX_ErrorInsufficientResources;

    return err;
}
示例#5
0
static codec_data_t *ffmpeg_create (const char *stream_type,
                                    const char *compressor,
                                    int type,
                                    int profile,
                                    format_list_t *media_fmt,
                                    video_info_t *vinfo,
                                    const uint8_t *userdata,
                                    uint32_t ud_size,
                                    video_vft_t *vft,
                                    void *ifptr)
{
    ffmpeg_codec_t *ffmpeg;

    ffmpeg = MALLOC_STRUCTURE(ffmpeg_codec_t);
    memset(ffmpeg, 0, sizeof(*ffmpeg));

    ffmpeg->m_vft = vft;
    ffmpeg->m_ifptr = ifptr;
    avcodec_init();
    avcodec_register_all();
    av_log_set_level(AV_LOG_QUIET);

    ffmpeg->m_codecId = ffmpeg_find_codec(stream_type, compressor, type,
                                          profile, media_fmt, userdata, ud_size);

    // must have a codecID - we checked it earlier
    ffmpeg->m_codec = avcodec_find_decoder(ffmpeg->m_codecId);
    ffmpeg->m_c = avcodec_alloc_context();
    ffmpeg->m_picture = avcodec_alloc_frame();
    bool open_codec = true;
    bool run_userdata = false;
    bool free_userdata = false;

    switch (ffmpeg->m_codecId) {
    case CODEC_ID_MJPEG:
        break;
    case CODEC_ID_H264:
        // need to find height and width
        if (media_fmt != NULL && media_fmt->fmt_param != NULL) {
            userdata = h264_sdp_parse_sprop_param_sets(media_fmt->fmt_param,
                       &ud_size,
                       ffmpeg->m_vft->log_msg);
            if (userdata != NULL) free_userdata = true;
            ffmpeg_message(LOG_DEBUG, "ffmpeg", "sprop len %d", ud_size);
        }
        if (ud_size > 0) {
            ffmpeg_message(LOG_DEBUG, "ffmpeg", "userdata len %d", ud_size);
            open_codec = ffmpeg_find_h264_size(ffmpeg, userdata, ud_size);
            ffmpeg_message(LOG_DEBUG, "ffmpeg", "open codec is %d", open_codec);
            run_userdata = true;
        } else {
            open_codec = false;
        }
        break;
    case CODEC_ID_MPEG4: {
        fmtp_parse_t *fmtp = NULL;
        open_codec = false;
        if (media_fmt != NULL) {
            fmtp = parse_fmtp_for_mpeg4(media_fmt->fmt_param,
                                        ffmpeg->m_vft->log_msg);
            if (fmtp->config_binary != NULL) {
                userdata = fmtp->config_binary;
                ud_size = fmtp->config_binary_len;
                fmtp->config_binary = NULL;
                free_userdata = true;
            }
        }

        if (ud_size > 0) {
            uint8_t *vol = MP4AV_Mpeg4FindVol((uint8_t *)userdata, ud_size);
            u_int8_t TimeBits;
            u_int16_t TimeTicks;
            u_int16_t FrameDuration;
            u_int16_t FrameWidth;
            u_int16_t FrameHeight;
            u_int8_t  aspectRatioDefine;
            u_int8_t  aspectRatioWidth;
            u_int8_t  aspectRatioHeight;
            if (vol) {
                if (MP4AV_Mpeg4ParseVol(vol,
                                        ud_size - (vol - userdata),
                                        &TimeBits,
                                        &TimeTicks,
                                        &FrameDuration,
                                        &FrameWidth,
                                        &FrameHeight,
                                        &aspectRatioDefine,
                                        &aspectRatioWidth,
                                        &aspectRatioHeight)) {
                    ffmpeg->m_c->width = FrameWidth;
                    ffmpeg->m_c->height = FrameHeight;
                    open_codec = true;
                    run_userdata = true;
                }
            }
        }
        if (fmtp != NULL) {
            free_fmtp_parse(fmtp);
        }
    }
    break;
    case CODEC_ID_SVQ3:
        ffmpeg->m_c->extradata = (void *)userdata;
        ffmpeg->m_c->extradata_size = ud_size;
        if (vinfo != NULL) {
            ffmpeg->m_c->width = vinfo->width;
            ffmpeg->m_c->height = vinfo->height;
        }
        break;
    default:
        break;
    }
    if (open_codec) {
        if (avcodec_open(ffmpeg->m_c, ffmpeg->m_codec) < 0) {
            ffmpeg_message(LOG_CRIT, "ffmpeg", "failed to open codec");
            return NULL;
        }
        ffmpeg_message(LOG_DEBUG, "ffmpeg", "pixel format is %d",
                       ffmpeg->m_c->pix_fmt);
        ffmpeg->m_codec_opened = true;
        if (run_userdata) {
            uint32_t offset = 0;
            do {
                int got_picture;
                offset += avcodec_decode_video(ffmpeg->m_c,
                                               ffmpeg->m_picture,
                                               &got_picture,
                                               (uint8_t *)userdata + offset,
                                               ud_size - offset);
            } while (offset < ud_size);
        }

    }

    if (free_userdata) {
        CHECK_AND_FREE(userdata);
    }
    ffmpeg->m_did_pause = 1;
    return ((codec_data_t *)ffmpeg);
}
示例#6
0
bool CFfmpegVideoEncoder::Init(CLiveConfig* pConfig, bool realTime)
{
  avcodec_init();
  avcodec_register_all();
  m_pConfig = pConfig;

  if (m_push != NULL) {
    delete m_push;
    m_push = NULL;
  }
  double rate;
  rate = TimestampTicks / pConfig->GetFloatValue(CONFIG_VIDEO_FRAME_RATE);

  m_frame_time = (Duration)rate;
  if (strcasecmp(pConfig->GetStringValue(CONFIG_VIDEO_ENCODING),
		 VIDEO_ENCODING_MPEG4) == 0) {
    m_push = new CTimestampPush(1);
    m_codec = avcodec_find_encoder(CODEC_ID_MPEG4);
    m_media_frame = MPEG4VIDEOFRAME;
#ifdef OUTPUT_RAW
    m_outfile = fopen("raw.m4v", FOPEN_WRITE_BINARY);
#endif
  } else if (strcasecmp(pConfig->GetStringValue(CONFIG_VIDEO_ENCODING),
			VIDEO_ENCODING_H263) == 0) {
    m_push = new CTimestampPush(1);
    m_codec = avcodec_find_encoder(CODEC_ID_H263);
    m_media_frame = H263VIDEOFRAME;
#ifdef OUTPUT_RAW
    m_outfile = fopen("raw.263", FOPEN_WRITE_BINARY);
#endif
  } else {
    m_push = new CTimestampPush(3);
    m_codec = avcodec_find_encoder(CODEC_ID_MPEG2VIDEO);
    m_media_frame = MPEG2VIDEOFRAME;
#ifdef OUTPUT_RAW
    m_outfile = fopen("raw.m2v", FOPEN_WRITE_BINARY);
#endif
  }

  if (m_codec == NULL) {
    error_message("Couldn't find codec");
    return false;
  }
  
  m_avctx = avcodec_alloc_context();
  m_picture = avcodec_alloc_frame();
  m_avctx->width = m_pConfig->m_videoWidth;
  m_avctx->height = m_pConfig->m_videoHeight;
  m_avctx->bit_rate = 
    m_pConfig->GetIntegerValue(CONFIG_VIDEO_BIT_RATE) * 1000;
  m_avctx->frame_rate = (int)(m_pConfig->GetFloatValue(CONFIG_VIDEO_FRAME_RATE) + 0.5);
  m_avctx->frame_rate_base = 1;
  if (pConfig->GetIntegerValue(CONFIG_VIDEO_MPEG4_PAR_WIDTH) > 0 &&
      pConfig->GetIntegerValue(CONFIG_VIDEO_MPEG4_PAR_HEIGHT) > 0) {
#ifndef HAVE_AVRATIONAL
    float asp = (float)pConfig->GetIntegerValue(CONFIG_VIDEO_MPEG4_PAR_WIDTH);
    asp /= (float)pConfig->GetIntegerValue(CONFIG_VIDEO_MPEG4_PAR_HEIGHT);
    m_avctx->aspect_ratio = asp;
#else
    AVRational asp = 
      {pConfig->GetIntegerValue(CONFIG_VIDEO_MPEG4_PAR_WIDTH),
       pConfig->GetIntegerValue(CONFIG_VIDEO_MPEG4_PAR_HEIGHT)};
    m_avctx->sample_aspect_ratio = asp;
#endif
  }
			       
  
  if (m_media_frame == MPEG2VIDEOFRAME) {
    m_avctx->gop_size = 15;
    m_avctx->b_frame_strategy = 0;
    m_avctx->max_b_frames = 2;
  } else {
    if (m_media_frame == H263VIDEOFRAME) {
      m_avctx->bit_rate = 
	m_pConfig->GetIntegerValue(CONFIG_VIDEO_BIT_RATE) * 800;
      m_avctx->bit_rate_tolerance = 
	m_pConfig->GetIntegerValue(CONFIG_VIDEO_BIT_RATE) * 200;
#if 0
      // this makes file writing difficult
      m_avctx->rtp_mode = true;
      m_avctx->rtp_payload_size = 
	m_pConfig->GetIntegerValue(CONFIG_RTP_PAYLOAD_SIZE);
#endif
    } 
    m_key_frame_count = m_avctx->gop_size = (int)
      ((m_pConfig->GetFloatValue(CONFIG_VIDEO_FRAME_RATE)+0.5)
       * m_pConfig->GetFloatValue(CONFIG_VIDEO_KEY_FRAME_INTERVAL));
    m_avctx->flags |= CODEC_FLAG_GLOBAL_HEADER;
    debug_message("key frame count is %d", m_key_frame_count);
  }
  m_count = 0;
  if (avcodec_open(m_avctx, m_codec) < 0) {
    error_message("Couldn't open codec");
    return false;
  }
  
  return true;
}
示例#7
0
/**
 * Initialize libavcodec and register all the codecs and formats.
 */
void av_register_all(void)
{
    static int inited = 0;

    if (inited != 0)
        return;
    inited = 1;

    avcodec_init();
    avcodec_register_all();

    REGISTER_DEMUXER (AAC, aac);
    REGISTER_MUXDEMUX(AC3, ac3);
    REGISTER_MUXER   (ADTS, adts);
    REGISTER_MUXDEMUX(AIFF, aiff);
    REGISTER_MUXDEMUX(AMR, amr);
    REGISTER_MUXDEMUX(ASF, asf);
    REGISTER_MUXER   (ASF_STREAM, asf_stream);
    REGISTER_MUXDEMUX(AU, au);
#if defined(CONFIG_AUDIO_OSS) || defined(CONFIG_AUDIO_BEOS)
    REGISTER_MUXDEMUX(AUDIO, audio);
#endif
    REGISTER_MUXDEMUX(AVI, avi);
#ifdef CONFIG_AVISYNTH
    av_register_input_format(&avisynth_demuxer);
#endif
    REGISTER_DEMUXER (AVS, avs);
    REGISTER_MUXER   (CRC, crc);
    REGISTER_DEMUXER (DAUD, daud);
#ifdef CONFIG_DC1394
    REGISTER_DEMUXER (DC1394, dc1394);
#endif
    REGISTER_DEMUXER (DSICIN, dsicin);
    REGISTER_DEMUXER (DTS, dts);
    REGISTER_MUXDEMUX(DV, dv);
#ifdef CONFIG_DV1394
    REGISTER_DEMUXER (DV1394, dv1394);
#endif
    REGISTER_DEMUXER (EA, ea);
    REGISTER_MUXDEMUX(FFM, ffm);
    REGISTER_MUXDEMUX(FLAC, flac);
    REGISTER_DEMUXER (FLIC, flic);
    REGISTER_MUXDEMUX(FLV, flv);
    REGISTER_DEMUXER (FOURXM, fourxm);
    REGISTER_MUXER   (FRAMECRC, framecrc);
    REGISTER_MUXDEMUX(GIF, gif);
    REGISTER_DEMUXER (GXF, gxf);
#ifdef CONFIG_GPL
    REGISTER_MUXER   (GXF, gxf);
#endif
    REGISTER_MUXDEMUX(H261, h261);
    REGISTER_MUXDEMUX(H263, h263);
    REGISTER_MUXDEMUX(H264, h264);
    REGISTER_DEMUXER (IDCIN, idcin);
    REGISTER_MUXDEMUX(IMAGE2, image2);
    REGISTER_MUXDEMUX(IMAGE2PIPE, image2pipe);
    REGISTER_DEMUXER (INGENIENT, ingenient);
    REGISTER_DEMUXER (IPMOVIE, ipmovie);
    REGISTER_MUXDEMUX(M4V, m4v);
    REGISTER_DEMUXER (MATROSKA, matroska);
    REGISTER_MUXDEMUX(MJPEG, mjpeg);
    REGISTER_DEMUXER (MM, mm);
    REGISTER_MUXDEMUX(MMF, mmf);
    REGISTER_MUXDEMUX(MOV, mov);
    REGISTER_MUXER   (MP2, mp2);
    REGISTER_MUXDEMUX(MP3, mp3);
    REGISTER_MUXER   (MP4, mp4);
    REGISTER_MUXER   (MPEG1SYSTEM, mpeg1system);
    REGISTER_MUXER   (MPEG1VCD, mpeg1vcd);
    REGISTER_MUXER   (MPEG1VIDEO, mpeg1video);
    REGISTER_MUXER   (MPEG2DVD, mpeg2dvd);
    REGISTER_MUXER   (MPEG2SVCD, mpeg2svcd);
    REGISTER_MUXER   (MPEG2VIDEO, mpeg2video);
    REGISTER_MUXER   (MPEG2VOB, mpeg2vob);
    REGISTER_DEMUXER (MPEGPS, mpegps);
    REGISTER_MUXDEMUX(MPEGTS, mpegts);
    REGISTER_DEMUXER (MPEGVIDEO, mpegvideo);
    REGISTER_MUXER   (MPJPEG, mpjpeg);
    REGISTER_DEMUXER (MTV, mtv);
    REGISTER_DEMUXER (MXF, mxf);
    REGISTER_DEMUXER (NSV, nsv);
    REGISTER_MUXER   (NULL, null);
    REGISTER_DEMUXER (NUT, nut);
#ifdef CONFIG_LIBNUT
    REGISTER_MUXER   (NUT, nut);
#endif
    REGISTER_DEMUXER (NUV, nuv);
    REGISTER_DEMUXER (OGG, ogg);
#ifdef CONFIG_LIBOGG
    REGISTER_MUXER   (OGG, ogg);
#endif
    REGISTER_MUXDEMUX(PCM_ALAW,  pcm_alaw);
    REGISTER_MUXDEMUX(PCM_MULAW, pcm_mulaw);
    REGISTER_MUXDEMUX(PCM_S16BE, pcm_s16be);
    REGISTER_MUXDEMUX(PCM_S16LE, pcm_s16le);
    REGISTER_MUXDEMUX(PCM_S8,    pcm_s8);
    REGISTER_MUXDEMUX(PCM_U16BE, pcm_u16be);
    REGISTER_MUXDEMUX(PCM_U16LE, pcm_u16le);
    REGISTER_MUXDEMUX(PCM_U8,    pcm_u8);
    REGISTER_MUXER   (PSP, psp);
    REGISTER_MUXDEMUX(RAWVIDEO, rawvideo);
    REGISTER_MUXDEMUX(RM, rm);
    REGISTER_DEMUXER (ROQ, roq);
#ifdef CONFIG_NETWORK
    REGISTER_DEMUXER (REDIR, redir);
    REGISTER_MUXER   (RTP, rtp);
    REGISTER_DEMUXER (RTSP, rtsp);
    REGISTER_DEMUXER (SDP, sdp);
    av_register_rtp_dynamic_payload_handlers();
#endif
    REGISTER_DEMUXER (SEGAFILM, segafilm);
    REGISTER_DEMUXER (SHORTEN, shorten);
    REGISTER_DEMUXER (SMACKER, smacker);
    REGISTER_DEMUXER (SOL, sol);
    REGISTER_DEMUXER (STR, str);
    REGISTER_MUXDEMUX(SWF, swf);
    REGISTER_MUXER   (TG2, tg2);
    REGISTER_MUXER   (TGP, tgp);
    REGISTER_DEMUXER (TIERTEXSEQ, tiertexseq);
    REGISTER_DEMUXER (TTA, tta);
#ifdef CONFIG_VIDEO4LINUX2
    REGISTER_DEMUXER (V4L2, v4l2);
#endif
#if defined(CONFIG_VIDEO4LINUX) || defined(CONFIG_BKTR)
    REGISTER_DEMUXER (VIDEO_GRAB_DEVICE, video_grab_device);
#endif
    REGISTER_DEMUXER (VMD, vmd);
    REGISTER_MUXDEMUX(VOC, voc);
    REGISTER_MUXDEMUX(WAV, wav);
    REGISTER_DEMUXER (WC3, wc3);
    REGISTER_DEMUXER (WSAUD, wsaud);
    REGISTER_DEMUXER (WSVQA, wsvqa);
    REGISTER_DEMUXER (WV, wv);
    REGISTER_MUXDEMUX(YUV4MPEGPIPE, yuv4mpegpipe);

#ifdef CONFIG_PROTOCOLS
    /* file protocols */
    register_protocol(&file_protocol);
    register_protocol(&pipe_protocol);
#ifdef CONFIG_NETWORK
    register_protocol(&udp_protocol);
    register_protocol(&rtp_protocol);
    register_protocol(&tcp_protocol);
    register_protocol(&http_protocol);
#endif
#endif
}
示例#8
0
文件: tdav.c 项目: Zhe-Zhu/Qianli
int tdav_init()
{
	int ret = 0;
	
	/* === OS specific === */
#if TDAV_UNDER_WINDOWS
	if ((ret = tdav_win32_init())) {
		return ret;
	}
#elif TDAV_UNDER_APPLE
	if ((ret = tdav_apple_init())) {
		return ret;
	}
#endif
	
	/* === Initialize ffmpeg === */
#if HAVE_FFMPEG
#   if LIBAVCODEC_VERSION_MAJOR <= 53
	avcodec_init();
#   endif
#endif

	/* === SRTP === */

	/* === Register media contents === */
	tmedia_content_plugin_register("text/html", tmedia_content_dummy_plugin_def_t);
	tmedia_content_plugin_register("text/plain", tmedia_content_dummy_plugin_def_t);
	tmedia_content_plugin_register("application/octet-stream", tmedia_content_dummy_plugin_def_t);
	tmedia_content_plugin_register("message/CPIM", tmedia_content_cpim_plugin_def_t);
	/* To be implemented
	tmedia_content_plugin_register("message/sipfrag", tmedia_content_sipfrag_plugin_def_t);
	tmedia_content_plugin_register("multipart/digest", tmedia_content_multipart_plugin_def_t);
	tmedia_content_plugin_register("multipart/mixed", tmedia_content_multipart_plugin_def_t);
	tmedia_content_plugin_register("multipart/related", tmedia_content_multipart_plugin_def_t);
	tmedia_content_plugin_register("multipart/alternative", tmedia_content_multipart_plugin_def_t);
	tmedia_content_plugin_register("multipart/encrypted", tmedia_content_multipart_plugin_def_t);
	tmedia_content_plugin_register("multipart/parallel", tmedia_content_multipart_plugin_def_t);
	tmedia_content_plugin_register("multipart/signed", tmedia_content_multipart_plugin_def_t);
	*/

	/* === Register sessions === */
	tmedia_session_plugin_register(tmedia_session_ghost_plugin_def_t);
	tmedia_session_plugin_register(tdav_session_audio_plugin_def_t);
	tmedia_session_plugin_register(tdav_session_video_plugin_def_t);
	tmedia_session_plugin_register(tdav_session_msrp_plugin_def_t);
	tmedia_session_plugin_register(tdav_session_t140_plugin_def_t);

	/* === Register codecs === */
#if HAVE_FFMPEG
	avcodec_register_all();
#endif
	
	tmedia_codec_plugin_register(tdav_codec_msrp_plugin_def_t);
	tmedia_codec_plugin_register(tdav_codec_t140_plugin_def_t);
	tmedia_codec_plugin_register(tdav_codec_red_plugin_def_t);
	tmedia_codec_plugin_register(tdav_codec_g711a_plugin_def_t);
	tmedia_codec_plugin_register(tdav_codec_g711u_plugin_def_t);
	tmedia_codec_plugin_register(tdav_codec_g722_plugin_def_t);
#if HAVE_OPENCORE_AMR
	tmedia_codec_plugin_register(tdav_codec_amrnb_oa_plugin_def_t);
	tmedia_codec_plugin_register(tdav_codec_amrnb_be_plugin_def_t);
#endif
#if HAVE_BV16
	tmedia_codec_plugin_register(tdav_codec_bv16_plugin_def_t);
#endif
#if HAVE_LIBGSM
	tmedia_codec_plugin_register(tdav_codec_gsm_plugin_def_t);
#endif
#if HAVE_ILBC
	tmedia_codec_plugin_register(tdav_codec_ilbc_plugin_def_t);
#endif
#if HAVE_LIB_SPEEX
	tmedia_codec_plugin_register(tdav_codec_speex_nb_plugin_def_t);
	tmedia_codec_plugin_register(tdav_codec_speex_wb_plugin_def_t);
	tmedia_codec_plugin_register(tdav_codec_speex_uwb_plugin_def_t);
#endif
#if HAVE_LIBOPUS
	tmedia_codec_plugin_register(tdav_codec_opus_plugin_def_t);
#endif
#if HAVE_G729
	tmedia_codec_plugin_register(tdav_codec_g729ab_plugin_def_t);
#endif
	// last: dtmf, ULPFEC and RED
	tmedia_codec_plugin_register(tdav_codec_dtmf_plugin_def_t);
	// tmedia_codec_plugin_register(tdav_codec_ulpfec_plugin_def_t);
	// tmedia_codec_plugin_register(tdav_codec_red_plugin_def_t);

#if HAVE_LIBVPX
	tmedia_codec_plugin_register(tdav_codec_vp8_plugin_def_t);
#endif
#if HAVE_CUDA
	if(tdav_codec_h264_cuda_is_supported()){
		tmedia_codec_plugin_register(tdav_codec_h264_cuda_bp10_plugin_def_t);
		tmedia_codec_plugin_register(tdav_codec_h264_cuda_bp20_plugin_def_t);
		tmedia_codec_plugin_register(tdav_codec_h264_cuda_bp30_plugin_def_t);
	}
#endif
#if HAVE_FFMPEG
	tmedia_codec_plugin_register(tdav_codec_mp4ves_plugin_def_t);
#	if !defined(HAVE_H264) || HAVE_H264
	tmedia_codec_plugin_register(tdav_codec_h264_base_plugin_def_t);
	tmedia_codec_plugin_register(tdav_codec_h264_main_plugin_def_t);
#	endif
	tmedia_codec_plugin_register(tdav_codec_h263p_plugin_def_t);
	tmedia_codec_plugin_register(tdav_codec_h263pp_plugin_def_t);
#	if !defined(HAVE_THEORA) || HAVE_THEORA
	tmedia_codec_plugin_register(tdav_codec_theora_plugin_def_t);
#	endif
	tmedia_codec_plugin_register(tdav_codec_h263_plugin_def_t);
	tmedia_codec_plugin_register(tdav_codec_h261_plugin_def_t);
#elif HAVE_H264_PASSTHROUGH
	tmedia_codec_plugin_register(tdav_codec_h264_base_plugin_def_t);
	tmedia_codec_plugin_register(tdav_codec_h264_main_plugin_def_t);
#endif

	
	/* === Register converters === */
#if HAVE_LIBYUV
	tmedia_converter_video_plugin_register(tdav_converter_video_libyuv_plugin_def_t);
#elif HAVE_FFMPEG || HAVE_SWSSCALE
	tmedia_converter_video_plugin_register(tdav_converter_video_ffmpeg_plugin_def_t);
#endif

	/* === Register consumers === */
	tmedia_consumer_plugin_register(tdav_consumer_t140_plugin_def_t); /* T140 */
#if HAVE_DSOUND_H
	tmedia_consumer_plugin_register(tdav_consumer_dsound_plugin_def_t);
#elif HAVE_WAVE_API
	tmedia_consumer_plugin_register(tdav_consumer_waveapi_plugin_def_t);
#elif HAVE_WASAPI
	tmedia_consumer_plugin_register(tdav_consumer_wasapi_plugin_def_t);
#endif
#if HAVE_TINYDSHOW // DirectShow (Windows XP and later)
	tmedia_consumer_plugin_register(tdshow_consumer_plugin_def_t);
#elif HAVE_WINM // Windows Media (WP8)
	tmedia_consumer_plugin_register(tdav_consumer_winm_plugin_def_t);
#elif HAVE_MF // Media Foundation (Windows 7 and later)
	tmedia_consumer_plugin_register(tdav_consumer_video_mf_plugin_def_t);
#endif

#if HAVE_COREAUDIO_AUDIO_UNIT // CoreAudio based on AudioUnit
	tmedia_consumer_plugin_register(tdav_consumer_audiounit_plugin_def_t);
#elif HAVE_COREAUDIO_AUDIO_QUEUE // CoreAudio based on AudioQueue
	tmedia_consumer_plugin_register(tdav_consumer_audioqueue_plugin_def_t);
#endif

#if HAVE_OSS_H
	tmedia_consumer_plugin_register(tmedia_consumer_oss_plugin_def_t);
#endif

	/* === Register producers === */
	tmedia_producer_plugin_register(tdav_producer_t140_plugin_def_t); /* T140 */
#if HAVE_DSOUND_H // DirectSound
	tmedia_producer_plugin_register(tdav_producer_dsound_plugin_def_t);
#elif HAVE_WAVE_API // WaveAPI
	tmedia_producer_plugin_register(tdav_producer_waveapi_plugin_def_t);
#elif HAVE_WASAPI // WASAPI
	tmedia_producer_plugin_register(tdav_producer_wasapi_plugin_def_t);
#endif
#if HAVE_TINYDSHOW // DirectShow (Windows XP and later)
	tmedia_producer_plugin_register(tdshow_producer_plugin_def_t);
#elif HAVE_WINM // Windows Media (WP8)
	tmedia_producer_plugin_register(tdav_producer_winm_plugin_def_t);
#elif HAVE_MF // Medi Foundation (Windows 7 and later)
	tmedia_producer_plugin_register(tdav_producer_video_mf_plugin_def_t);
#endif
	
#if HAVE_COREAUDIO_AUDIO_UNIT // CoreAudio based on AudioUnit
	tmedia_producer_plugin_register(tdav_producer_audiounit_plugin_def_t);
#elif HAVE_COREAUDIO_AUDIO_QUEUE // CoreAudio based on AudioQueue
	tmedia_producer_plugin_register(tdav_producer_audioqueue_plugin_def_t);
#endif

	/* === Register Audio Denoise (AGC, VAD, Noise Suppression and AEC) === */
#if HAVE_SPEEX_DSP && (!defined(HAVE_SPEEX_DENOISE) || HAVE_SPEEX_DENOISE)
	tmedia_denoise_plugin_register(tdav_speex_denoise_plugin_def_t);
#endif
#if HAVE_WEBRTC && (!defined(HAVE_WEBRTC_DENOISE) || HAVE_WEBRTC_DENOISE)
	tmedia_denoise_plugin_register(tdav_webrtc_denoise_plugin_def_t);
#endif

	/* === Register Audio Resampler === */
#if HAVE_SPEEX_DSP && (!defined(HAVE_SPEEX_RESAMPLER) || HAVE_SPEEX_RESAMPLER)
	tmedia_resampler_plugin_register(tdav_speex_resampler_plugin_def_t);
#endif

	/* === Register Audio/video JitterBuffer === */
#if HAVE_SPEEX_DSP && HAVE_SPEEX_JB
	tmedia_jitterbuffer_plugin_register(tdav_speex_jitterbuffer_plugin_def_t);
#else
	tmedia_jitterbuffer_plugin_register(tdav_speakup_jitterbuffer_plugin_def_t);
#endif

	return ret;
}
示例#9
0
static int init(sh_audio_t *sh_audio)
{
    int tries = 0;
    int x;
    AVCodecContext *lavc_context;
    AVCodec *lavc_codec;

    mp_msg(MSGT_DECAUDIO,MSGL_V,"FFmpeg's libavcodec audio codec\n");
    if(!avcodec_initialized){
      avcodec_init();
      avcodec_register_all();
      avcodec_initialized=1;
    }

    lavc_codec = (AVCodec *)avcodec_find_decoder_by_name(sh_audio->codec->dll);
    if(!lavc_codec){
	mp_tmsg(MSGT_DECAUDIO,MSGL_ERR,"Cannot find codec '%s' in libavcodec...\n",sh_audio->codec->dll);
	return 0;
    }

    lavc_context = avcodec_alloc_context();
    sh_audio->context=lavc_context;

    lavc_context->sample_rate = sh_audio->samplerate;
    lavc_context->bit_rate = sh_audio->i_bps * 8;
    if(sh_audio->wf){
	lavc_context->channels = sh_audio->wf->nChannels;
	lavc_context->sample_rate = sh_audio->wf->nSamplesPerSec;
	lavc_context->bit_rate = sh_audio->wf->nAvgBytesPerSec * 8;
	lavc_context->block_align = sh_audio->wf->nBlockAlign;
	lavc_context->bits_per_coded_sample = sh_audio->wf->wBitsPerSample;
    }
    lavc_context->request_channels = audio_output_channels;
    lavc_context->codec_tag = sh_audio->format; //FOURCC
    lavc_context->codec_type = CODEC_TYPE_AUDIO;
    lavc_context->codec_id = lavc_codec->id; // not sure if required, imho not --A'rpi

    /* alloc extra data */
    if (sh_audio->wf && sh_audio->wf->cbSize > 0) {
        lavc_context->extradata = av_mallocz(sh_audio->wf->cbSize + FF_INPUT_BUFFER_PADDING_SIZE);
        lavc_context->extradata_size = sh_audio->wf->cbSize;
        memcpy(lavc_context->extradata, (char *)sh_audio->wf + sizeof(WAVEFORMATEX),
               lavc_context->extradata_size);
    }

    // for QDM2
    if (sh_audio->codecdata_len && sh_audio->codecdata && !lavc_context->extradata)
    {
        lavc_context->extradata = av_malloc(sh_audio->codecdata_len);
        lavc_context->extradata_size = sh_audio->codecdata_len;
        memcpy(lavc_context->extradata, (char *)sh_audio->codecdata,
               lavc_context->extradata_size);
    }

    /* open it */
    if (avcodec_open(lavc_context, lavc_codec) < 0) {
        mp_tmsg(MSGT_DECAUDIO,MSGL_ERR, "Could not open codec.\n");
        return 0;
    }
   mp_msg(MSGT_DECAUDIO,MSGL_V,"INFO: libavcodec \"%s\" init OK!\n", lavc_codec->name);

//   printf("\nFOURCC: 0x%X\n",sh_audio->format);
   if(sh_audio->format==0x3343414D){
       // MACE 3:1
       sh_audio->ds->ss_div = 2*3; // 1 samples/packet
       sh_audio->ds->ss_mul = 2*sh_audio->wf->nChannels; // 1 byte*ch/packet
   } else
   if(sh_audio->format==0x3643414D){
       // MACE 6:1
       sh_audio->ds->ss_div = 2*6; // 1 samples/packet
       sh_audio->ds->ss_mul = 2*sh_audio->wf->nChannels; // 1 byte*ch/packet
   }

   // Decode at least 1 byte:  (to get header filled)
   do {
       x=decode_audio(sh_audio,sh_audio->a_buffer,1,sh_audio->a_buffer_size);
   } while (x <= 0 && tries++ < 5);
   if(x>0) sh_audio->a_buffer_len=x;

  sh_audio->channels=lavc_context->channels;
  sh_audio->samplerate=lavc_context->sample_rate;
  sh_audio->i_bps=lavc_context->bit_rate/8;
  switch (lavc_context->sample_fmt) {
      case SAMPLE_FMT_U8:  sh_audio->sample_format = AF_FORMAT_U8;       break;
      case SAMPLE_FMT_S16: sh_audio->sample_format = AF_FORMAT_S16_NE;   break;
      case SAMPLE_FMT_S32: sh_audio->sample_format = AF_FORMAT_S32_NE;   break;
      case SAMPLE_FMT_FLT: sh_audio->sample_format = AF_FORMAT_FLOAT_NE; break;
      default:
          mp_msg(MSGT_DECAUDIO, MSGL_FATAL, "Unsupported sample format\n");
          return 0;
  }
  /* If the audio is AAC the container level data may be unreliable
   * because of SBR handling problems (possibly half real sample rate at
   * container level). Default AAC decoding with ad_faad has used codec-level
   * values for a long time without generating complaints so it should be OK.
   */
  if (sh_audio->wf && lavc_context->codec_id != CODEC_ID_AAC) {
      // If the decoder uses the wrong number of channels all is lost anyway.
      // sh_audio->channels=sh_audio->wf->nChannels;
      if (sh_audio->wf->nSamplesPerSec)
      sh_audio->samplerate=sh_audio->wf->nSamplesPerSec;
      if (sh_audio->wf->nAvgBytesPerSec)
      sh_audio->i_bps=sh_audio->wf->nAvgBytesPerSec;
  }
  sh_audio->samplesize=af_fmt2bits(sh_audio->sample_format)/ 8;
  return 1;
}
示例#10
0
文件: Server.cpp 项目: m1geo/UNV
int main(int argc, char * argv[]) 
{
	cout << "The UNV Project - Server" << endl;
	cout << "Department of Electronic & Electrical Engineering" << endl;
	cout << "University College London" << endl << endl;
	
	// Read CLI Options, and error if not vaild
	if ( (argc<=1)||(get_options(argc, argv)) ) 
	{
		fail("parsing CLI options", "couldn't understand options. Run with --help.", FALSE);
		exit(EXIT_SUCCESS);
	}
	
	// check that mandatory command line args are there...
	if ( (cliOpts.mode==NULL)||(cliOpts.devicepath==NULL)||(cliOpts.networkport==0)||(cliOpts.transport==4)||(cliOpts.vcodec==4) ) 
	{
		printf("You must specify mode (-m), device (-d), network port (-p), network transport (-t) and a video codec (-c)\n");
		fail("parsing CLI options", "Mandatory options missing! Run with --help.", FALSE);
		exit(EXIT_FAILURE);
	}

	// register all codecs, drivers, devics, etc so we know what we have.
	if (cliOpts.verbose) { cout << "Registering Codecs and Device drivers" << endl; } // Verbose

	// Init libav stuff
	avcodec_init();
	av_register_all();
	avdevice_register_all();
	av_init_packet(&CurrentPacket);

	// Show version information
	if (cliOpts.version) {
		show_version();
		exit(EXIT_SUCCESS);
	}

	// Show formats supported if asked.
	if (cliOpts.formats) {
		show_format(pInputFmtVidDec);
		exit(EXIT_SUCCESS);
	}
	
	// Before we get onto the deep stuff, check if we know what we're about...
	if ((cliOpts.devicepath == NULL) || (cliOpts.mode == NULL)) {
		fail("intialising", "device or mode not set.", TRUE);
	}
	
	// Program actually starts here - before was just checking stuffs //
	
	// Allocate codec context
	if (cliOpts.verbose) { cout << "Allocating memory for codec contexts" << endl; }

	pCodecCtxVidEnc = avcodec_alloc_context();
	pCodecCtxVidDec = avcodec_alloc_context();

	pCodecCtxAudDec = avcodec_alloc_context();
	pCodecCtxAudEnc = avcodec_alloc_context();
	
	if ( (pCodecCtxVidEnc == NULL) || (pCodecCtxVidDec == NULL) ) {
		fail("allocating frames", "couldn't allocate either pFrame of pFrameRGB", TRUE);
	}

	// Allocate Frames
	if (cliOpts.verbose)
	{
		cout << "Allocating memory for frames " << "\n";
	}

	pFrameDec = avcodec_alloc_frame();
	pFrameEnc = avcodec_alloc_frame();
	pFrameRGB = avcodec_alloc_frame();

	if ( (pFrameDec == NULL) || (pFrameEnc == NULL) || (pFrameRGB == NULL) ) {
		fail("allocating frames", "couldn't allocate either pFrame of pFrameRGB", TRUE);
	}

	// Get options for input type
	if (strcmp(cliOpts.mode, "file") == 0 || strcmp(cliOpts.mode, "file") == 0) {
	  int temp;
		// File
		if (cliOpts.verbose) {
			cout << "Opening '" << cliOpts.devicepath << "' as input file" << "\n";
		}
			// Verbose

		temp = av_open_input_file(&pFormatCtxVidDec, cliOpts.devicepath, NULL, 0, NULL);
		iFileOpen = av_open_input_file(&pFormatCtxAudDec,cliOpts.devicepath, NULL, 0, NULL);
		
		if(temp != 0) {
			AVERROR_LOOKUP(temp);
			fail("opening video", "couldn't open input file", TRUE);
		}

		if(iFileOpen != 0) {
			AVERROR_LOOKUP(iFileOpen);
			fail("opening audio", "couldn't open audio device", TRUE);
		}
	} else {
	  int temp;
		// Video4Linux2
		if (cliOpts.verbose) { cout << "Opening " << cliOpts.devicepath << " as Video4Linux2 device" << "\n";  } // Verbose
		FormatParamVidDec.channel = 0;
		FormatParamVidDec.standard = "pal"; // pal (or ntsc)
		FormatParamVidDec.width = cliOpts.width;    // read from CLI
		FormatParamVidDec.height = cliOpts.height;   // read from CLI
		FormatParamVidDec.time_base.num = 1;
		FormatParamVidDec.time_base.den = 15;
		pInputFmtVidDec = av_find_input_format("video4linux2");
		/*FIXME*/ //temp = av_open_input_file(&pFormatCtxVidDec, cliOpts.devicepath, pInputFmtVidDec, 0, &FormatParamVidDec); // should take the FormatParamVidDec option, but seg faults. /////////////////////////////////////////
		temp = av_open_input_file(&pFormatCtxVidDec, cliOpts.devicepath, pInputFmtVidDec, 0, NULL);
		if(temp !=0) {
			AVERROR_LOOKUP(temp);
			fail("opening video", "couldn't open input file", TRUE);
		}
	}

	// Set parameters

	FormatParamAudDec.sample_rate = SAMPLE_RATE;
	FormatParamAudDec.channels = CHANNELS;
	FormatParamAudDec.time_base = (AVRational){1, SAMPLE_RATE};
	// FormatParamAudDec.audio_codec_id = CODEC_TYPE_AUDIO;

	// Find input format
	pInputFmtAudDec = av_find_input_format("alsa");

	// Open device
	if (cliOpts.verbose) {
		cout << "Opening '" << "plughw:0,0" << "'  as ALSA Audio device" << "\n"; 
	}
	
	iFileOpen = av_open_input_file(&pFormatCtxAudDec, "plughw:0,0", pInputFmtAudDec, 0, &FormatParamAudDec);
	if (cliOpts.verbose) { cout << "av_open_input_file: " << iFileOpen << "\n"; }

	if(iFileOpen<0) {
		AVERROR_LOOKUP(iFileOpen);
		fail("opening video", "couldn't open audio device", TRUE);
	}

	if(iFileOpen==0 && cliOpts.verbose) {
		cout << "Opened successfully!" << "\n";
	}

	// Retrieve stream information
	if (cliOpts.verbose) { cout << "Analysing video stream(s)" << "\n"; } {
	  int temp;
	  temp = av_find_stream_info(pFormatCtxVidDec);
		if(temp<0) {
			AVERROR_LOOKUP(temp);
			fail("finding stream", "couldn't find stream infomation", TRUE);
		}
	}
	
	// dump what we've found to stderr.
	if (cliOpts.verbose) {
		cerr << "Format Dump" << "\n";
		dump_format(pFormatCtxVidDec, 0, cliOpts.devicepath, FALSE);
	}

	// Find the first video stream
	if (cliOpts.verbose) {
		cout << "Selecting first video stream" << "\n";
	}

	iVideoStream=-1;

	for(int i=0; i<(int)pFormatCtxVidDec->nb_streams; i++) {
		if(pFormatCtxVidDec->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO)
		{ //modified codec.codec... to union in structure - GS
			iVideoStream=i;
			break;
		}
	}

	if(iVideoStream == -1) {
		fail("selecting stream", "couldn't select first stream", TRUE);
	}

	iAudioStream = -1;

	if (cliOpts.verbose) { // Look for audio stream
		cout << "Looking for audio stream..." << "\n";
	}

	for (int i = 0; i < (int)pFormatCtxAudDec->nb_streams; i++){ // Loop through streams
		if (pFormatCtxAudDec->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO) {
			// If audio stream is found
			iAudioStream = i;
			break;
		}
	}

	if (cliOpts.verbose) {
		cout << "iAudioStream = " << iAudioStream << "\n";
	}

	if (iAudioStream < 0 ) {
		fail("selecting stream", "couldn't select audio stream", TRUE);
	}

	// Get a pointer to the codec context for the video stream
	pCodecCtxVidDec=pFormatCtxVidDec->streams[iVideoStream]->codec; // removed address operator - GS

	// Find the decoder for the video stream
	pCodecVidDec=avcodec_find_decoder(pCodecCtxVidDec->codec_id);

	if(pCodecVidDec==NULL) { fail("finding decoder", "couldn't find required codec", TRUE); }

	// Populate AVCodecContext with info from stream
	pCodecCtxAudDec = pFormatCtxAudDec->streams[iAudioStream]->codec;

	if (pCodecCtxAudDec == NULL) {
		cerr << "Error: pCodecCtxAudDec is null!" << "\n";
		return 1;
	}

	// Find decoder
	pCodecAudDec = avcodec_find_decoder(pCodecCtxAudDec->codec_id);

	if(pCodecAudDec==NULL) {
		fail("finding decoder", "couldn't find required codec", TRUE);
	}

	// Find the codec for our required format
	if (cliOpts.vcodec == USE_MJPEG) {pCodecVidEnc = avcodec_find_encoder(CODEC_ID_MJPEG);}
	if (cliOpts.vcodec == USE_H264) {pCodecVidEnc = avcodec_find_encoder(CODEC_ID_H264);}
	
	if (pCodecVidEnc == NULL) {
		fail("finding encoder", "couldn't find required codec", TRUE);
	}

	// X.264 Parameters
	if (cliOpts.vcodec == USE_H264) {
		pCodecCtxVidEnc->thread_count = 2;
		avcodec_thread_init(pCodecCtxVidEnc, pCodecCtxVidEnc->thread_count);
		pCodecCtxVidEnc->flags |= CODEC_FLAG_LOOP_FILTER;
		pCodecCtxVidEnc->me_cmp |= 1;
		pCodecCtxVidEnc->partitions |= X264_PART_I8X8+X264_PART_I4X4+X264_PART_P8X8+X264_PART_B8X8;
		pCodecCtxVidEnc->me_method = ME_HEX;
		pCodecCtxVidEnc->me_subpel_quality = 2;
		//c->me_range = 16;
		pCodecCtxVidEnc->keyint_min = 25;
		//c->scenechange_threshold=40;
		//c->qcompress = 0.6;
		pCodecCtxVidEnc->qmin = 10;
		pCodecCtxVidEnc->qmax = 51;
		pCodecCtxVidEnc->max_qdiff = 4;
		pCodecCtxVidEnc->max_b_frames = 0;
		pCodecCtxVidEnc->refs = 1;
		//c->directpred = 1;
		//c->trellis = 1;
		pCodecCtxVidEnc->flags2 |= CODEC_FLAG2_MIXED_REFS+CODEC_FLAG2_WPRED+CODEC_FLAG2_8X8DCT+CODEC_FLAG2_FASTPSKIP;//CODEC_FLAG2_BPYRAMID+
		//c->weighted_p_pred = 2;
		pCodecCtxVidEnc->crf = 32;
		pCodecCtxVidEnc->rc_lookahead = 0;
		pCodecCtxVidEnc->gop_size = 10;
		//pCodecCtxVidEnc->time_base.den * 2; //250;// emit one intra frame every twelve frames at most
		//pCodecCtxVidEnc->pix_fmt = STREAM_PIX_FMT;
		pCodecCtxVidEnc->width = 640;
		pCodecCtxVidEnc->height = 480;
		pCodecCtxVidEnc->time_base=(AVRational){1,5};
		// some formats want stream headers to be separate
		if(pCodecCtxVidEnc->flags & AVFMT_GLOBALHEADER)
		pCodecCtxVidEnc->flags |= CODEC_FLAG_GLOBAL_HEADER;
		if(cliOpts.transport==USE_TCP) {pCodecCtxVidEnc->bit_rate = 1000000; printf("Capping BR for TCP/H264\n");}
		if (cliOpts.verbose) { cout << "x264 configured" << "\n"; }
	}
	
	// MJPEG Parameters
	if (cliOpts.vcodec == USE_MJPEG) {
		pCodecCtxVidEnc->codec_type = CODEC_TYPE_VIDEO;
		pCodecCtxVidEnc->codec_id = CODEC_ID_MJPEG;
		pCodecCtxVidEnc->bit_rate = BITRATE;
		pCodecCtxVidEnc->width = pCodecCtxVidDec->width;
		pCodecCtxVidEnc->height = pCodecCtxVidDec->height;
		pCodecCtxVidEnc->time_base=(AVRational){1,25};
		pCodecCtxVidEnc->pix_fmt = PIX_FMT_YUVJ420P;//YUVJ422P
		pCodecCtxVidEnc->color_range=AVCOL_RANGE_JPEG;
		pCodecCtxVidEnc->qmin= 90;
		pCodecCtxVidEnc->qmax= 90;
		if (cliOpts.verbose) { cout << "MJPEG configured" << "\n"; }
	}
	
	// Find encoder
	pCodecAudEnc = avcodec_find_encoder(CODEC_ID_MP3);
	if (pCodecAudEnc == NULL) {
		fail("Error:", "codec not found!", TRUE);
		return 1;
	}

	//Set encoder parameters
	pCodecCtxAudEnc->bit_rate = BITRATE;
	pCodecCtxAudEnc->sample_fmt = SAMPLE_FMT_S16;
	pCodecCtxAudEnc->sample_rate = SAMPLE_RATE;
	pCodecCtxAudEnc->channels = CHANNELS;
	//pCodecCtxAudEnc->profile = 1; //FF_PROFILE_AAC_MAIN;
	pCodecCtxAudEnc->time_base = (AVRational){1, SAMPLE_RATE};
	pCodecCtxAudEnc->codec_type = CODEC_TYPE_AUDIO;
	
	// Open decoder
	if (cliOpts.verbose) { cout << "Opening codec (decoder)" << "\n"; } {
		int temp;
		temp = avcodec_open(pCodecCtxVidDec, pCodecVidDec);

		if(temp<0) {
			AVERROR_LOOKUP(temp);
			fail("opening codec", "couldn't open decoder codec", TRUE);
		}
	}
	
	// Open the encoder
	if (cliOpts.verbose) { cout << "Opening codec (encoder)" << "\n"; } {
		int temp;
		temp = avcodec_open(pCodecCtxVidEnc, pCodecVidEnc);
		if(temp < 0) {
			AVERROR_LOOKUP(temp);
			fail("opening codec", "couldn't open encoder codec", TRUE);
		}
	}
	
	// Open decoder
	iCodecOpen = avcodec_open(pCodecCtxAudDec, pCodecAudDec);
	if (cliOpts.verbose) { cout << "avcodec_open (decoder): " << iCodecOpen << "\n"; }
	if (iCodecOpen < 0 ) {
		AVERROR_LOOKUP(iCodecOpen);
		fail("opening codec", "couldn't open decoder codec", TRUE);
	}

	// Open encoder
	iOpenEncoder = avcodec_open(pCodecCtxAudEnc, pCodecAudEnc);
	if (cliOpts.verbose) { cout << "avcodec_open (encoder): " << iOpenEncoder << "\n"; }
	if(iOpenEncoder < 0) {
		AVERROR_LOOKUP(iOpenEncoder);
		fail("opening codec", "couldn't open encoder codec", TRUE);
	}

	// Allocate YUV and RGB memory.
	if (cliOpts.verbose) { cout << "Allocating format conversion colourspace" << "\n"; }
	iRGBFrameSize=avpicture_get_size(PIX_FMT_RGB24, pCodecCtxVidDec->width, pCodecCtxVidDec->height);
	iYUVFrameSize = avpicture_get_size(PIX_FMT_YUV420P, pCodecCtxVidEnc->width, pCodecCtxVidEnc->height);
	iOutBufferSize = 100000;

	if (cliOpts.verbose) {
		cout << "  RGB: " << iRGBFrameSize << " Bytes\n  YUV: " << iYUVFrameSize << " Bytes\n  OUT: " << iOutBufferSize << " Bytes\n";
	}

	pYUVBufferVid = (uint8_t *) malloc((iYUVFrameSize));
	pRGBBufferVid = (uint8_t *) malloc(iRGBFrameSize);
	
	// check we got the buffer we wanted.
	if ( (pRGBBufferVid == NULL) || (pYUVBufferVid == NULL) ) {   
		fail("malloc buffers", "couldn't allocate memory for pFrameRGB or pFrameEnc buffers", TRUE);
	}

	if (cliOpts.verbose) { cout << "Assigning RGB and YUV buffers to AVFrames.\n"; }

	// Assign appropriate parts of buffer to image planes in pFrameRGB and pFrameYUV
	avpicture_fill((AVPicture *)pFrameRGB, pRGBBufferVid, PIX_FMT_RGB24, pCodecCtxVidDec->width, pCodecCtxVidDec->height);  // RGB size
	avpicture_fill((AVPicture *)pFrameEnc, pYUVBufferVid, PIX_FMT_YUV420P, pCodecCtxVidDec->width, pCodecCtxVidDec->height);  // YUV size
	pOutBufferVid = (unsigned char *) av_malloc(iOutBufferSize * sizeof(uint8_t));  // alloc output buffer for encoded datastream
	
	// Allocate Encoding and Decoding Buffers AUDIO
	// Decode output buffer
	iOutbufDecSize = AVCODEC_MAX_AUDIO_FRAME_SIZE;
	outbufDec = (uint8_t *)av_malloc(iOutbufDecSize + FF_INPUT_BUFFER_PADDING_SIZE);

	// Encode output buffer
	iOutbufEncSize = 10000;
	outbufEnc = (uint8_t *)av_malloc(iOutbufEncSize);
	
	// if we want to save video
	if (cliOpts.savevideo) {
		// Open output file handle

		if (cliOpts.verbose) {
			cout << "Opening output video file" << "\n";
		}

		pOutputVideo = fopen(cliOpts.videopath, "wb"); // Write Binary
		test=fopen("test.264","wb");

		if ((pOutputVideo == NULL) && (test == NULL)) {
			cerr << "Could not open " << cliOpts.videopath << "\n";
			fail("opening file handle", "couldn't open file", TRUE);
		}
	}

	// if we want to save the audio
	if (cliOpts.saveaudio) {
		// Open output file handle
		if (cliOpts.verbose) {
			cout << "Opening output audio file" << "\n";
		}
		pOutputAudio = fopen(cliOpts.audiopath, "wb"); // Write Binary
		if (!pOutputAudio) {
			cerr << "Could not open " << cliOpts.audiopath << "\n";
			fail("opening file handle", "couldn't open file", TRUE);
		}
	}

	// Stats file
	pStatisticsFile = fopen("stats.csv", "w");
	
	if(cliOpts.networkport > 0) {	// if the port is greater than 0, we requested it.
		startServerRTSP(20,cliOpts.networkport, (cliOpts.networkport + 5), cliOpts.transport);
	}

	if (cliOpts.verbose) {
		cout << "Entering main processing loop" << "\n";
		cout << "If you would like to have this debugged, run with two verbose options.\nThis will slow the program a lot!\n";
	}

	//boost::thread AudioThread(runAudioLoop);
	//timer start
	cout << "Spawning Server Child Thread" << endl;
	start = stampstart();
	boost::thread VideoThread(runVideoLoop);
	
	// Setup Signal Catcher callback...
	// This lets us exit nicely once the program loop is running.
	cout << "Setting Signal Handler" <<endl;
	signal(SIGINT, signal_handler);		// on signal, we call signal_handler with the sig type as an integer arg

	// fall through this when the stop flag is set.
	while(StopExecution == false) {
		usleep(10*1000*1000);
	}
	cout << "Parent Thread Stop Execution Requested" << endl;
	
	// report back to the user how many frames were processed.
	cout << (long) iFramesDecoded << " frames parsed" << "\n";
	
	if (cliOpts.verbose) {
		cout << "Freeing memory " << "\n";
	}

	// Free frame memory
	av_free(pFrameDec);
	av_free(pFrameEnc);
	av_free(pFrameRGB);
	free(pOutBufferVid);
	free(pRGBBufferVid);
	free(pYUVBufferVid);
	free(outbufDec);
	free(outbufEnc);

	if (cliOpts.verbose) {
		cout << "Freeing codecs " << "\n";
	}

	// Close the codecs
	avcodec_close(pCodecCtxVidDec);
	avcodec_close(pCodecCtxVidEnc);
	
	avcodec_close(pCodecCtxAudDec);
	avcodec_close(pCodecCtxAudEnc);

	if (cliOpts.verbose) {
		cout << "Freeing I/O " << "\n";
	}

	// Close video file
	av_close_input_file(pFormatCtxVidDec);

	// Close the video output file handle IF it was opened
	if (cliOpts.savevideo) {
		if (cliOpts.verbose) {
			cout << "Close Video Dump" << "\n";
		}
		fclose(pOutputVideo);
	}

	// Close the audio output file handle IF it was opened

	if (cliOpts.saveaudio) {
		if (cliOpts.verbose) {
			cout << "Close Audio Dump" << "\n";
		}
		fclose(pOutputAudio);
	}
	
	// close stats file
	fclose(pStatisticsFile);
	
	if (cliOpts.verbose) {
		cout <<"Exiting..." << "\n";
	}

	exit(EXIT_SUCCESS);
}
bool AudioOutputDigitalEncoder::Init(
    CodecID codec_id, int bitrate, int samplerate, int channels)
{
    AVCodec *codec;
    int ret;

    LOG(VB_AUDIO, LOG_INFO, QString("Init codecid=%1, br=%2, sr=%3, ch=%4")
            .arg(ff_codec_id_string(codec_id)) .arg(bitrate)
            .arg(samplerate) .arg(channels));

    // We need to do this when called from mythmusic
    avcodec_init();
    avcodec_register_all();
#if LIBAVCODEC_VERSION_INT > AV_VERSION_INT( 52, 113, 0 )
    codec = avcodec_find_encoder_by_name("ac3_fixed");
#else
    codec = avcodec_find_encoder(CODEC_ID_AC3);
#endif
    if (!codec)
    {
        LOG(VB_GENERAL, LOG_ERR, "Could not find codec");
        return false;
    }

    av_context                 = avcodec_alloc_context();
    avcodec_get_context_defaults3(av_context, codec);

    av_context->bit_rate       = bitrate;
    av_context->sample_rate    = samplerate;
    av_context->channels       = channels;
#if LIBAVCODEC_VERSION_INT > AV_VERSION_INT( 52, 113, 0 )
    av_context->channel_layout = AV_CH_LAYOUT_5POINT1;
    av_context->sample_fmt     = AV_SAMPLE_FMT_S16;
#else
    av_context->channel_layout = CH_LAYOUT_5POINT1;
    av_context->sample_fmt     = SAMPLE_FMT_S16;
#endif

// open it
    ret = avcodec_open(av_context, codec);
    if (ret < 0)
    {
        LOG(VB_GENERAL, LOG_ERR,
            "Could not open codec, invalid bitrate or samplerate");

        Dispose();
        return false;
    }

    if (m_spdifenc)
    {
        delete m_spdifenc;
    }

    m_spdifenc = new SPDIFEncoder("spdif", CODEC_ID_AC3);
    if (!m_spdifenc->Succeeded())
    {
        Dispose();
        LOG(VB_GENERAL, LOG_ERR, "Could not create spdif muxer");
        return false;
    }

    samples_per_frame  = av_context->frame_size * av_context->channels;

    LOG(VB_AUDIO, LOG_INFO, QString("DigitalEncoder::Init fs=%1, spf=%2")
            .arg(av_context->frame_size) .arg(samples_per_frame));

    return true;
}
C_RESULT ffmpeg_stage_decoding_open(ffmpeg_stage_decoding_config_t *cfg)
{
  cfg->num_picture_decoded = 0;
  
  /* must be called before using avcodec lib */
  avcodec_init();
  
  /* register all the codecs */
  avcodec_register_all();
  
  av_log_set_level(FFMPEG_LOG_LEVEL);

  cfg->pCodecMP4 = avcodec_find_decoder (CODEC_ID_MPEG4);
  cfg->pCodecH264 = avcodec_find_decoder (CODEC_ID_H264);
  if(NULL == cfg->pCodecMP4 || NULL == cfg->pCodecH264) 
    {
      fprintf(stderr, "Unsupported codec!\n");
      return C_FAIL; // Codec not found
    }

  cfg->pCodecCtxMP4 = avcodec_alloc_context();
  cfg->pCodecCtxH264 = avcodec_alloc_context();
  if (NULL == cfg->pCodecCtxMP4 || NULL == cfg->pCodecCtxH264)
    {
      fprintf(stderr, "Impossible to allocate codec context\n");
      return C_FAIL; // Allocation failure
    }

  cfg->pCodecCtxMP4->pix_fmt = PIX_FMT_YUV420P;
  cfg->pCodecCtxMP4->skip_frame = AVDISCARD_DEFAULT;
  cfg->pCodecCtxMP4->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK;
  cfg->pCodecCtxMP4->error_recognition = FF_ER_CAREFUL;
  cfg->pCodecCtxMP4->skip_loop_filter = AVDISCARD_DEFAULT;
  cfg->pCodecCtxMP4->workaround_bugs = FF_BUG_AUTODETECT;
  cfg->pCodecCtxMP4->codec_type = AVMEDIA_TYPE_VIDEO;
  cfg->pCodecCtxMP4->codec_id = CODEC_ID_MPEG4;
  cfg->pCodecCtxMP4->skip_idct = AVDISCARD_DEFAULT;
  
  cfg->pCodecCtxH264->pix_fmt = PIX_FMT_YUV420P;
  cfg->pCodecCtxH264->skip_frame = AVDISCARD_DEFAULT;
  cfg->pCodecCtxH264->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK;
  cfg->pCodecCtxH264->error_recognition = FF_ER_CAREFUL;
  cfg->pCodecCtxH264->skip_loop_filter = AVDISCARD_DEFAULT;
  cfg->pCodecCtxH264->workaround_bugs = FF_BUG_AUTODETECT;
  cfg->pCodecCtxH264->codec_type = AVMEDIA_TYPE_VIDEO;
  cfg->pCodecCtxH264->codec_id = CODEC_ID_H264;
  cfg->pCodecCtxH264->skip_idct = AVDISCARD_DEFAULT;
  		
  // Open codec
  if(avcodec_open(cfg->pCodecCtxMP4, cfg->pCodecMP4) < 0)
    {
      fprintf (stderr, "Error opening MP4 codec\n");
      return C_FAIL;
    }
  if(avcodec_open(cfg->pCodecCtxH264, cfg->pCodecH264) < 0)
    {
      fprintf (stderr, "Error opening h264 codec\n");
      return C_FAIL;
    }

  cfg->pFrameOutput = avcodec_alloc_frame();
  cfg->pFrame = avcodec_alloc_frame();
  if (NULL == cfg->pFrameOutput || NULL == cfg->pFrame)
    {
      fprintf (stderr, "Unable to alloc frames");
      return C_FAIL;
    }

  cfg->bufferArray = (uint8_t **)vp_os_malloc (sizeof (uint8_t *));
  if (NULL == cfg->bufferArray)
    {
      fprintf (stderr, "Unable to alloc output buffer");
      return C_FAIL;
    }
  cfg->buffer = NULL;
  cfg->img_convert_ctx = NULL;
  
  return C_OK;
}
示例#13
0
static Bool avr_process ( GF_TermExt *termext, u32 action, void *param )
{
    const char *opt;
    GF_AVRedirect *avr = termext->udta;

    switch ( action )
    {
    case GF_TERM_EXT_START:
        avr->term = ( GF_Terminal * ) param;
        opt = gf_modules_get_option ( ( GF_BaseInterface* ) termext, moduleName, AVR_ENABLED_OPTION );
        if ( !opt )
            gf_modules_set_option ( ( GF_BaseInterface* ) termext, moduleName, AVR_ENABLED_OPTION, "no" );
        if ( !opt || strcmp ( opt, "yes" ) ) return 0;
        opt = gf_modules_get_option ( ( GF_BaseInterface* ) termext, moduleName, AVR_VIDEO_CODEC_OPTION );
        avr->globalLock = gf_global_resource_lock("AVRedirect:output");
        if (!avr->globalLock) {
            GF_LOG(GF_LOG_ERROR, GF_LOG_MODULE, ("Failed to lock global resource 'AVRedirect:output', another GPAC instance must be running, disabling AVRedirect\n"));
            return 0;
        }
        /* must be called before using avcodec lib */
        avcodec_init();

        /* register all the codecs */
        avcodec_register_all();
        if ( !opt )
            gf_modules_set_option ( ( GF_BaseInterface* ) termext, moduleName, AVR_VIDEO_CODEC_OPTION, possibleCodecs );
        {
            if ( !opt )
            {
                avr->videoCodec = avcodec_find_encoder ( CODEC_ID_MPEG2VIDEO );
            }
            else if ( !strcmp ( "MPEG-1", opt ) )
            {
                avr->videoCodec=avcodec_find_encoder ( CODEC_ID_MPEG1VIDEO );
            }
            else if ( !strcmp ( "MPEG-2", opt ) )
            {
                avr->videoCodec=avcodec_find_encoder ( CODEC_ID_MPEG2VIDEO );
            }
            else if ( !strcmp ( "MPEG-4", opt ) )
            {
                avr->videoCodec=avcodec_find_encoder ( CODEC_ID_MPEG4 );
            }
            else if ( !strcmp ( "MSMPEG-4", opt ) )
            {
                avr->videoCodec=avcodec_find_encoder ( CODEC_ID_MSMPEG4V3 );
            }
            else if ( !strcmp ( "H263", opt ) )
            {
                avr->videoCodec=avcodec_find_encoder ( CODEC_ID_H263 );
            }
            else if ( !strcmp ( "RV10", opt ) )
            {
                avr->videoCodec = avcodec_find_encoder ( CODEC_ID_RV10 );
            }
            else if ( !strcmp ( "H263P", opt ) )
            {
                avr->videoCodec=avcodec_find_encoder ( CODEC_ID_H263P );
            }
            else if ( !strcmp ( "H263I", opt ) )
            {
                avr->videoCodec=avcodec_find_encoder ( CODEC_ID_H263I );
            }
            else if ( !strcmp( "MJPEG", opt))
            {
                avr->videoCodec=avcodec_find_encoder( CODEC_ID_MJPEG);
            }
            else
            {
                GF_LOG ( GF_LOG_ERROR, GF_LOG_MODULE, ( "[AVRedirect] Not a known Video codec : %s, using MPEG-2 video instead, %s\n", opt, possibleCodecs ) );
                avr->videoCodec = avcodec_find_encoder ( CODEC_ID_MPEG2VIDEO );
            }
        }
#if REDIRECT_AV_AUDIO_ENABLED
        avr->audioCodec = avcodec_find_encoder(CODEC_ID_MP2);
#endif
        /*
                opt = gf_modules_get_option ( ( GF_BaseInterface* ) termext, moduleName, AVR_UDP_ADDRESS_OPTION);
                if (!opt) {
                    gf_modules_set_option ( ( GF_BaseInterface* ) termext, moduleName, AVR_UDP_ADDRESS_OPTION, DEFAULT_UDP_OUT_ADDRESS);
                    avr->udp_address = DEFAULT_UDP_OUT_ADDRESS;
                    GF_LOG ( GF_LOG_ERROR, GF_LOG_MODULE, ( "[AVRedirect] %s not set, using %s\n", AVR_UDP_ADDRESS_OPTION, DEFAULT_UDP_OUT_ADDRESS ) );
                } else
                    avr->udp_address = opt;
                opt = gf_modules_get_option ( ( GF_BaseInterface* ) termext, moduleName, AVR_UDP_PORT_OPTION);
                if (opt) {
                    char *endPtr = NULL;
                    unsigned int x = strtoul(opt, &endPtr, 10);
                    if (endPtr == opt || x > 65536) {
                        printf("Failed to parse : %s\n", opt);
                        opt = NULL;
                    } else
                        avr->udp_port = (u16) x;
                }
                if (!opt) {
                    gf_modules_set_option ( ( GF_BaseInterface* ) termext, moduleName, AVR_UDP_PORT_OPTION, DEFAULT_UDP_OUT_PORT_STR);
                    GF_LOG ( GF_LOG_ERROR, GF_LOG_MODULE, ( "[AVRedirect] %s is not set or valid, using %s\n", AVR_UDP_PORT_OPTION, DEFAULT_UDP_OUT_PORT_STR ) );
                    avr->udp_port = DEFAULT_UDP_OUT_PORT;
                }
        */
        opt = gf_modules_get_option ( ( GF_BaseInterface* ) termext, moduleName, AVR_DESTINATION);
        if (!opt) {
            gf_modules_set_option ( ( GF_BaseInterface* ) termext, moduleName, AVR_DESTINATION, AVR_DEFAULT_DESTINATION);
            avr->destination = AVR_DEFAULT_DESTINATION;
            GF_LOG ( GF_LOG_ERROR, GF_LOG_MODULE, ( "[AVRedirect] %s not set, using %s\n", AVR_DESTINATION, AVR_DEFAULT_DESTINATION ) );
        } else
            avr->destination = opt;
        avr->audio_listen.udta = avr;
        avr->audio_listen.on_audio_frame = avr_on_audio_frame;
        avr->audio_listen.on_audio_reconfig = avr_on_audio_reconfig;
        avr->video_listen.udta = avr;
        avr->video_listen.on_video_frame = avr_on_video_frame;
        avr->video_listen.on_video_reconfig = avr_on_video_reconfig;

        avr->term_listen.udta = avr;
        avr->term_listen.on_event = avr_on_event;
        gf_term_add_event_filter ( avr->term, &avr->term_listen );
        return 1;

    case GF_TERM_EXT_STOP:
        gf_term_remove_event_filter ( avr->term, &avr->term_listen );
        avr->term = NULL;
        break;

        /*if not threaded, perform our tasks here*/
    case GF_TERM_EXT_PROCESS:
        break;
    }
    return 0;
}
示例#14
0
struct iaxc_video_codec *codec_video_ffmpeg_new(int format, int w, int h,
						     int framerate, int bitrate,
						     int fragsize)
{
	struct encoder_ctx *e;
	struct decoder_ctx *d;
	AVCodec *codec;
	int ff_enc_id, ff_dec_id;
	char *name;

	struct iaxc_video_codec *c = calloc(sizeof(struct iaxc_video_codec), 1);

	if (!c)
	{
		fprintf(stderr,
			"codec_ffmpeg: failed to allocate video context\n");
		return NULL;
	}

	avcodec_init();
	avcodec_register_all();

	c->format = format;
	c->width = w;
	c->height = h;
	c->framerate = framerate;
	c->bitrate = bitrate;
	/* TODO: Is a fragsize of zero valid? If so, there's a divide
	 * by zero error to contend with.
	 */
	c->fragsize = fragsize;

	c->encode = encode;
	c->decode = decode_iaxc_slice;
	c->destroy = destroy;

	c->encstate = calloc(sizeof(struct encoder_ctx), 1);
	if (!c->encstate)
		goto bail;
	e = c->encstate;
	e->avctx = avcodec_alloc_context();
	if (!e->avctx)
		goto bail;
	e->picture = avcodec_alloc_frame();
	if (!e->picture)
		goto bail;
	/* The idea here is that the encoded frame that will land in this
	 * buffer will be no larger than the size of an uncompressed 32-bit
	 * rgb frame.
	 *
	 * TODO: Is this assumption really valid?
	 */
	e->frame_buf_len = w * h * 4;
	e->frame_buf = malloc(e->frame_buf_len);
	if (!e->frame_buf)
		goto bail;

	c->decstate = calloc(sizeof(struct decoder_ctx), 1);
	if (!c->decstate)
		goto bail;
	d = c->decstate;
	d->avctx = avcodec_alloc_context();
	if (!d->avctx)
		goto bail;
	d->picture = avcodec_alloc_frame();
	if (!d->picture)
		goto bail;
	d->frame_buf_len = e->frame_buf_len;
	d->frame_buf = malloc(d->frame_buf_len);
	if (!d->frame_buf)
		goto bail;

	e->slice_header.version = 0;
	srandom(time(0));
	e->slice_header.source_id = random() & 0xffff;

	e->avctx->time_base.num = 1;
	e->avctx->time_base.den = framerate;

	e->avctx->width = w;
	e->avctx->height = h;

	e->avctx->bit_rate = bitrate;

	/* This determines how often i-frames are sent */
	e->avctx->gop_size = framerate * 3;
	e->avctx->pix_fmt = PIX_FMT_YUV420P;
	e->avctx->has_b_frames = 0;

	e->avctx->mb_qmin = e->avctx->qmin = 10;
	e->avctx->mb_qmax = e->avctx->qmax = 10;

	e->avctx->lmin = 2 * FF_QP2LAMBDA;
	e->avctx->lmax = 10 * FF_QP2LAMBDA;
	e->avctx->global_quality = FF_QP2LAMBDA * 2;
	e->avctx->qblur = 0.5;
	e->avctx->global_quality = 10;

	e->avctx->flags |= CODEC_FLAG_PSNR;
	e->avctx->flags |= CODEC_FLAG_QSCALE;

	e->avctx->mb_decision = FF_MB_DECISION_SIMPLE;

	ff_enc_id = ff_dec_id = map_iaxc_codec_to_avcodec(format);

	/* Note, when fragsize is used (non-zero) ffmpeg will use a "best
	 * effort" strategy: the fragment size will be fragsize +/- 20%
	 */

	switch (format)
	{

	case IAXC_FORMAT_H261:
		/* TODO: H261 only works with specific resolutions. */
		name = "H.261";
		break;

	case IAXC_FORMAT_H263:
		/* TODO: H263 only works with specific resolutions. */
		name = "H.263";
		e->avctx->flags |= CODEC_FLAG_AC_PRED;
		if (fragsize)
		{
			c->decode = decode_rtp_slice;
			e->avctx->rtp_payload_size = fragsize;
			e->avctx->flags |=
				CODEC_FLAG_TRUNCATED | CODEC_FLAG2_STRICT_GOP;
			e->avctx->rtp_callback = encode_rtp_callback;
			d->avctx->flags |= CODEC_FLAG_TRUNCATED;
		}
		break;

	case IAXC_FORMAT_H263_PLUS:
		/* Although the encoder is CODEC_ID_H263P, the decoder
		 * is the regular h.263, so we handle this special case
		 * here.
		 */
		ff_dec_id = CODEC_ID_H263;
		name = "H.263+";
		e->avctx->flags |= CODEC_FLAG_AC_PRED;
		if (fragsize)
		{
			c->decode = decode_rtp_slice;
			e->avctx->rtp_payload_size = fragsize;
			e->avctx->flags |=
				CODEC_FLAG_TRUNCATED |
				CODEC_FLAG_H263P_SLICE_STRUCT |
				CODEC_FLAG2_STRICT_GOP |
				CODEC_FLAG2_LOCAL_HEADER;
			e->avctx->rtp_callback = encode_rtp_callback;
			d->avctx->flags |= CODEC_FLAG_TRUNCATED;
		}
		break;

	case IAXC_FORMAT_MPEG4:
		name = "MPEG4";
		c->decode = decode_rtp_slice;
		e->avctx->rtp_payload_size = fragsize;
		e->avctx->rtp_callback = encode_rtp_callback;
		e->avctx->flags |=
			CODEC_FLAG_TRUNCATED |
			CODEC_FLAG_H263P_SLICE_STRUCT |
			CODEC_FLAG2_STRICT_GOP |
			CODEC_FLAG2_LOCAL_HEADER;

		d->avctx->flags |= CODEC_FLAG_TRUNCATED;
		break;

	case IAXC_FORMAT_H264:
		name = "H.264";

		/*
		 * Encoder flags
		 */

		/* Headers are not repeated */
		/* e->avctx->flags |= CODEC_FLAG_GLOBAL_HEADER; */

		/* Slower, less blocky */
		/* e->avctx->flags |= CODEC_FLAG_LOOP_FILTER; */

		e->avctx->flags |= CODEC_FLAG_PASS1;
		/* e->avctx->flags |= CODEC_FLAG_PASS2; */

		/* Compute psnr values at encode-time (avctx->error[]) */
		/* e->avctx->flags |= CODEC_FLAG_PSNR; */

		/* e->avctx->flags2 |= CODEC_FLAG2_8X8DCT; */

		/* Access Unit Delimiters */
		e->avctx->flags2 |= CODEC_FLAG2_AUD;

		/* Allow b-frames to be used as reference */
		/* e->avctx->flags2 |= CODEC_FLAG2_BPYRAMID; */

		/* b-frame rate distortion optimization */
		/* e->avctx->flags2 |= CODEC_FLAG2_BRDO; */

		/* e->avctx->flags2 |= CODEC_FLAG2_FASTPSKIP; */

		/* Multiple references per partition */
		/* e->avctx->flags2 |= CODEC_FLAG2_MIXED_REFS; */

		/* Weighted biprediction for b-frames */
		/* e->avctx->flags2 |= CODEC_FLAG2_WPRED; */

		/*
		 * Decoder flags
		 */

		/* Do not draw edges */
		/* d->avctx->flags |= CODEC_FLAG_EMU_EDGE; */

		/* Decode grayscale only */
		/* d->avctx->flags |= CODEC_FLAG_GRAY; */

		/* d->avctx->flags |= CODEC_FLAG_LOW_DELAY; */

		/* Allow input bitstream to be randomly truncated */
		/* d->avctx->flags |= CODEC_FLAG_TRUNCATED; */

		/* Allow out-of-spec speed tricks */
		/* d->avctx->flags2 |= CODEC_FLAG2_FAST; */
		break;

	case IAXC_FORMAT_THEORA:
		/* TODO: ffmpeg only has a theora decoder. Until it has
		 * an encoder also, we cannot use ffmpeg for theora.
		 */
		name = "Theora";
		break;

	default:
		fprintf(stderr, "codec_ffmpeg: unsupported format (0x%08x)\n",
				format);
		goto bail;
	}

	strcpy(c->name, "ffmpeg-");
	strncat(c->name, name, sizeof(c->name));

	/* Get the codecs */
	codec = avcodec_find_encoder(ff_enc_id);
	if (!codec)
	{
		iaxci_usermsg(IAXC_TEXT_TYPE_ERROR,
			     "codec_ffmpeg: cannot find encoder %d\n",
			     ff_enc_id);
		goto bail;
	}

	if (avcodec_open(e->avctx, codec))
	{
		iaxci_usermsg(IAXC_TEXT_TYPE_ERROR,
			     "codec_ffmpeg: cannot open encoder %s\n", name);
		goto bail;
	}

	codec = avcodec_find_decoder(ff_dec_id);
	if (!codec)
	{
		iaxci_usermsg(IAXC_TEXT_TYPE_ERROR,
			     "codec_ffmpeg: cannot find decoder %d\n",
			     ff_dec_id);
		goto bail;
	}
	if (avcodec_open(d->avctx, codec))
	{
		iaxci_usermsg(IAXC_TEXT_TYPE_ERROR,
			     "codec_ffmpeg: cannot open decoder %s\n", name);
		goto bail;
	}

	{
		enum PixelFormat fmts[] = { PIX_FMT_YUV420P, -1 };
		if (d->avctx->get_format(d->avctx, fmts) != PIX_FMT_YUV420P)
		{
			iaxci_usermsg(IAXC_TEXT_TYPE_ERROR,
					"codec_ffmpeg: cannot set decode format to YUV420P\n");
			goto bail;
		}
	}

	return c;

bail:
	destroy(c);
	return 0;
}
示例#15
0
文件: switcher.c 项目: FLYKingdom/vlc
/*****************************************************************************
 * Open:
 *****************************************************************************/
static int Open( vlc_object_t *p_this )
{
    sout_stream_t     *p_stream = (sout_stream_t*)p_this;
    sout_stream_sys_t *p_sys;
    vlc_value_t       val;
    char              *psz_files, *psz_sizes;
    int               i_height = 0, i_width = 0;

    p_sys = calloc( 1, sizeof(sout_stream_sys_t) );
    if( !p_sys )
        return VLC_ENOMEM;

    p_sys->p_out = sout_StreamNew( p_stream->p_sout, p_stream->psz_next );
    if( !p_sys->p_out )
    {
        msg_Err( p_stream, "cannot create chain" );
        free( p_sys );
        return VLC_EGENERIC;
    }

    config_ChainParse( p_stream, SOUT_CFG_PREFIX, ppsz_sout_options,
                   p_stream->p_cfg );

    var_Get( p_stream, SOUT_CFG_PREFIX "files", &val );
    psz_files = val.psz_string;
    var_Get( p_stream, SOUT_CFG_PREFIX "sizes", &val );
    psz_sizes = val.psz_string;

    p_sys->i_nb_pictures = 0;
    while ( psz_files && *psz_files )
    {
        char * psz_file = psz_files;
        char * psz_size = psz_sizes;

        while ( *psz_files && *psz_files != ':' )
            psz_files++;
        if ( *psz_files == ':' )
           *psz_files++ = '\0';

        if ( *psz_sizes )
        {
            while ( *psz_sizes && *psz_sizes != ':' )
                psz_sizes++;
            if ( *psz_sizes == ':' )
                *psz_sizes++ = '\0';
            if ( sscanf( psz_size, "%dx%d", &i_width, &i_height ) != 2 )
            {
                msg_Err( p_stream, "bad size %s for file %s", psz_size,
                         psz_file );
                free( p_sys );
                return VLC_EGENERIC;
            }
        }

        if ( UnpackFromFile( p_stream, psz_file, i_width, i_height,
                             &p_sys->p_pictures[p_sys->i_nb_pictures] ) < 0 )
        {
            free( p_sys );
            return VLC_EGENERIC;
        }
        p_sys->i_nb_pictures++;
    }

    var_Get( p_stream, SOUT_CFG_PREFIX "aspect-ratio", &val );
    if ( val.psz_string )
    {
        char *psz_parser = strchr( val.psz_string, ':' );

        if( psz_parser )
        {
            *psz_parser++ = '\0';
            p_sys->i_aspect = atoi( val.psz_string ) * VOUT_ASPECT_FACTOR
                / atoi( psz_parser );
        }
        else
        {
            msg_Warn( p_stream, "bad aspect ratio %s", val.psz_string );
            p_sys->i_aspect = 4 * VOUT_ASPECT_FACTOR / 3;
        }

        free( val.psz_string );
    }
    else
    {
        p_sys->i_aspect = 4 * VOUT_ASPECT_FACTOR / 3;
    }

    var_Get( p_stream, SOUT_CFG_PREFIX "port", &val );
    p_sys->i_fd = net_ListenUDP1( VLC_OBJECT(p_stream), NULL, val.i_int );
    if ( p_sys->i_fd < 0 )
    {
        free( p_sys );
        return VLC_EGENERIC;
    }

    var_Get( p_stream, SOUT_CFG_PREFIX "command", &val );
    p_sys->i_cmd = val.i_int;
    p_sys->i_old_cmd = 0;

    var_Get( p_stream, SOUT_CFG_PREFIX "gop", &val );
    p_sys->i_gop = val.i_int;

    var_Get( p_stream, SOUT_CFG_PREFIX "qscale", &val );
    p_sys->i_qscale = val.i_int;

    var_Get( p_stream, SOUT_CFG_PREFIX "mute-audio", &val );
    p_sys->b_audio = val.b_bool;

    p_stream->pf_add    = Add;
    p_stream->pf_del    = Del;
    p_stream->pf_send   = Send;
    p_stream->p_sys     = p_sys;

    avcodec_init();
    avcodec_register_all();

    return VLC_SUCCESS;
}
示例#16
0
// init driver
static int init(sh_video_t *sh){
    struct lavc_param *lavc_param = &sh->opts->lavc_param;
    AVCodecContext *avctx;
    vd_ffmpeg_ctx *ctx;
    AVCodec *lavc_codec;
    int lowres_w=0;
    int do_vis_debug= lavc_param->vismv || (lavc_param->debug&(FF_DEBUG_VIS_MB_TYPE|FF_DEBUG_VIS_QP));

    if(!avcodec_initialized){
        avcodec_init();
        avcodec_register_all();
        avcodec_initialized=1;
    }

    ctx = sh->context = malloc(sizeof(vd_ffmpeg_ctx));
    if (!ctx)
        return 0;
    memset(ctx, 0, sizeof(vd_ffmpeg_ctx));

    lavc_codec = (AVCodec *)avcodec_find_decoder_by_name(sh->codec->dll);
    if(!lavc_codec){
        mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Cannot find codec '%s' in libavcodec...\n", sh->codec->dll);
        uninit(sh);
        return 0;
    }

    if(sh->opts->vd_use_slices && (lavc_codec->capabilities&CODEC_CAP_DRAW_HORIZ_BAND) && !do_vis_debug)
        ctx->do_slices=1;

    if(lavc_codec->capabilities&CODEC_CAP_DR1 && !do_vis_debug && lavc_codec->id != CODEC_ID_H264 && lavc_codec->id != CODEC_ID_INTERPLAY_VIDEO && lavc_codec->id != CODEC_ID_ROQ)
        ctx->do_dr1=1;
    ctx->b_age= ctx->ip_age[0]= ctx->ip_age[1]= 256*256*256*64;
    ctx->ip_count= ctx->b_count= 0;

    ctx->pic = avcodec_alloc_frame();
    ctx->avctx = avcodec_alloc_context();
    avctx = ctx->avctx;
    avctx->opaque = sh;
    avctx->codec_type = CODEC_TYPE_VIDEO;
    avctx->codec_id = lavc_codec->id;

    if (lavc_codec->capabilities & CODEC_CAP_HWACCEL   // XvMC
        || lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
        ctx->do_dr1    = true;
        ctx->do_slices = true;
        lavc_param->threads    = 1;
        avctx->get_format      = get_format;
        avctx->get_buffer      = get_buffer;
        avctx->release_buffer  = release_buffer;
        avctx->reget_buffer    = get_buffer;
        avctx->draw_horiz_band = draw_slice;
        if (lavc_codec->capabilities & CODEC_CAP_HWACCEL)
            mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] XVMC-accelerated "
                   "MPEG-2.\n");
        if (lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
            mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] VDPAU hardware "
                   "decoding.\n");
        avctx->slice_flags = SLICE_FLAG_CODED_ORDER|SLICE_FLAG_ALLOW_FIELD;
    }

    if ( lavc_param->threads == 0 ) {
#if defined(_WIN32)
        lavc_param->threads = pthread_num_processors_np();
#elif defined(__linux__)
        unsigned int bit;
        int np;
        cpu_set_t p_aff;
        memset( &p_aff, 0, sizeof(p_aff) );
        sched_getaffinity( 0, sizeof(p_aff), &p_aff );
        for( np = 0, bit = 0; bit < sizeof(p_aff); bit++ )
            np += (((uint8_t *)&p_aff)[bit / 8] >> (bit % 8)) & 1;

        lavc_param->threads = np;
#elif defined(__BEOS__)
        system_info info;
        get_system_info( &info );
        lavc_param->threads = info.cpu_count;

#elif defined(__MACH__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__)
        int numberOfCPUs;
        size_t length = sizeof( numberOfCPUs );
#ifdef __OpenBSD__
        int mib[2] = { CTL_HW, HW_NCPU };
        if( sysctl(mib, 2, &numberOfCPUs, &length, NULL, 0) )
#else
        if( sysctlbyname("hw.ncpu", &numberOfCPUs, &length, NULL, 0) )
#endif
        {
             numberOfCPUs = 1;
        }
        lavc_param->threads = numberOfCPUs;
#else /* No CPU detection routine available */
        lavc_param->threads = 1;
#endif
    }
示例#17
0
static int module_init(void)
{
	const uint8_t profile_idc = 0x42; /* baseline profile */
	const uint8_t profile_iop = 0x80;
	int err = 0;

	if (re_snprintf(h264_fmtp, sizeof(h264_fmtp),
			"packetization-mode=0;profile-level-id=%02x%02x%02x"
#if 0
			";max-mbps=35000"
			";max-fs=3600"
			";max-smbps=98875"  /* times 4 for full HD */
#endif
			"",
			profile_idc, profile_iop, h264_level_idc) < 0)
		return ENOMEM;

#ifdef USE_X264
	re_printf("x264 build %d\n", X264_BUILD);
#else
	re_printf("using FFmpeg H.264 encoder\n");
#endif

#if LIBAVCODEC_VERSION_INT < ((53<<16)+(10<<8)+0)
	avcodec_init();
#endif

	avcodec_register_all();

#if 0
	av_log_set_level(AV_LOG_WARNING);
#endif

	if (avcodec_find_decoder(CODEC_ID_H264)) {

		/* XXX: add two h264 codecs */
		err |= vidcodec_register(&h264, 0,    "H264",
					 h264_fmtp,
					 alloc,
#ifdef USE_X264
					 enc_x264,
#else
					 enc,
#endif
					 h264_nal_send,
					 dec_h264, h264_fmtp_cmp);
	}

	if (avcodec_find_decoder(CODEC_ID_H263)) {

		err |= vidcodec_register(&h263, "34", "H263",
					 "F=1;CIF=1;CIF4=1",
					 alloc, enc, NULL, dec_h263, NULL);
	}

	if (avcodec_find_decoder(CODEC_ID_MPEG4)) {

		err |= vidcodec_register(&mpg4, 0, "MP4V-ES",
					 "profile-level-id=3",
					 alloc, enc, NULL, dec_mpeg4, NULL);
	}

	return err;
}
示例#18
0
SignalMonitor *SignalMonitor::Init(QString cardtype, int db_cardnum,
                                   ChannelBase *channel)
{
    (void) cardtype;
    (void) db_cardnum;
    (void) channel;

    SignalMonitor *signalMonitor = NULL;

    {
        QMutexLocker locker(avcodeclock);
        avcodec_init();
    }

#ifdef USING_DVB
    if (CardUtil::IsDVBCardType(cardtype))
    {
        DVBChannel *dvbc = dynamic_cast<DVBChannel*>(channel);
        if (dvbc)
            signalMonitor = new DVBSignalMonitor(db_cardnum, dvbc);
    }
#endif

#ifdef USING_V4L
    if ((cardtype.toUpper() == "HDPVR"))
    {
        V4LChannel *chan = dynamic_cast<V4LChannel*>(channel);
        if (chan)
            signalMonitor = new AnalogSignalMonitor(db_cardnum, chan);
    }
#endif

#ifdef USING_HDHOMERUN
    if (cardtype.toUpper() == "HDHOMERUN")
    {
        HDHRChannel *hdhrc = dynamic_cast<HDHRChannel*>(channel);
        if (hdhrc)
            signalMonitor = new HDHRSignalMonitor(db_cardnum, hdhrc);
    }
#endif

#ifdef USING_IPTV
    if (cardtype.toUpper() == "FREEBOX")
    {
        IPTVChannel *fbc = dynamic_cast<IPTVChannel*>(channel);
        if (fbc)
            signalMonitor = new IPTVSignalMonitor(db_cardnum, fbc);
    }
#endif

#ifdef USING_FIREWIRE
    if (cardtype.toUpper() == "FIREWIRE")
    {
        FirewireChannel *fc = dynamic_cast<FirewireChannel*>(channel);
        if (fc)
            signalMonitor = new FirewireSignalMonitor(db_cardnum, fc);
    }
#endif

    if (!signalMonitor)
    {
        // For anything else
        if (channel)
            signalMonitor = new ChannelChangeMonitor(db_cardnum, channel);
    }

    if (!signalMonitor)
    {
        VERBOSE(VB_IMPORTANT,
                QString("Failed to create signal monitor in Init(%1, %2, 0x%3)")
                .arg(cardtype).arg(db_cardnum).arg((long)channel,0,16));
    }

    return signalMonitor;
}
示例#19
0
/**
 * Initialize libavformat and register all the (de)muxers and protocols.
 */
void av_register_all(void)
{
    static int inited;

    if (inited)
        return;
    inited = 1;

    avcodec_init();
    avcodec_register_all();

    /* (de)muxers */
    REGISTER_DEMUXER  (AAC, aac);
    REGISTER_MUXDEMUX (AC3, ac3);
    REGISTER_MUXER    (ADTS, adts);
    REGISTER_MUXDEMUX (AIFF, aiff);
    REGISTER_MUXDEMUX (AMR, amr);
    REGISTER_DEMUXER  (APC, apc);
    REGISTER_DEMUXER  (APE, ape);
    REGISTER_MUXDEMUX (ASF, asf);
    REGISTER_MUXER    (ASF_STREAM, asf_stream);
    REGISTER_MUXDEMUX (AU, au);
    REGISTER_MUXDEMUX (AVI, avi);
    REGISTER_DEMUXER  (AVISYNTH, avisynth);
    REGISTER_DEMUXER  (AVS, avs);
    REGISTER_DEMUXER  (BETHSOFTVID, bethsoftvid);
    REGISTER_DEMUXER  (C93, c93);
    REGISTER_MUXER    (CRC, crc);
    REGISTER_DEMUXER  (DAUD, daud);
    REGISTER_DEMUXER  (DSICIN, dsicin);
    REGISTER_DEMUXER  (DTS, dts);
    REGISTER_MUXDEMUX (DV, dv);
    REGISTER_DEMUXER  (DXA, dxa);
    REGISTER_DEMUXER  (EA, ea);
    REGISTER_DEMUXER  (EA_CDATA, ea_cdata);
    REGISTER_MUXDEMUX (FFM, ffm);
    REGISTER_MUXDEMUX (FLAC, flac);
    REGISTER_DEMUXER  (FLIC, flic);
    REGISTER_MUXDEMUX (FLV, flv);
    REGISTER_DEMUXER  (FOURXM, fourxm);
    REGISTER_MUXER    (FRAMECRC, framecrc);
    REGISTER_MUXDEMUX (GIF, gif);
    REGISTER_MUXDEMUX (GXF, gxf);
    REGISTER_MUXDEMUX (H261, h261);
    REGISTER_MUXDEMUX (H263, h263);
    REGISTER_MUXDEMUX (H264, h264);
    REGISTER_DEMUXER  (IDCIN, idcin);
    REGISTER_MUXDEMUX (IMAGE2, image2);
    REGISTER_MUXDEMUX (IMAGE2PIPE, image2pipe);
    REGISTER_DEMUXER  (INGENIENT, ingenient);
    REGISTER_DEMUXER  (IPMOVIE, ipmovie);
    REGISTER_MUXDEMUX (M4V, m4v);
    REGISTER_MUXDEMUX (MATROSKA, matroska);
    REGISTER_MUXER    (MATROSKA_AUDIO, matroska_audio);
    REGISTER_MUXDEMUX (MJPEG, mjpeg);
    REGISTER_DEMUXER  (MM, mm);
    REGISTER_MUXDEMUX (MMF, mmf);
    REGISTER_MUXDEMUX (MOV, mov);
    REGISTER_MUXER    (MP2, mp2);
    REGISTER_MUXDEMUX (MP3, mp3);
    REGISTER_MUXER    (MP4, mp4);
    REGISTER_DEMUXER  (MPC, mpc);
    REGISTER_DEMUXER  (MPC8, mpc8);
    REGISTER_MUXER    (MPEG1SYSTEM, mpeg1system);
    REGISTER_MUXER    (MPEG1VCD, mpeg1vcd);
    REGISTER_MUXER    (MPEG1VIDEO, mpeg1video);
    REGISTER_MUXER    (MPEG2DVD, mpeg2dvd);
    REGISTER_MUXER    (MPEG2SVCD, mpeg2svcd);
    REGISTER_MUXER    (MPEG2VIDEO, mpeg2video);
    REGISTER_MUXER    (MPEG2VOB, mpeg2vob);
    REGISTER_DEMUXER  (MPEGPS, mpegps);
    REGISTER_MUXDEMUX (MPEGTS, mpegts);
    REGISTER_DEMUXER  (MPEGTSRAW, mpegtsraw);
    REGISTER_DEMUXER  (MPEGVIDEO, mpegvideo);
    REGISTER_MUXER    (MPJPEG, mpjpeg);
    REGISTER_DEMUXER  (MTV, mtv);
    REGISTER_DEMUXER  (MXF, mxf);
    REGISTER_DEMUXER  (NSV, nsv);
    REGISTER_MUXER    (NULL, null);
    REGISTER_MUXDEMUX (NUT, nut);
    REGISTER_DEMUXER  (NUV, nuv);
    REGISTER_MUXDEMUX (OGG, ogg);
    REGISTER_MUXDEMUX (PCM_ALAW,  pcm_alaw);
    REGISTER_MUXDEMUX (PCM_MULAW, pcm_mulaw);
    REGISTER_MUXDEMUX (PCM_S16BE, pcm_s16be);
    REGISTER_MUXDEMUX (PCM_S16LE, pcm_s16le);
    REGISTER_MUXDEMUX (PCM_S8,    pcm_s8);
    REGISTER_MUXDEMUX (PCM_U16BE, pcm_u16be);
    REGISTER_MUXDEMUX (PCM_U16LE, pcm_u16le);
    REGISTER_MUXDEMUX (PCM_U8,    pcm_u8);
    REGISTER_MUXER    (PSP, psp);
    REGISTER_MUXDEMUX (RAWVIDEO, rawvideo);
    REGISTER_MUXDEMUX (RM, rm);
    REGISTER_MUXDEMUX (ROQ, roq);
    REGISTER_DEMUXER  (REDIR, redir);
    REGISTER_MUXER    (RTP, rtp);
    REGISTER_DEMUXER  (RTSP, rtsp);
    REGISTER_DEMUXER  (SDP, sdp);
#ifdef CONFIG_RTP_MUXER
    av_register_rtp_dynamic_payload_handlers();
#endif
    REGISTER_DEMUXER  (SEGAFILM, segafilm);
    REGISTER_DEMUXER  (SHORTEN, shorten);
    REGISTER_DEMUXER  (SIFF, siff);
    REGISTER_DEMUXER  (SMACKER, smacker);
    REGISTER_DEMUXER  (SOL, sol);
    REGISTER_DEMUXER  (STR, str);
    REGISTER_MUXDEMUX (SWF, swf);
    REGISTER_MUXER    (TG2, tg2);
    REGISTER_MUXER    (TGP, tgp);
    REGISTER_DEMUXER  (THP, thp);
    REGISTER_DEMUXER  (TIERTEXSEQ, tiertexseq);
    REGISTER_DEMUXER  (TTA, tta);
    REGISTER_DEMUXER  (TXD, txd);
    REGISTER_DEMUXER  (VC1, vc1);
    REGISTER_DEMUXER  (VMD, vmd);
    REGISTER_MUXDEMUX (VOC, voc);
    REGISTER_MUXDEMUX (WAV, wav);
    REGISTER_DEMUXER  (WC3, wc3);
    REGISTER_DEMUXER  (WSAUD, wsaud);
    REGISTER_DEMUXER  (WSVQA, wsvqa);
    REGISTER_DEMUXER  (WV, wv);
    REGISTER_MUXDEMUX (YUV4MPEGPIPE, yuv4mpegpipe);

    /* external libraries */
    REGISTER_MUXDEMUX (LIBNUT, libnut);

    /* protocols */
    REGISTER_PROTOCOL (FILE, file);
    REGISTER_PROTOCOL (HTTP, http);
    REGISTER_PROTOCOL (PIPE, pipe);
    REGISTER_PROTOCOL (RTP, rtp);
    REGISTER_PROTOCOL (TCP, tcp);
    REGISTER_PROTOCOL (UDP, udp);
}
示例#20
0
int mpae_init_lavc(audio_encoder_t *encoder)
{
	encoder->params.samples_per_frame = encoder->params.sample_rate;
	encoder->params.bitrate = encoder->params.sample_rate * encoder->params.channels * 2 * 8;
	
	if(!lavc_param_acodec)
	{
		mp_msg(MSGT_MENCODER, MSGL_FATAL, MSGTR_NoLavcAudioCodecName);
		return 0;
	}

	if(!avcodec_inited){
		avcodec_init();
		avcodec_register_all();
		avcodec_inited=1;
	}

	lavc_acodec = avcodec_find_encoder_by_name(lavc_param_acodec);
	if (!lavc_acodec)
	{
		mp_msg(MSGT_MENCODER, MSGL_FATAL, MSGTR_LavcAudioCodecNotFound, lavc_param_acodec);
		return 0;
	}
	if(lavc_param_atag == 0)
	{
#if defined(USE_LIBAVFORMAT) ||  defined(USE_LIBAVFORMAT_SO)
		lavc_param_atag = av_codec_get_tag(mp_wav_taglists, lavc_acodec->id);
#else
		lavc_param_atag = lavc_find_atag(lavc_param_acodec);
#endif
		if(!lavc_param_atag)
		{
			mp_msg(MSGT_MENCODER, MSGL_FATAL, "Couldn't find wav tag for specified codec, exit\n");
			return 0;
		}
	}

	lavc_actx = avcodec_alloc_context();
	if(lavc_actx == NULL)
	{
		mp_msg(MSGT_MENCODER, MSGL_FATAL, MSGTR_CouldntAllocateLavcContext);
		return 0;
	}
	
	// put sample parameters
	lavc_actx->channels = encoder->params.channels;
	lavc_actx->sample_rate = encoder->params.sample_rate;
	lavc_actx->bit_rate = encoder->params.bitrate = lavc_param_abitrate * 1000;
	

	/*
	* Special case for adpcm_ima_wav.
	* The bitrate is only dependent on samplerate.
	* We have to known frame_size and block_align in advance,
	* so I just copied the code from libavcodec/adpcm.c
	*
	* However, ms adpcm_ima_wav uses a block_align of 2048,
	* lavc defaults to 1024
	*/
	if(lavc_param_atag == 0x11) {
		int blkalign = 2048;
		int framesize = (blkalign - 4 * lavc_actx->channels) * 8 / (4 * lavc_actx->channels) + 1;
		lavc_actx->bit_rate = lavc_actx->sample_rate*8*blkalign/framesize;
	}
        if((lavc_param_audio_global_header&1)
        /*|| (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))*/){
                lavc_actx->flags |= CODEC_FLAG_GLOBAL_HEADER;
        }
        if(lavc_param_audio_global_header&2){
                lavc_actx->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
        }

	if(avcodec_open(lavc_actx, lavc_acodec) < 0)
	{
		mp_msg(MSGT_MENCODER, MSGL_FATAL, MSGTR_CouldntOpenCodec, lavc_param_acodec, lavc_param_abitrate);
		return 0;
	}

	if(lavc_param_atag == 0x11) {
		lavc_actx->block_align = 2048;
		lavc_actx->frame_size = (lavc_actx->block_align - 4 * lavc_actx->channels) * 8 / (4 * lavc_actx->channels) + 1;
	}

	encoder->decode_buffer_size = lavc_actx->frame_size * 2 * encoder->params.channels;
	encoder->bind = bind_lavc;
	encoder->get_frame_size = get_frame_size;
	encoder->encode = encode_lavc;
	encoder->close = close_lavc;

	return 1;
}
	// initialization taken from plugin h263-1998 in opal-2.8.0
	bool VideoEncoderFfmpeg::InitEncoder(int bitrate, int fps, int width, int height,
			int fragsize, int *fragcount, const char *enc_params)
	{
		if (!VideoEncoder::InitEncoder(bitrate, fps, width, height, fragsize, fragcount, enc_params))
			goto InitEncoder_ErrInitParent;

		avcodec_init();
		avcodec_register_all();

		// codec
		codec_ = avcodec_find_encoder(GetCodecId());
		if (NULL == codec_)
			goto InitEncoder_ErrFindEncoder;

		// frame
		input_buffer_size_ = width * height * 3 / 2;
		input_buffer_ = static_cast<unsigned char *>(
			_aligned_malloc(input_buffer_size_, kMemAlign));
		frame_ = avcodec_alloc_frame();
		if (NULL == frame_)
			goto InitEncoder_ErrAllocFrame;
		frame_->data[0] = input_buffer_;
		frame_->data[1] = frame_->data[0] + width * height;
		frame_->data[2] = frame_->data[1] + width * height / 4;
		frame_->linesize[0] = width;
		frame_->linesize[1] =
		frame_->linesize[2] = width / 2;

		// context
		context_ = avcodec_alloc_context3(codec_);
		if (NULL == context_)
			goto InitEncoder_ErrAllocContext;
		context_->pix_fmt = PIX_FMT_YUV420P;
		context_->width = width;
		context_->height = height;
		context_->time_base.num = 1;
		context_->time_base.den = fps;
		context_->gop_size = param_video()->GetGopSize();

		context_->flags = CODEC_FLAG_INPUT_PRESERVED
			| CODEC_FLAG_EMU_EDGE
			| CODEC_FLAG_PASS1
			| GetFlags();
		context_->mb_decision = FF_MB_DECISION_SIMPLE;
		context_->me_method = ME_EPZS;
		context_->max_b_frames = 0;
		
		// target bitrate
		context_->bit_rate = bitrate * 3 / 4;
		context_->bit_rate_tolerance = bitrate / 2;
		context_->rc_min_rate = 0;
		context_->rc_max_rate = bitrate;
		context_->rc_buffer_size = bitrate / 1000;

		/* ratecontrol qmin qmax limiting method
		 0-> clipping, 1-> use a nice continous function to limit qscale wthin qmin/qmax.
		*/  
		context_->rc_qsquish = 0;            // limit q by clipping 
		context_->rc_eq = (char*) "1";       // rate control equation
		context_->rc_buffer_size = bitrate * 64;

		// temporal spatial trade off
		context_->max_qdiff = 10;  // was 3      // max q difference between frames
		context_->qcompress = 0.5;               // qscale factor between easy & hard scenes (0.0-1.0)
		context_->i_quant_factor = (float)-0.6;  // qscale factor between p and i frames
		context_->i_quant_offset = (float)0.0;   // qscale offset between p and i frames
		context_->me_subpel_quality = 8;

		context_->qmin = MIN_QUANT;
		context_->qmax = static_cast<int>(round ( (31.0 - MIN_QUANT) / 31.0 * GetTsto() + MIN_QUANT));
		context_->qmax = min(context_->qmax, 31);

		// TODO: vedere come mapparli in ffmpeg 0.10.3
		//context_->mb_qmin = context_->qmin;
		//context_->mb_qmax = context_->qmax;

		// Lagrange multipliers - this is how the context defaults do it:
		context_->lmin = context_->qmin * FF_QP2LAMBDA;
		context_->lmax = context_->qmax * FF_QP2LAMBDA; 

		context_->debug = FF_DEBUG_RC | FF_DEBUG_PICT_INFO | FF_DEBUG_MV;

		// frammentazione
		if (fragsize > 0) {
			context_->opaque = GetOpaque();
			context_->rtp_payload_size = 1; // if I leave 0, ffmpeg doesn't split at gobs, if I use a large value
				// ffmpeg aggregates gobs without inserting gob headers
		}

		if (0 != avcodec_open2(context_, codec_, &opts_)) {
			goto InitEncoder_ErrOpenCodec;
		}
		return true;

InitEncoder_ErrOpenCodec:
		avcodec_close(context_);
		av_free(context_);
		context_ = NULL;
InitEncoder_ErrAllocContext:
		av_free(frame_);	
		frame_ = NULL;
InitEncoder_ErrAllocFrame:
		codec_ = NULL;
		_aligned_free(input_buffer_);
		input_buffer_ = NULL;
		input_buffer_size_ = 0;
InitEncoder_ErrFindEncoder:
		VideoEncoder::DestroyEncoder();
InitEncoder_ErrInitParent:
		return false;
	}
示例#22
0
文件: IoAVCodec.c 项目: BMeph/io
void IoAVCodec_registerIfNeeded(IoAVCodec *self)
{
	avcodec_init();
	avcodec_register_all();
	av_register_all();
}
示例#23
0
int main(int argc, char *argv[])
{
// Check for big files

#ifdef     __USE_LARGEFILE
#ifdef   __USE_LARGEFILE64
printf("\n LARGE FILE AVAILABLE : %d offset\n",  __USE_FILE_OFFSET64	);
#endif
#endif

/*
	Initialize Gettext if available
*/
#ifdef HAVE_DCGETTEXT
  setlocale (LC_ALL, "");

//#define ALOCALES "/usr/local/share/locale"
  bindtextdomain ("avidemux", ADMLOCALE);
  textdomain ("avidemux");
  printf("Locales for %s appear to be in %s\n","avidemux", ADMLOCALE);
  printf("\nI18N : %s \n",dgettext("avidemux","_File"));
#endif



// thx smurf uk :)
     signal(11, sig_segfault_handler); // show stacktrace on default

	printf("\n*******************\n");
	printf("  Avidemux 2, v  " VERSION "\n");
	printf("*******************\n");
	printf(" http://fixounet.free.fr/avidemux\n");
	printf(" Code      : Mean & JSC \n");
	printf(" GFX       : Nestor Di , [email protected]\n");
	printf(" Testing   : Jakub Misak\n");
	printf(" FreeBSD   : Anish Mistry, [email protected]\n");


#if (defined( ARCH_X86)  || defined(ARCH_X86_64))
	printf("Arcc X86 X86_64 activated.\n"); 	
#endif
   

#ifdef USE_XX_XVID_CVS
	printf("Probing XvidCVS library....\n");
 	dloadXvidCVS(  );
#endif
   VPInitLibrary();
   register_Encoders( );
    atexit(onexit);

#ifndef CYG_MANGLING    
    g_thread_init(NULL);
    gdk_threads_init();
#endif
    gdk_threads_enter();
    gtk_set_locale();
    gtk_init(&argc, &argv);
    gdk_rgb_init();
#ifdef USE_XVID_4
	xvid4_init();
#endif
        initFileSelector();
	CpuCaps::init();
	ADM_InitMemcpy();
	
// Load .avidemuxrc
    quotaInit();
    prefs->load();

   if(!initGUI())
    	{
		printf("\n Fatal : could not init GUI\n");
		exit(-1);	
	}

    video_body = new ADM_Composer;
#ifdef HAVE_ENCODER
     registerVideoFilters(  );
#endif
     
#ifdef USE_FFMPEG
  
                		avcodec_init();
	                 	avcodec_register_all();
				mpegps_init();
	                  
#endif
#ifdef HAVE_AUDIO
    AVDM_audioInit();
#endif    
    buildDistMatrix();
    initScaleTab();

    loadEncoderConfig();
    COL_init();
    
   
    if (argc >= 2)
    {
			  global_argc=argc;
			  global_argv=argv;
			  gtk_timeout_add( 300, (GtkFunction )automation, NULL );
				//automation();				
		}
   #ifdef USE_SDL
   	printf("Global SDL init...\n");
   	SDL_Init(0); //SDL_INIT_AUDIO+SDL_INIT_VIDEO);
   #endif
    oplug_mpegInit();
	if(SpidermonkeyInit() == true)
		printf("Spidermonkey initialized.\n");
	gtk_main();
	gdk_threads_leave();

    return 0;
}
示例#24
0
int main(int argc, char** argv)
{

  char *outfilename = "outfile";
  int reclength= -1; // reclength in secs
 char c;


  /////////////////////////////////////////////////////
  //  CHECKING AND INTERPRETING COMMAND LINE SWITCHES
  /////////////////////////////////////////////////////
 printf("\n*********************************************************************\n");
 printf("\n FFV1rec based on nuppelrec by Roman Hochleitner");
 printf("\n version "_VERSION_"\n");
 printf("\n*********************************************************************\n");
  quiet = 0;
  
	avcodec_init();
	avcodec_register_all();
	
  recordaudio = 1;
  memset(&ainfo,0,sizeof(ainfo));
  ainfo.frequency=44100;

  tzone.tz_minuteswest=-60; // whatever
  tzone.tz_dsttime=0;
  now.tv_sec=0; // reset
  now.tv_usec=0; // reset

  parseRcFile();

  while ((c=getopt(argc,argv,"d:b:M:q:l:c:C:S:W:H:t:NTV:A:a:srf:pnb:x:y:zQ2")) != -1) {
    switch(c) {
      case '2': do_split=1;break;
      case 'b': ainfo.frequency=atoi(optarg);break;
      case 'q': info.quality = atoi(optarg); break;
      case 'd': if(!(info.keydist = atoi(optarg))) info.keydist=1; break;
      case 'M': info.me = atoi(optarg); break;
      case 'S': info.channel = atoi(optarg); break;
      case 'W': info.width = atoi(optarg);  break;
      case 'H': info.height = atoi(optarg);  break;
      case 't': drec = atof(optarg);  break;
      case 'x': videomegs = atoi(optarg);  break;
      case 'C': if(!FFV1_selectByName(optarg))
      				{
					printf("\n cannot find this codec\n");
					exit(0);
				};break;
      case 'y': audiomegs = atoi(optarg);  break;
      case 'p': info.ntsc = 0;  break;
      case 'n': info.ntsc = 1;  break;
      case 's': info.ntsc = 0; info.secam=1;  break;
      case 'f': info.frequency = atof(optarg); break;
      case 'z': recordaudio = 0;printf("\n Audio disabled\n");   break;
      case 'A': audiodevice = optarg;   break;
      case 'V': videodevice = optarg;   break;
      case 'Q': quiet = 1;   break;
      case 'h': usage();  break;

      default: usage();
    }
  }

  if (optind==argc) usage();
  else outfilename=argv[optind];

  if (drec != -1.0) {
    reclength = (int)(drec*60);
  }

 if(info.width==0)
 {
 	info.width=352;
}
if(info.height==0)
{
	if(info.ntsc) 	info.height=240;
	else			info.height=288;
  }
  /////////////////////////////////////////////
  //  CALCULATE BUFFER SIZES
  /////////////////////////////////////////////

  video_buffer_size=(info.height*info.width*3)>>1  ;


  if (videomegs == -1) {
    if (info.width>=480 || info.height>288) {
      videomegs = 64; //drRocket -> helps  megs for big ones
    } else {
      videomegs = 14;  // normally we don't need more than that
    }
  }
  video_buffer_count = (videomegs*1024*1024)/video_buffer_size;

  // we have to detect audio_buffer_size, too before initshm()
  // or we crash horribly later, if no audio is recorded we
  // don't change the value of 16384
  if (recordaudio)
  {
    if (!audioDevPreinit(audiodevice,&ainfo))
     {
      fprintf(stderr,"error: could not detect audio blocksize, audio recording disabled\n");
      recordaudio = 0;
    }
  }

  if (audiomegs==-1) audiomegs=2;

  if (ainfo.bufferSize!=0) audio_buffer_count = (audiomegs*1000*1000)/ainfo.bufferSize;
                       else audio_buffer_count = 1;

  fprintf(stderr,
          "we are using %dx%ldB video (frame-) buffers and\n %dx%ldB audio blocks\n audio fq=%ld\n",
                  video_buffer_count, video_buffer_size,
                  audio_buffer_count, ainfo.bufferSize,
		  ainfo.frequency );



	initBuffers();
  /////////////////////////////////////////////
  //  NOW START WRITER/ENCODER PROCESS
  /////////////////////////////////////////////

	writeInit(&info);

	PTHR *wr;
	wr=(PTHR *)&write_process;

	pthread_create(&pid_write,0,wr,outfilename);
  ///////////////////////////
  // now save the start time
  gettimeofday(&stm, &tzone);

// #ifndef TESTINPUT
  /////////////////////////////////////////////
  //  NOW START AUDIO RECORDER
  /////////////////////////////////////////////

  if (recordaudio)
   {
	printf("Initializing audio...\n");
      	if(!	initAudioDev(audiodevice,&ainfo))
	{
		fprintf(stderr, "cannot initialize audio!\n");
		exit(-1);
	}
	PTHR *aud;
	aud=(PTHR *)&captureAudioDev;
	pthread_create(&pid_audio,0,aud,NULL);
 }
 else
 {
	printf("No audio.\n");
 }

// #endif

  /////////////////////////////////////////////
  //  NOW START VIDEO RECORDER
  /////////////////////////////////////////////

  // only root can do this
  if (getuid()==0) nice(-10);


	if( !initVideoDev(videodevice, &info ))
	{
		printf(" Cannot init video input\n");
		exit(0);
	}
	captureVideoDev();

	return 0;
}
示例#25
0
WmaDecoder::WmaDecoder()
{
    avcodec_init();
    avcodec_register_all();
    av_register_all();
}
示例#26
0
static int init(sh_audio_t *sh_audio)
{
    int x;
    AVCodecContext *lavc_context;
    AVCodec *lavc_codec;

    mp_msg(MSGT_DECAUDIO,MSGL_V,"FFmpeg's libavcodec audio codec\n");
    if(!avcodec_inited){
      avcodec_init();
      avcodec_register_all();
      avcodec_inited=1;
    }
    
    lavc_codec = (AVCodec *)avcodec_find_decoder_by_name(sh_audio->codec->dll);
    if(!lavc_codec){
	mp_msg(MSGT_DECAUDIO,MSGL_ERR,MSGTR_MissingLAVCcodec,sh_audio->codec->dll);
	return 0;
    }
    
    lavc_context = avcodec_alloc_context();
    sh_audio->context=lavc_context;

    if(sh_audio->wf){
	lavc_context->channels = sh_audio->wf->nChannels;
	lavc_context->sample_rate = sh_audio->wf->nSamplesPerSec;
	lavc_context->bit_rate = sh_audio->wf->nAvgBytesPerSec * 8;
	lavc_context->block_align = sh_audio->wf->nBlockAlign;
	lavc_context->bits_per_sample = sh_audio->wf->wBitsPerSample;
    }
    lavc_context->codec_tag = sh_audio->format; //FOURCC
    lavc_context->codec_id = lavc_codec->id; // not sure if required, imho not --A'rpi

    /* alloc extra data */
    if (sh_audio->wf && sh_audio->wf->cbSize > 0) {
        lavc_context->extradata = av_mallocz(sh_audio->wf->cbSize + FF_INPUT_BUFFER_PADDING_SIZE);
        lavc_context->extradata_size = sh_audio->wf->cbSize;
        memcpy(lavc_context->extradata, (char *)sh_audio->wf + sizeof(WAVEFORMATEX), 
               lavc_context->extradata_size);
    }

    // for QDM2
    if (sh_audio->codecdata_len && sh_audio->codecdata && !lavc_context->extradata)
    {
        lavc_context->extradata = av_malloc(sh_audio->codecdata_len);
        lavc_context->extradata_size = sh_audio->codecdata_len;
        memcpy(lavc_context->extradata, (char *)sh_audio->codecdata, 
               lavc_context->extradata_size);	
    }

    /* open it */
    if (avcodec_open(lavc_context, lavc_codec) < 0) {
        mp_msg(MSGT_DECAUDIO,MSGL_ERR, MSGTR_CantOpenCodec);
        return 0;
    }
   mp_msg(MSGT_DECAUDIO,MSGL_V,"INFO: libavcodec init OK!\n");
   
//   printf("\nFOURCC: 0x%X\n",sh_audio->format);
   if(sh_audio->format==0x3343414D){
       // MACE 3:1
       sh_audio->ds->ss_div = 2*3; // 1 samples/packet
       sh_audio->ds->ss_mul = 2*sh_audio->wf->nChannels; // 1 byte*ch/packet
   } else
   if(sh_audio->format==0x3643414D){
       // MACE 6:1
       sh_audio->ds->ss_div = 2*6; // 1 samples/packet
       sh_audio->ds->ss_mul = 2*sh_audio->wf->nChannels; // 1 byte*ch/packet
   }

   // Decode at least 1 byte:  (to get header filled)
   x=decode_audio(sh_audio,sh_audio->a_buffer,1,sh_audio->a_buffer_size);
   if(x>0) sh_audio->a_buffer_len=x;

  sh_audio->channels=lavc_context->channels;
  sh_audio->samplerate=lavc_context->sample_rate;
  sh_audio->i_bps=lavc_context->bit_rate/8;
  if(sh_audio->wf){
      // If the decoder uses the wrong number of channels all is lost anyway.
      // sh_audio->channels=sh_audio->wf->nChannels;
      if (sh_audio->wf->nSamplesPerSec)
      sh_audio->samplerate=sh_audio->wf->nSamplesPerSec;
      if (sh_audio->wf->nAvgBytesPerSec)
      sh_audio->i_bps=sh_audio->wf->nAvgBytesPerSec;
  }
  sh_audio->samplesize=2;
  return 1;
}
示例#27
0
void InitDecoder()
{
	avcodec_init();
}
示例#28
0
文件: tdav.c 项目: shanlq/doubango
int tdav_init()
{
    int ret = 0;

    if(__b_initialized) {
        TSK_DEBUG_INFO("TINYDAV already initialized");
        return 0;
    }

    /* === OS specific === */
#if TDAV_UNDER_WINDOWS
    if ((ret = tdav_win32_init())) {
        return ret;
    }
#elif TDAV_UNDER_APPLE
    if ((ret = tdav_apple_init())) {
        return ret;
    }
#endif

    /* === Initialize ffmpeg === */
#if HAVE_FFMPEG
#   if LIBAVCODEC_VERSION_MAJOR <= 53
    avcodec_init();
#   endif
#endif

    /* === stand-alone plugins === */
#if TDAV_HAVE_PLUGIN_EXT_WIN32
    {
        tsk_size_t plugins_count = 0;
        char* full_path = tsk_null; // Loading plugins from ActiveX fails when using relative path.
        /* WASAPI (Audio consumer, Audio producer) */
#if 0 // disable WASAPI by default (AEC issue because of code#consumer rate mismatch)
        if(tdav_win32_is_winvista_or_later()) {
            tsk_sprintf(&full_path, "%s/pluginWASAPI.dll", tdav_get_current_directory_const());
            if(tsk_plugin_file_exist(full_path) && (__dll_plugin_wasapi = tsk_plugin_create(full_path))) {
                plugins_count += tmedia_plugin_register(__dll_plugin_wasapi, tsk_plugin_def_type_all, tsk_plugin_def_media_type_all);
            }
        }
#endif
        /* CUDA (H.264 codec) */
#if 1 // Enable CUDA by default
        tsk_sprintf(&full_path, "%s/pluginCUDA.dll", tdav_get_current_directory_const()); // CUDA works on all Windows versions
        if(tsk_plugin_file_exist(full_path) && (__dll_plugin_cuda = tsk_plugin_create(full_path))) {
            plugins_count += tmedia_plugin_register(__dll_plugin_cuda, tsk_plugin_def_type_all, tsk_plugin_def_media_type_all);
        }
#endif
        /* Microsoft Desktop Duplication API (Screen capture) */
        if (tdav_win32_is_win8_or_later()) {
            tsk_sprintf(&full_path, "%s/pluginWinDD.dll", tdav_get_current_directory_const());
            if (tsk_plugin_file_exist(full_path) && (__dll_plugin_dd = tsk_plugin_create(full_path))) {
                plugins_count += tmedia_plugin_register(__dll_plugin_dd, tsk_plugin_def_type_all, tsk_plugin_def_media_type_all);
            }
        }

        /* Media Foundation (Video converter, Video consumer, Video producer, Microsoft H.264 codec, Intel Quick Sync H.264 codec) */
        if(tdav_win32_is_win7_or_later()) {
            tsk_sprintf(&full_path, "%s/pluginWinMF.dll", tdav_get_current_directory_const());
            if(tsk_plugin_file_exist(full_path) && (__dll_plugin_mf = tsk_plugin_create(full_path))) {
                plugins_count += tmedia_plugin_register(__dll_plugin_mf, tsk_plugin_def_type_all, tsk_plugin_def_media_type_all);
            }
        }
        /* DirectShow (Video consumer, Video producer) */
        if (tdav_win32_is_winxp_or_later()) {
            tsk_sprintf(&full_path, "%s/pluginDirectShow.dll", tdav_get_current_directory_const());
            if (tsk_plugin_file_exist(full_path) && (__dll_plugin_dshow = tsk_plugin_create(full_path))) {
                plugins_count += tmedia_plugin_register(__dll_plugin_dshow, tsk_plugin_def_type_all, tsk_plugin_def_media_type_all);
            }
        }
        /* Audio DSP (Resampler, AEC, NS, AGC...) */
        if (tdav_win32_is_winvista_or_later()) {
            tsk_sprintf(&full_path, "%s/pluginWinAudioDSP.dll", tdav_get_current_directory_const());
            if(tsk_plugin_file_exist(full_path) && (__dll_plugin_audio_dsp = tsk_plugin_create(full_path))) {
                plugins_count += tmedia_plugin_register(__dll_plugin_audio_dsp, tsk_plugin_def_type_all, tsk_plugin_def_media_type_all);
            }
        }
        /* IPSec implementation using Windows Filtering Platform (WFP) */
#if !defined(HAVE_TINYIPSEC) || HAVE_TINYIPSEC
        if (tdav_win32_is_winvista_or_later()) {
            tsk_sprintf(&full_path, "%s/pluginWinIPSecVista.dll", tdav_get_current_directory_const());
            if (tsk_plugin_file_exist(full_path) && (tipsec_plugin_register_file(full_path, &__dll_plugin_ipsec_wfp) == 0)) {
                plugins_count += 1; // at least one
                __b_ipsec_supported = tsk_true;
            }
        }
#endif

        TSK_FREE(full_path);
        TSK_DEBUG_INFO("Windows stand-alone plugins loaded = %u", plugins_count);
    }
#endif

    /* === Register media contents === */
    tmedia_content_plugin_register("text/html", tmedia_content_dummy_plugin_def_t);
    tmedia_content_plugin_register("text/plain", tmedia_content_dummy_plugin_def_t);
    tmedia_content_plugin_register("application/octet-stream", tmedia_content_dummy_plugin_def_t);
    tmedia_content_plugin_register("message/CPIM", tmedia_content_cpim_plugin_def_t);
    /* To be implemented
    tmedia_content_plugin_register("message/sipfrag", tmedia_content_sipfrag_plugin_def_t);
    tmedia_content_plugin_register("multipart/digest", tmedia_content_multipart_plugin_def_t);
    tmedia_content_plugin_register("multipart/mixed", tmedia_content_multipart_plugin_def_t);
    tmedia_content_plugin_register("multipart/related", tmedia_content_multipart_plugin_def_t);
    tmedia_content_plugin_register("multipart/alternative", tmedia_content_multipart_plugin_def_t);
    tmedia_content_plugin_register("multipart/encrypted", tmedia_content_multipart_plugin_def_t);
    tmedia_content_plugin_register("multipart/parallel", tmedia_content_multipart_plugin_def_t);
    tmedia_content_plugin_register("multipart/signed", tmedia_content_multipart_plugin_def_t);
    */

    /* === Register sessions === */
    tmedia_session_plugin_register(tmedia_session_ghost_plugin_def_t);
    tmedia_session_plugin_register(tdav_session_audio_plugin_def_t);
    tmedia_session_plugin_register(tdav_session_video_plugin_def_t);
#if !defined(HAVE_TINYMSRP) || HAVE_TINYMSRP
    tmedia_session_plugin_register(tdav_session_msrp_plugin_def_t);
#endif
    tmedia_session_plugin_register(tdav_session_t140_plugin_def_t);
#if !defined(HAVE_TINYBFCP) || HAVE_TINYBFCP
    tmedia_session_plugin_register(tdav_session_bfcp_plugin_def_t);
#endif
    tmedia_session_plugin_register(tdav_session_bfcpaudio_plugin_def_t);
    tmedia_session_plugin_register(tdav_session_bfcpvideo_plugin_def_t);

    /* === Register codecs === */
#if HAVE_FFMPEG
    avcodec_register_all();
#endif
#if !defined(HAVE_TINYMSRP) || HAVE_TINYMSRP
    tmedia_codec_plugin_register(tdav_codec_msrp_plugin_def_t);
#endif
    tmedia_codec_plugin_register(tdav_codec_t140_plugin_def_t);
#if !defined(HAVE_TINYBFCP) || HAVE_TINYBFCP
    tmedia_codec_plugin_register(tdav_codec_bfcp_plugin_def_t);
#endif
    tmedia_codec_plugin_register(tdav_codec_red_plugin_def_t);
    tmedia_codec_plugin_register(tdav_codec_g711a_plugin_def_t);
    tmedia_codec_plugin_register(tdav_codec_g711u_plugin_def_t);
    tmedia_codec_plugin_register(tdav_codec_g722_plugin_def_t);
#if HAVE_OPENCORE_AMR
    tmedia_codec_plugin_register(tdav_codec_amrnb_oa_plugin_def_t);
    tmedia_codec_plugin_register(tdav_codec_amrnb_be_plugin_def_t);
#endif
#if HAVE_BV16
    tmedia_codec_plugin_register(tdav_codec_bv16_plugin_def_t);
#endif
#if HAVE_LIBGSM
    tmedia_codec_plugin_register(tdav_codec_gsm_plugin_def_t);
#endif
#if HAVE_ILBC
    tmedia_codec_plugin_register(tdav_codec_ilbc_plugin_def_t);
#endif
#if HAVE_LIB_SPEEX
    tmedia_codec_plugin_register(tdav_codec_speex_nb_plugin_def_t);
    tmedia_codec_plugin_register(tdav_codec_speex_wb_plugin_def_t);
    tmedia_codec_plugin_register(tdav_codec_speex_uwb_plugin_def_t);
#endif
#if HAVE_LIBOPUS
    tmedia_codec_plugin_register(tdav_codec_opus_plugin_def_t);
#endif
#if HAVE_G729
    tmedia_codec_plugin_register(tdav_codec_g729ab_plugin_def_t);
#endif
    // last: dtmf, ULPFEC and RED
    tmedia_codec_plugin_register(tdav_codec_dtmf_plugin_def_t);
    // tmedia_codec_plugin_register(tdav_codec_ulpfec_plugin_def_t);
    // tmedia_codec_plugin_register(tdav_codec_red_plugin_def_t);

#if HAVE_LIBVPX
    tmedia_codec_plugin_register(tdav_codec_vp8_plugin_def_t);
#endif
#if HAVE_CUDA
#error "Support for H.264 Cuda is deprecated"
    if(tdav_codec_h264_cuda_is_supported()) {
        tmedia_codec_plugin_register(tdav_codec_h264_cuda_bp10_plugin_def_t);
        tmedia_codec_plugin_register(tdav_codec_h264_cuda_bp20_plugin_def_t);
        tmedia_codec_plugin_register(tdav_codec_h264_cuda_bp30_plugin_def_t);
    }
#endif
#if HAVE_OPENH264
    tmedia_codec_plugin_register(tdav_codec_h264_cisco_base_plugin_def_t);
#endif
#if HAVE_FFMPEG
    if(tdav_codec_ffmpeg_mp4ves_is_supported()) {
        tmedia_codec_plugin_register(tdav_codec_mp4ves_plugin_def_t);
    }
    if(tdav_codec_ffmpeg_h264_is_supported()) {
        if(!tmedia_codec_plugin_is_registered_2(tmedia_codec_id_h264_bp)) { // could be already registered by stand alone plugins (e.g. pluginWinMF.DLL)
            tmedia_codec_plugin_register(tdav_codec_h264_base_plugin_def_t);
        }
        if(!tmedia_codec_plugin_is_registered_2(tmedia_codec_id_h264_mp)) { // could be already registered by stand alone plugins (e.g. pluginWinMF.DLL)
            tmedia_codec_plugin_register(tdav_codec_h264_main_plugin_def_t);
        }
    }
    tmedia_codec_plugin_register(tdav_codec_h263p_plugin_def_t);
    tmedia_codec_plugin_register(tdav_codec_h263pp_plugin_def_t);
    if(tdav_codec_ffmpeg_theora_is_supported()) {
        tmedia_codec_plugin_register(tdav_codec_theora_plugin_def_t);
    }
    tmedia_codec_plugin_register(tdav_codec_h263_plugin_def_t);
    tmedia_codec_plugin_register(tdav_codec_h261_plugin_def_t);
#elif HAVE_H264_PASSTHROUGH
    tmedia_codec_plugin_register(tdav_codec_h264_base_plugin_def_t);
    tmedia_codec_plugin_register(tdav_codec_h264_main_plugin_def_t);
#endif
#if HAVE_INTEL_MEDIA_SDK
    tmedia_codec_plugin_register(tdav_codec_h264_intel_base_plugin_def_t);
    tmedia_codec_plugin_register(tdav_codec_h264_intel_main_plugin_def_t);
#endif


    /* === Register converters === */
    // register several convertors and try them all (e.g. LIBYUV only support to/from I420)
#if HAVE_LIBYUV
    tmedia_converter_video_plugin_register(tdav_converter_video_libyuv_plugin_def_t);
#endif
#if HAVE_FFMPEG || HAVE_SWSSCALE
    tmedia_converter_video_plugin_register(tdav_converter_video_ffmpeg_plugin_def_t);
#endif

    /* === Register consumers === */
    tmedia_consumer_plugin_register(tdav_consumer_t140_plugin_def_t); /* T140 */
#if HAVE_DSOUND_H
    tmedia_consumer_plugin_register(tdav_consumer_dsound_plugin_def_t);
#elif HAVE_WAVE_API
    tmedia_consumer_plugin_register(tdav_consumer_waveapi_plugin_def_t);
#elif HAVE_WASAPI
    tmedia_consumer_plugin_register(tdav_consumer_wasapi_plugin_def_t);
#endif
#if TDAV_UNDER_WINDOWS && !TDAV_UNDER_WINDOWS_RT // Windows GDI
    tmedia_consumer_plugin_register(tdav_consumer_video_gdi_plugin_def_t);
#endif
#if HAVE_WINM // Windows Media (WP8)
    tmedia_consumer_plugin_register(tdav_consumer_winm_plugin_def_t);
#endif
#if HAVE_ALSA_ASOUNDLIB_H // Linux
    tmedia_consumer_plugin_register(tdav_consumer_alsa_plugin_def_t);
#endif
#if HAVE_LINUX_SOUNDCARD_H // Linux
    tmedia_consumer_plugin_register(tdav_consumer_oss_plugin_def_t);
#endif

#if HAVE_COREAUDIO_AUDIO_UNIT // CoreAudio based on AudioUnit
    tmedia_consumer_plugin_register(tdav_consumer_audiounit_plugin_def_t);
#elif HAVE_COREAUDIO_AUDIO_QUEUE // CoreAudio based on AudioQueue
    tmedia_consumer_plugin_register(tdav_consumer_audioqueue_plugin_def_t);
#endif

#if HAVE_OSS_H
    tmedia_consumer_plugin_register(tmedia_consumer_oss_plugin_def_t);
#endif

    /* === Register producers === */
    tmedia_producer_plugin_register(tdav_producer_t140_plugin_def_t); /* T140 */
#if HAVE_DSOUND_H // DirectSound
    tmedia_producer_plugin_register(tdav_producer_dsound_plugin_def_t);
#elif HAVE_WAVE_API // WaveAPI
    tmedia_producer_plugin_register(tdav_producer_waveapi_plugin_def_t);
#elif HAVE_WASAPI // WASAPI
    tmedia_producer_plugin_register(tdav_producer_wasapi_plugin_def_t);
#endif
#if TDAV_UNDER_WINDOWS && !TDAV_UNDER_WINDOWS_RT // Windows DirectDraw (DirectX)
    if (tdav_producer_screencast_ddraw_plugin_is_supported()) {
        tmedia_producer_plugin_register(tdav_producer_screencast_ddraw_plugin_def_t);
    }
#endif
#if TDAV_UNDER_WINDOWS && !TDAV_UNDER_WINDOWS_RT // Windows GDI
    tmedia_producer_plugin_register(tdav_producer_screencast_gdi_plugin_def_t);
#endif
#if HAVE_WINM // Windows Media (WP8)
    tmedia_producer_plugin_register(tdav_producer_winm_plugin_def_t);
#endif
#if HAVE_ALSA_ASOUNDLIB_H // Linux
    tmedia_producer_plugin_register(tdav_producer_alsa_plugin_def_t);
#endif
#if HAVE_LINUX_SOUNDCARD_H // Linux
    tmedia_producer_plugin_register(tdav_producer_oss_plugin_def_t);
#endif
#if HAVE_LINUX_VIDEODEV2_H // V4L2 (Linux)
    tmedia_producer_plugin_register(tdav_producer_video_v4l2_plugin_def_t);
    tmedia_producer_plugin_register(tdav_producer_screencast_v4l2_plugin_def_t);
#endif

#if HAVE_COREAUDIO_AUDIO_UNIT // CoreAudio based on AudioUnit
    tmedia_producer_plugin_register(tdav_producer_audiounit_plugin_def_t);
#elif HAVE_COREAUDIO_AUDIO_QUEUE // CoreAudio based on AudioQueue
    tmedia_producer_plugin_register(tdav_producer_audioqueue_plugin_def_t);
#endif

    /* === Register Audio Denoise (AGC, VAD, Noise Suppression and AEC) === */
#if HAVE_WEBRTC && (!defined(HAVE_WEBRTC_DENOISE) || HAVE_WEBRTC_DENOISE)
    tmedia_denoise_plugin_register(tdav_webrtc_denoise_plugin_def_t);
#endif
#if HAVE_SPEEX_DSP && (!defined(HAVE_SPEEX_DENOISE) || HAVE_SPEEX_DENOISE)
    tmedia_denoise_plugin_register(tdav_speex_denoise_plugin_def_t);
#endif

    /* === Register Audio Resampler === */
#if HAVE_SPEEX_DSP && (!defined(HAVE_SPEEX_RESAMPLER) || HAVE_SPEEX_RESAMPLER)
    tmedia_resampler_plugin_register(tdav_speex_resampler_plugin_def_t);
#endif

    /* === Register Audio/video JitterBuffer === */
#if HAVE_SPEEX_DSP && HAVE_SPEEX_JB
    tmedia_jitterbuffer_plugin_register(tdav_speex_jitterbuffer_plugin_def_t);
#else
    tmedia_jitterbuffer_plugin_register(tdav_speakup_jitterbuffer_plugin_def_t);
#endif

    // collect all codecs before filtering
    _tdav_codec_plugins_collect();

    __b_initialized = tsk_true;

    return ret;
}
示例#29
0
void FFMPEGV_Init()
{
	nodedef Def;
	const codecinfo* i;

	avcodec_init();

	/* video codecs */
	REGISTER_DECODER (FLV, flv);
		
	REGISTER_DECODER (AVS, avs);
	REGISTER_DECODER (CAVS, cavs);
	
	REGISTER_DECODER (CINEPAK, cinepak);
	REGISTER_DECODER (H261, h261);
	REGISTER_DECODER (H263, h263);
	REGISTER_DECODER (H263I, h263i);
	REGISTER_DECODER (H264, h264);

	REGISTER_DECODER (INDEO2, indeo2);
	REGISTER_DECODER (INDEO3, indeo3);

	REGISTER_DECODER (MPEG2VIDEO, mpeg2video);
	REGISTER_DECODER (MPEG4, mpeg4);

	REGISTER_DECODER (MSMPEG4V1, msmpeg4v1);
	REGISTER_DECODER (MSMPEG4V2, msmpeg4v2);
	REGISTER_DECODER (MSMPEG4V3, msmpeg4v3);

	REGISTER_DECODER (MSRLE, msrle);
	REGISTER_DECODER (MSVIDEO1, msvideo1);

	REGISTER_DECODER (RV10, rv10);
	REGISTER_DECODER (RV20, rv20);
	REGISTER_DECODER (RV30, rv30);
	REGISTER_DECODER (RV40, rv40);

	//REGISTER_DECODER	(sp5x);
	REGISTER_DECODER (SVQ1, svq1);
	REGISTER_DECODER (SVQ3, svq3);

	REGISTER_DECODER (THEORA, theora);
	REGISTER_DECODER (VC1, vc1);

	REGISTER_DECODER (VP3, vp3);
	REGISTER_DECODER (VP5, vp5);
	REGISTER_DECODER (VP6, vp6);
	REGISTER_DECODER (VP6A, vp6a);
	REGISTER_DECODER (VP6F, vp6f);
	REGISTER_DECODER (VP8, vp8);

	REGISTER_DECODER  (WMV1, wmv1);
	REGISTER_DECODER  (WMV2, wmv2);
	REGISTER_DECODER (WMV3, wmv3);

	REGISTER_DECODER (TSCC, tscc);
    
/*	register_avcodec(&flv_decoder);
	register_avcodec(&mpeg1video_decoder);
	register_avcodec(&mpeg2video_decoder);
	register_avcodec(&mpegvideo_decoder);
//	register_avcodec(&svq1_decoder);
	register_avcodec(&svq3_decoder);
	register_avcodec(&h263_decoder);
	register_avcodec(&mpeg4_decoder);
	register_avcodec(&msmpeg4v1_decoder);
	register_avcodec(&msmpeg4v2_decoder);
	register_avcodec(&msmpeg4v3_decoder);
	register_avcodec(&wmv1_decoder);
	register_avcodec(&wmv2_decoder);
//	register_avcodec(&wmv3_decoder);
	register_avcodec(&h264_decoder);
	register_avcodec(&cinepak_decoder);
	register_avcodec(&msvideo1_decoder);
	register_avcodec(&tscc_decoder);
*/
	NodeRegisterClass(&FFMPEGVideo);
	memset(&Def,0,sizeof(Def));

	for (i=Info;i->Id;++i)
	{
		StringAdd(1,i->Id,NODE_NAME,i->Name);
		StringAdd(1,i->Id,NODE_CONTENTTYPE,i->ContentType);

		Def.Class = i->Id;
		Def.ParentClass = FFMPEG_VIDEO_CLASS;
		Def.Priority = PRI_DEFAULT-10; // do not override ARM optimized codecs by default
		Def.Flags = 0; // parent size

		if ((i->CodecId == CODEC_ID_WMV1 && QueryPlatform(PLATFORM_WMPVERSION)!=10) || //WMP10 RGB only output -> prefer ffmpeg
			i->CodecId == CODEC_ID_WMV2 ||
			i->CodecId == CODEC_ID_WMV3)
			Def.Priority -= 100; // prefer DMO, WMV2 J-frames are not supported by ffmpeg, WMMX support by MS codecs are faster

		NodeRegisterClass(&Def);
	}

	NodeRegisterClass(&WMVF);
}
/** The Constructor
 */
OMX_ERRORTYPE omx_audioenc_component_Constructor(OMX_COMPONENTTYPE *openmaxStandComp,OMX_STRING cComponentName) {

  OMX_ERRORTYPE err = OMX_ErrorNone;
  omx_audioenc_component_PrivateType* omx_audioenc_component_Private;
  OMX_U32 i;

  if (!openmaxStandComp->pComponentPrivate) {
    DEBUG(DEB_LEV_FUNCTION_NAME,"In %s, allocating component\n",__func__);
    openmaxStandComp->pComponentPrivate = calloc(1, sizeof(omx_audioenc_component_PrivateType));
    if(openmaxStandComp->pComponentPrivate==NULL)
      return OMX_ErrorInsufficientResources;
  }
  else
    DEBUG(DEB_LEV_FUNCTION_NAME,"In %s, Error Component %x Already Allocated\n",__func__, (int)openmaxStandComp->pComponentPrivate);

  omx_audioenc_component_Private = openmaxStandComp->pComponentPrivate;
  omx_audioenc_component_Private->ports = NULL;

  /** Calling base filter constructor */
  err = omx_base_filter_Constructor(openmaxStandComp,cComponentName);

  omx_audioenc_component_Private->sPortTypesParam[OMX_PortDomainAudio].nStartPortNumber = 0;
  omx_audioenc_component_Private->sPortTypesParam[OMX_PortDomainAudio].nPorts = 2;

  /** Allocate Ports and call port constructor. */
  if (omx_audioenc_component_Private->sPortTypesParam[OMX_PortDomainAudio].nPorts && !omx_audioenc_component_Private->ports) {
    omx_audioenc_component_Private->ports = calloc(omx_audioenc_component_Private->sPortTypesParam[OMX_PortDomainAudio].nPorts, sizeof(omx_base_PortType *));
    if (!omx_audioenc_component_Private->ports) {
      return OMX_ErrorInsufficientResources;
    }
    for (i=0; i < omx_audioenc_component_Private->sPortTypesParam[OMX_PortDomainAudio].nPorts; i++) {
      omx_audioenc_component_Private->ports[i] = calloc(1, sizeof(omx_base_audio_PortType));
      if (!omx_audioenc_component_Private->ports[i]) {
        return OMX_ErrorInsufficientResources;
      }
    }
  }

  base_audio_port_Constructor(openmaxStandComp, &omx_audioenc_component_Private->ports[0], 0, OMX_TRUE);
  base_audio_port_Constructor(openmaxStandComp, &omx_audioenc_component_Private->ports[1], 1, OMX_FALSE);

  /** Domain specific section for the ports. */
  // first we set the parameter common to both formats
  //common parameters related to input port
  omx_audioenc_component_Private->ports[OMX_BASE_FILTER_INPUTPORT_INDEX]->sPortParam.nBufferSize =  DEFAULT_OUT_BUFFER_SIZE;
  //common parameters related to output port
  omx_audioenc_component_Private->ports[OMX_BASE_FILTER_OUTPUTPORT_INDEX]->sPortParam.nBufferSize = DEFAULT_IN_BUFFER_SIZE;

  // now it's time to know the audio coding type of the component
  if(!strcmp(cComponentName, AUDIO_ENC_MP3_NAME))   // mp3 format encoder
    omx_audioenc_component_Private->audio_coding_type = OMX_AUDIO_CodingMP3;

  else if(!strcmp(cComponentName, AUDIO_ENC_AAC_NAME))   // AAC format encoder
    omx_audioenc_component_Private->audio_coding_type = OMX_AUDIO_CodingAAC;

  else if(!strcmp(cComponentName, AUDIO_ENC_G726_NAME))  // G726 format encoder
    omx_audioenc_component_Private->audio_coding_type = OMX_AUDIO_CodingG726;

  else if (!strcmp(cComponentName, AUDIO_ENC_BASE_NAME))// general audio encoder
    omx_audioenc_component_Private->audio_coding_type = OMX_AUDIO_CodingUnused;

  else  // IL client specified an invalid component name
    return OMX_ErrorInvalidComponentName;

  omx_audioenc_component_SetInternalParameters(openmaxStandComp);

  //settings of output port
  //output is pcm mode for all encoders - so generalise it
  setHeader(&omx_audioenc_component_Private->pAudioPcmMode,sizeof(OMX_AUDIO_PARAM_PCMMODETYPE));
  omx_audioenc_component_Private->pAudioPcmMode.nPortIndex = 0;
  omx_audioenc_component_Private->pAudioPcmMode.nChannels = 2;
  omx_audioenc_component_Private->pAudioPcmMode.eNumData = OMX_NumericalDataSigned;
  omx_audioenc_component_Private->pAudioPcmMode.eEndian = OMX_EndianLittle;
  omx_audioenc_component_Private->pAudioPcmMode.bInterleaved = OMX_TRUE;
  omx_audioenc_component_Private->pAudioPcmMode.nBitPerSample = 16;
  omx_audioenc_component_Private->pAudioPcmMode.nSamplingRate = 44100;
  omx_audioenc_component_Private->pAudioPcmMode.ePCMMode = OMX_AUDIO_PCMModeLinear;
  omx_audioenc_component_Private->pAudioPcmMode.eChannelMapping[0] = OMX_AUDIO_ChannelLF;
  omx_audioenc_component_Private->pAudioPcmMode.eChannelMapping[1] = OMX_AUDIO_ChannelRF;

  //general configuration irrespective of any audio formats
  //setting other parameters of omx_audioenc_component_private
  omx_audioenc_component_Private->avCodec = NULL;
  omx_audioenc_component_Private->avCodecContext= NULL;
  omx_audioenc_component_Private->avcodecReady = OMX_FALSE;

  omx_audioenc_component_Private->BufferMgmtCallback = omx_audioenc_component_BufferMgmtCallback;

  /** first initializing the codec context etc that was done earlier by ffmpeglibinit function */
  avcodec_init();
  av_register_all();
  omx_audioenc_component_Private->avCodecContext = avcodec_alloc_context();

  omx_audioenc_component_Private->messageHandler = omx_audioenc_component_MessageHandler;
  omx_audioenc_component_Private->destructor = omx_audioenc_component_Destructor;
  openmaxStandComp->SetParameter = omx_audioenc_component_SetParameter;
  openmaxStandComp->GetParameter = omx_audioenc_component_GetParameter;
  openmaxStandComp->ComponentRoleEnum = omx_audioenc_component_ComponentRoleEnum;

  noaudioencInstance++;

  if(noaudioencInstance>MAX_COMPONENT_AUDIOENC)
    return OMX_ErrorInsufficientResources;

  return err;
}