bool MidiPlayerThread::start( const QString &path, int volume, double seek /* = -1 */ )
{
    qDebug() << "MidiPlayerThread::start";
    unsigned short int mixer_options = 0;
    m_path = path;

    if ( open_alsa_output() == ( -1 ) ) {
        qDebug() << "MidiPlayerThread::start:   error of open_alsa_output()...";
        return false;
    }

    if ( WildMidi_Init( qPrintable( m_configFile ), m_sample_rate, mixer_options ) < 0 )  {
        qWarning( "MidiPlayerThread::start:   unable to initialize WildMidi library" );
        close_output();
        return false;
    }

    m_midiPtr = WildMidi_Open ( qPrintable( m_path ) );
    if ( !m_midiPtr ) {
        qWarning("MidiPlayerThread::start:   unable to open file");
        WildMidi_Shutdown();
        close_output();
        return false;
    }

    Tracks audios;
    audios.addID( 0 );

    _WM_Info *wm_info = WildMidi_GetInfo( m_midiPtr );
    m_totalTime = ( qint64 )wm_info->approx_total_samples / m_sample_rate;
    qDebug() << "total time is " << m_totalTime << " sec";

    m_md->reset();
    m_md->duration = m_totalTime;
    m_md->audio_rate = m_sample_rate;
    m_md->novideo = true;
    m_md->audios = audios;
//    m_md->type = TYPE_FILE;

    setVolume( volume );

    if ( seek != ( -1 ) ) {
        goToSec( seek );
    }

    QThread::start();

    qDebug( "MidiPlayerThread: thread started" );

    emit audioInfoChanged( audios );

    return true;
}
示例#2
0
文件: choplog.c 项目: 40a/experiments
void split(char *file) {
  FILE *ifp = NULL, *ofp = NULL;
  int bytes = 0;
  char buf[READSIZE];

  memset(buf, 0, READSIZE);
  ifp = fopen(file, "r");

  if (ifp == NULL) {
    fprintf(stderr, "Problem opening '%s'\n", file);
    fprintf(stderr, "Error: %s\n", strerror(errno));
    exit(1);
  }

  while ((bytes = fread(buf, 1, READSIZE, ifp)) == READSIZE)
    output(buf, bytes, &ofp);
  
  if (!feof(ifp)) {
    fprintf(stderr, "Error while reading from '%s'\n", file);
    fprintf(stderr, "Error: %s\n", strerror(errno));
    exit(1);
  }

  if (bytes > 0)
    output(buf, bytes, &ofp);
    
  if (ofp)
    close_output(ofp, current_output_file);

}
示例#3
0
int
monitor(int pid, struct timeval *jointime)
{
    int ret, status = -1;
    uint64_t tsc, ovhd, start, duration, t;
    struct rusage usage;
    int sense = 1;

    pthread_barrier_wait(&barrier);
    start = _rdtsc();
    for (;;)
    {
        // We're not measuring the bootstrap core. Discourage users from
        // using the last core.
        //readcounters(0);

        t = _rdtsc();
        printcounters(counters, t - start);
        if (!gbl.server)
        {
            if (waitpid(pid, &status, WNOHANG))
            {
                gettimeofday(jointime, 0);
                done = 1;
                break;
            }
        }
        start = _rdtsc();
        timeout();
    }
    close_output();
    return status;
}
示例#4
0
文件: indent.c 项目: catterer/indent
static exit_values_ty indent_multiple_files(void)
{
    exit_values_ty exit_status = total_success;
    
    int i;
    /* When multiple input files are specified, make a backup copy
     * and then output the indented code into the same filename. */

    for (i = 0; input_files; i++, input_files--)
    {
        exit_values_ty status;
        struct stat file_stats;

        in_name = in_file_names[i];
        out_name = in_file_names[i];
        current_input = read_file(in_file_names[i], &file_stats);

        open_output(out_name, "r+");

        make_backup(current_input, &file_stats); /* Aborts on failure. */

        /* We have safely made a backup so the open file can be truncated. */
          
        reopen_output_trunc(out_name);
          
        reset_parser();
        status = indent (current_input);

        if (status > exit_status)
        {
            exit_status = status;
        }

        if (settings.preserve_mtime)
        {
            close_output(&file_stats, out_name);
        }
        else
        {
            close_output(NULL, out_name);
        }
    }
    
    return exit_status;
}
示例#5
0
void h2_stream_rst(h2_stream *stream, int error_code)
{
    stream->rst_error = error_code;
    close_input(stream);
    close_output(stream);
    ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, stream->session->c,
                  "h2_stream(%ld-%d): reset, error=%d", 
                  stream->session->id, stream->id, error_code);
}
示例#6
0
文件: driver.c 项目: MatzeB/cparser
bool do_copy_file(compilation_env_t *env, compilation_unit_t *unit)
{
	if (!open_input(unit))
		return false;
	if (!open_output(env))
		return false;
	copy_file(env->out, unit->input);
	close_output(env);
	return close_input(unit);
}
示例#7
0
void RenderEngine::run()
{
	start_render_threads();
	start_lock->unlock();
	interrupt_lock->unlock();

	wait_render_threads();

	interrupt_lock->lock("RenderEngine::run");


	if(interrupted)
	{
		playback_engine->tracking_position = playback_engine->get_tracking_position();
	}

	close_output();

// Fix the tracking position
	if(playback_engine)
	{
		if(command->command == CURRENT_FRAME)
		{
//printf("RenderEngine::run 4.1 %d\n", playback_engine->tracking_position);
			playback_engine->tracking_position = command->playbackstart;
		}
		else
		{
// Make sure transport doesn't issue a pause command next
//printf("RenderEngine::run 4.1 %d\n", playback_engine->tracking_position);
			if(!interrupted)
			{
				if(do_audio)
					playback_engine->tracking_position = 
						(double)arender->current_position / 
							command->get_edl()->session->sample_rate;
				else
				if(do_video)
				{
					playback_engine->tracking_position = 
						(double)vrender->current_position / 
							command->get_edl()->session->frame_rate;
				}
			}

			if(!interrupted) playback_engine->command->command = STOP;
			playback_engine->stop_tracking();

		}
		playback_engine->is_playing_back = 0;
	}

	input_lock->unlock();
	interrupt_lock->unlock();
}
示例#8
0
static int sun_discard_playing(void)
{
    void (* orig_alarm_handler)();

    orig_alarm_handler = signal(SIGALRM, null_proc);
    ualarm(10000, 10000);
    close_output();
    ualarm(0, 0);
    signal(SIGALRM, orig_alarm_handler);
    return open_output();
}
示例#9
0
int
main(int argc, char *argv[])
{
    int c;
    bool monochrome = FALSE;
    InitPanel myInit = init_panel;
    FillPanel myFill = fill_panel;

    setlocale(LC_ALL, "");

    while ((c = getopt(argc, argv, "i:o:mwx")) != -1) {
	switch (c) {
	case 'i':
	    log_in = fopen(optarg, "r");
	    break;
	case 'o':
	    log_out = fopen(optarg, "w");
	    break;
	case 'm':
	    monochrome = TRUE;
	    break;
#if USE_WIDEC_SUPPORT
	case 'w':
	    myInit = init_wide_panel;
	    myFill = fill_wide_panel;
	    break;
#endif
	case 'x':
	    unboxed = TRUE;
	    break;
	default:
	    usage();
	}
    }
    if (unboxed)
	myFill = fill_unboxed;

    initscr();
    cbreak();
    noecho();
    keypad(stdscr, TRUE);

    use_colors = monochrome ? FALSE : has_colors();
    if (use_colors)
	start_color();

    demo_panels(myInit, myFill);
    endwin();

    close_input();
    close_output();

    ExitProgram(EXIT_SUCCESS);
}
示例#10
0
int AudioALSA::close_all()
{
	close_input();
	close_output();
	if(device->d)
	{
		snd_pcm_close(dsp_duplex);
	}
	samples_written = 0;
	delay = 0;
	interrupted = 0;
	return 1;
}
示例#11
0
/**
 * cockpit_stream_close:
 * @self: a pipe
 * @problem: a problem or NULL
 *
 * Close the pipe. If @problem is non NULL, then it's treated
 * as if an error occurred, and the pipe is closed immediately.
 * Otherwise the pipe output is closed when all data has been sent.
 *
 * The 'close' signal will be fired when the pipe actually closes.
 * This may be during this function call (esp. in the case of a
 * non-NULL @problem) or later.
 */
void
cockpit_stream_close (CockpitStream *self,
                    const gchar *problem)
{
  g_return_if_fail (COCKPIT_IS_STREAM (self));

  self->priv->closing = TRUE;

  if (problem)
    close_immediately (self, problem);
  else if (g_queue_is_empty (self->priv->out_queue))
    close_output (self);
}
示例#12
0
文件: glpmpl4.c 项目: ecotox/pacfm
int mpl_postsolve(MPL *mpl, char *file)
{     if (!(mpl->phase == 3 && !mpl->flag_p))
         fault("mpl_postsolve: invalid call sequence");
      /* set up error handler */
      if (setjmp(mpl->jump)) goto done;
      /* perform postsolving */
      open_output(mpl, file, "a");
      postsolve_model(mpl);
      close_output(mpl);
      /* postsolving phase has been finished */
      print("Model has been successfully processed");
done: /* return to the calling program */
      return mpl->phase;
}
示例#13
0
RenderEngine::~RenderEngine()
{
	close_output();
	delete command;
	delete preferences;
	if(arender) delete arender;
	if(vrender) delete vrender;
	delete edl;
	delete input_lock;
	delete start_lock;
	delete output_lock;
	delete interrupt_lock;
	delete first_frame_lock;
	delete config;
}
示例#14
0
static int acntl(int request, void *arg)
{
  switch(request) {
  case PM_REQ_PLAY_START:
    if(dpm.flag & PF_AUTO_SPLIT_FILE)
      return auto_raw_output_open(current_file_info->filename);
    return 0;
  case PM_REQ_PLAY_END:
    if(dpm.flag & PF_AUTO_SPLIT_FILE)
      close_output();
    return 0;
  case PM_REQ_DISCARD:
    return 0;
  }
  return -1;
}
示例#15
0
int AudioALSA::write_buffer(char *buffer, int size)
{
// Don't give up and drop the buffer on the first error.
	int attempts = 0;
	int done = 0;
	int samples = size / (device->out_bits / 8) / device->get_ochannels();

	if(!get_output()) return 0;

	while(attempts < 2 && !done && !interrupted)
	{
// Buffers written must be equal to period_time
// Update timing
 		snd_pcm_sframes_t delay;
 		snd_pcm_delay(get_output(), &delay);
		snd_pcm_avail_update(get_output());

		device->Thread::enable_cancel();
		if(snd_pcm_writei(get_output(), 
			buffer, 
			samples) < 0)
		{
			device->Thread::disable_cancel();
			printf("AudioALSA::write_buffer underrun at sample %" PRId64 "\n",
				device->current_position());
//			snd_pcm_resume(get_output());
			close_output();
			open_output();
			attempts++;
		}
		else
		{
			device->Thread::disable_cancel();
			done = 1;
		}
	}

	if(done)
	{
		timer_lock->lock("AudioALSA::write_buffer");
		this->delay = delay;
		timer->update();
		samples_written += samples;
		timer_lock->unlock();
	}
	return 0;
}
示例#16
0
文件: glpmpl4.c 项目: ecotox/pacfm
int mpl_generate(MPL *mpl, char *file)
{     if (!(mpl->phase == 1 || mpl->phase == 2))
         fault("mpl_generate: invalid call sequence");
      /* set up error handler */
      if (setjmp(mpl->jump)) goto done;
      /* generate model */
      mpl->phase = 3;
      open_output(mpl, file, "w");
      generate_model(mpl);
      close_output(mpl);
      /* build problem instance */
      build_problem(mpl);
      /* generation phase has been finished */
      print("Model has been successfully generated");
done: /* return to the calling program */
      return mpl->phase;
}
示例#17
0
int
main(int argc, char **argv)
{
  int c;
  int status;
  int global_status = 0;
  while (1)
    {
      c = getopt(argc, argv, "nqyH");
      if (c == -1)
	break;
      switch (c)
	{
	case 'n':
	  global_suppress_output = 1;
	  break;
	case 'q':
	  global_quiet = 1;
	  break;
	case 'y':
	  global_fail_verify_ok = 1;
	  break;
	case 'H':
	  global_halt_on_error = 1;
	  break;
	default:
	  break;
	}
    }

  stp_init();
  output = stdout;
  while (1)
    {
      status = do_print();
      if (status == 1)
	break;
      else if (status != 0)
	global_status = 1;
    }
  close_output();
  if (passes + failures + skipped > 1)
    fprintf(stderr, "%d pass, %d fail, %d skipped\n", passes, failures, skipped);
  return global_status;
}
示例#18
0
static int open_output(void)
{
	int	i;

	// open the note allocator component
	gNoteAllocator = OpenDefaultComponent(kNoteAllocatorComponentType, 0);
	if(gNoteAllocator == NULL){
		ctl->cmsg(CMSG_INFO,VERB_VERBOSE,"open_output fail:");
		close_output();
		return -1;
	}else{
		ctl->cmsg(CMSG_INFO,VERB_VERBOSE,"open_output success:");
	}
	dmp.fd = 1; //normaly opened flag
	for(i = 0; i < MAX_CHANNELS; i++)
		bend_sense[i] = 0x100;
	return 0;
}
示例#19
0
static int acntl(int request, void *arg)
{
  switch(request) {
  case PM_REQ_PLAY_START:
    if(dpm.flag & PF_AUTO_SPLIT_FILE){
      if(  ( NULL == current_file_info ) || (NULL == current_file_info->filename ) )
        return auto_speex_output_open("Output.mid",NULL);
      return auto_speex_output_open(current_file_info->filename, current_file_info->seq_name);
   }
    return 0;
  case PM_REQ_PLAY_END:
    if(dpm.flag & PF_AUTO_SPLIT_FILE)
      close_output();
    return 0;
  case PM_REQ_DISCARD:
    return 0;
  }
  return -1;
}
示例#20
0
文件: choplog.c 项目: 40a/experiments
void newfile(FILE **ofpp) {
  char *newfilename;
  if (*ofpp)
    close_output(*ofpp, current_output_file);

  asprintf(&newfilename, "%s%05d", prefix, split_count);
  *ofpp = fopen(newfilename, "w");

  //fprintf(stderr, "New file: %s\n", newfilename);

  if (*ofpp == NULL) {
    fprintf(stderr, "Problem opening '%s'\n", newfilename);
    fprintf(stderr, "Error: %s\n", strerror(errno));
    exit(1);
  }

  split_count++;
  bytes_written = 0;

  if (current_output_file != NULL)
    free(current_output_file);
  current_output_file = newfilename;
}
示例#21
0
文件: spy.c 项目: metacore/spin
void
spy_dump_internal (spy_t s, tabstop *t)
{
    long average = 0;
    long median = 0;
    long std_var;
    long n_samples;

    if (s->n == 0) return;
    n_samples = s->n > s->n_samples ? s->n_samples : s->n;    
    open_output();

    average = spy_average(s);
    median = spy_median(s);
    std_var = spy_std_variation(s);

    if (!(mode & SPY_DISPLAY_CYCLES)) {
	print_fill(s->name, t->name);
	print_fill(r_dtoa(cycle_to_usec(s->min)), t->min);
	print_fill(r_dtoa(cycle_to_usec(s->max)), t->max);
	print_fill(r_dtoa(cycle_to_usec(average)), t->mean);
	print_fill(r_dtoa(cycle_to_usec(median)), t->median);
	print_fill(r_dtoa(cycle_to_usec(s->cumulative)), t->total);
	print_fill(itoa(s->n), t->hits);
	putc('\n', out);
    } else {
	fprintf(out, "%-9s: %5ld(%5.2f), %5ld(%5.2f), %5ld(%5.2f), %5ld(%5.2f), %5ld(%5.2f), %5ld.\n", 
	       s->name, 
	       s->min, cycle_to_usec(s->min),
	       s->max, cycle_to_usec(s->max),
	       average, cycle_to_usec(average),
	       median,  cycle_to_usec(median),
	       s->cumulative, cycle_to_usec(s->cumulative),
	       s->n);
    }
    close_output();
}
示例#22
0
int AudioALSA::open_output()
{
	char pcm_name[BCTEXTLEN];
	snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
	int open_mode = 0;
	int err;

	device->out_channels = device->get_ochannels();
	device->out_bits = device->out_config->alsa_out_bits;

	translate_name(pcm_name, device->out_config->alsa_out_device);

	err = snd_pcm_open(&dsp_out, device->out_config->alsa_out_device, stream, open_mode);

	if(err < 0)
	{
		dsp_out = 0;
		printf("AudioALSA::open_output %s: %s\n", pcm_name, snd_strerror(err));
		return 1;
	}

	err = set_params(dsp_out, 
		device->get_ochannels(), 
		device->out_config->alsa_out_bits,
		device->out_samplerate,
		device->out_samples);
	if(err)
	{
		fprintf(stderr, "AudioALSA::open_output: set_params failed.  Aborting playback.\n");
		close_output();
		return 1;
	}

	timer->update();
	return 0;
}
示例#23
0
static gboolean
dispatch_output (gint fd,
                 GIOCondition cond,
                 gpointer user_data)
{
  CockpitPipe *self = (CockpitPipe *)user_data;
  struct iovec iov[4];
  gsize partial;
  gssize ret;
  gint i, count;
  GList *l;

  /* A non-blocking connect is processed here */
  if (self->priv->connecting && !dispatch_connect (self))
    return TRUE;

  g_return_val_if_fail (self->priv->out_source, FALSE);

  /* Note we fall through when nothing to write */
  partial = self->priv->out_partial;
  for (l = self->priv->out_queue->head, i = 0;
      i < G_N_ELEMENTS (iov) && l != NULL;
      i++, l = g_list_next (l))
    {
      iov[i].iov_base = (gpointer)g_bytes_get_data (l->data, &iov[i].iov_len);

      if (partial)
        {
          g_assert (partial < iov[i].iov_len);
          iov[i].iov_len -= partial;
          iov[i].iov_base = ((gchar *)iov[i].iov_base) + partial;
          partial = 0;
        }
    }
  count = i;

  if (count == 0)
    ret = 0;
  else
    ret = writev (self->priv->out_fd, iov, count);
  if (ret < 0)
    {
      if (errno != EAGAIN && errno != EINTR)
        {
          if (errno == EPIPE)
            {
              g_debug ("%s: couldn't write: %s", self->priv->name, g_strerror (errno));
              close_immediately (self, "terminated");
            }
          else
            {
              set_problem_from_errno (self, "couldn't write", errno);
              close_immediately (self, NULL); /* already set */
            }
        }
      return FALSE;
    }

  /* Figure out what was written */
  for (i = 0; ret > 0 && i < count; i++)
    {
      if (ret >= iov[i].iov_len)
        {
          g_debug ("%s: wrote %d bytes", self->priv->name, (int)iov[i].iov_len);
          g_bytes_unref (g_queue_pop_head (self->priv->out_queue));
          self->priv->out_partial = 0;
          ret -= iov[i].iov_len;
        }
      else
        {
          g_debug ("%s: partial write %d of %d bytes", self->priv->name,
                   (int)ret, (int)iov[i].iov_len);
          self->priv->out_partial += ret;
          ret = 0;
        }
    }

  if (self->priv->out_queue->head)
    return TRUE;

  g_debug ("%s: output queue empty", self->priv->name);

  /* If all messages are done, then stop polling out fd */
  stop_output (self);

  if (self->priv->closing)
    close_output (self);
  else
    close_maybe (self);

  return TRUE;
}
示例#24
0
void *recorder_thread(void *ptr) {
  struct camera *cam = (struct camera *)ptr;
  struct motion_detection md;
  AVPacket packet;
  AVFrame *frame;
  int got_frame, ret;
  unsigned int cnt = 0;
  time_t first_activity = 0;
  time_t last_activity = 0;

  if(open_camera(cam) < 0)
    return NULL;
  if(open_output(cam) < 0)
    return NULL;

  av_dump_format(cam->context, 0, cam->context->filename, 0);
  av_dump_format(cam->output_context, 0, cam->output_context->filename, 1);

  md.cam = cam;

  md.prev = cvCreateImage(cvSize(cam->codec->width, cam->codec->height), IPL_DEPTH_8U, 1);
  md.cur  = cvCreateImage(cvSize(cam->codec->width, cam->codec->height), IPL_DEPTH_8U, 1);
  md.silh = cvCreateImage(cvSize(cam->codec->width, cam->codec->height), IPL_DEPTH_8U, 1);
  cvZero(md.prev);
  cvZero(md.cur);
  cvZero(md.silh);

  md.img_convert_ctx = sws_getContext(
    cam->codec->width, cam->codec->height, cam->codec->pix_fmt,
    cam->codec->width, cam->codec->height, PIX_FMT_GRAY8,
    SWS_BICUBIC, NULL, NULL, NULL);
  md.buffer = (uint8_t*)av_malloc(3 * cam->codec->width * cam->codec->height);

  int got_key_frame = 0, first_detection = 1;
  frame = avcodec_alloc_frame();
  if(!frame) {
    av_err_msg("avcodec_alloc_frame", 0);
    return NULL;
  }

  while(1) {
    cam->last_io = time(NULL);

    if((ret = av_read_frame(cam->context, &packet)) < 0) {
      if(ret == AVERROR_EOF) break;
      else av_err_msg("av_read_frame", ret);
    }

    if(packet.stream_index == cam->video_stream_index) {
      // start on keyframe
      if(!got_key_frame && !(packet.flags & AV_PKT_FLAG_KEY)) {
        continue;
      }
      got_key_frame = 1;

      avcodec_get_frame_defaults(frame);
      got_frame = 0;

      cnt = (cnt + 1) % cam->analize_frames;
      if(cnt == 0) {
        if((ret = avcodec_decode_video2(cam->codec, frame, &got_frame, &packet)) < 0)
          av_err_msg("avcodec_decode_video2", ret);

        if(got_frame) {
          if(detect_motion(&md, frame)) {
            if(first_activity == 0) first_activity = time(NULL);
            last_activity = time(NULL);
          } else {
            if(first_activity > 0 && time(NULL) - last_activity > cam->motion_delay) {
              if(!first_detection)
                db_create_event(cam->id, first_activity, last_activity);
              else
                first_detection = 0;
              first_activity = 0;
            }
          }
        }

        if(time(NULL) - cam->last_screenshot > 60 && (packet.flags & AV_PKT_FLAG_KEY)) {
          char fname[128];
          snprintf(fname, sizeof(fname), "%s/%s/screenshot.png", store_dir, cam->name);
          cvSaveImage(fname, md.cur, 0);
          cam->last_screenshot = time(NULL);
        }
      }

      packet.stream_index = cam->output_stream->id;
      if((ret = av_write_frame(cam->output_context, &packet)) < 0)
        av_err_msg("av_write_frame", ret);

      pthread_mutex_lock(&cam->consumers_lock);
      for(l1 *p = cam->cam_consumers_list; p != NULL; p = p->next) {
        struct cam_consumer *consumer = (struct cam_consumer *)p->value;
        if(!consumer->screen->active)
          continue;

        if(consumer->screen->tmpl_size == 1) {
          packet.stream_index = 0;
          if((ret = av_write_frame(consumer->screen->rtp_context, &packet)) < 0)
            av_err_msg("av_write_frame", ret);
        } else {
          if(!got_frame) {
            if((ret = avcodec_decode_video2(cam->codec, frame, &got_frame, &packet)) < 0) {
              av_err_msg("avcodec_decode_video2", ret);
              break;
            }
          }
          if(got_frame)
            copy_frame_to_consumer(frame, cam->codec->height, consumer);
        }
      }
      pthread_mutex_unlock(&cam->consumers_lock);
    }

    av_free_packet(&packet);
    
    if(!cam->active) {
      break;
    }

    if(time(NULL) - cam->file_started_at > 60 * 60) {
      db_update_videofile(cam);
      close_output(cam);
      open_output(cam);
      got_key_frame = 0;
    }
  }

  db_update_videofile(cam);
  close_output(cam);

  if((ret = avcodec_close(cam->codec)) < 0)
    av_err_msg("avcodec_close", ret);
  avformat_close_input(&cam->context);
  av_free(frame);

  cvReleaseImage(&md.prev);
  cvReleaseImage(&md.cur);
  cvReleaseImage(&md.silh);
  av_free(md.buffer);
  sws_freeContext(md.img_convert_ctx);

  return NULL;
}
示例#25
0
static gboolean
dispatch_output (GPollableOutputStream *os,
                 gpointer user_data)
{
  CockpitStream *self = (CockpitStream *)user_data;
  GError *error = NULL;
  const gint8 *data;
  gsize len;
  gssize ret;

  g_return_val_if_fail (self->priv->out_source, FALSE);
  while (self->priv->out_queue->head)
    {
      data = g_bytes_get_data (self->priv->out_queue->head->data, &len);
      g_assert (self->priv->out_partial <= len);

      ret = g_pollable_output_stream_write_nonblocking (os, data + self->priv->out_partial,
                                                        len - self->priv->out_partial, NULL, &error);

      if (ret < 0)
        {
          if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
            {
              g_debug ("%s: output would block", self->priv->name);
              g_error_free (error);
              return TRUE;
            }
          else
            {
              set_problem_from_error (self, "couldn't write", error);
              g_error_free (error);
              close_immediately (self, NULL);
              return FALSE;
            }
        }

      self->priv->out_partial += ret;
      if (self->priv->out_partial >= len)
        {
          g_debug ("%s: wrote %d bytes", self->priv->name, (int)len);
          g_bytes_unref (g_queue_pop_head (self->priv->out_queue));
          self->priv->out_partial = 0;
        }
      else
        {
          if (ret > 0)
            g_debug ("%s: partial write %d of %d bytes", self->priv->name, (int)ret, (int)len);
          return TRUE;
        }
    }

  g_debug ("%s: output queue empty", self->priv->name);

  /* If all messages are done, then stop polling out fd */
  stop_output (self);

  if (self->priv->closing)
    close_output (self);
  else
    close_maybe (self);

  return TRUE;
}
void MidiPlayerThread::play()
{
    qDebug() << "MidiPlayerThread::play";

    const unsigned long int buf_size = 4096;

    int output_result = 0;
    unsigned long int count_diff;
    unsigned long int cur_sec, prev_sec;

    m_inPause = false;
    m_received_end_of_file = false;
    cur_sec = 0;

    QByteArray buf;
    buf.resize( buf_size );

    _WM_Info *wm_info = WildMidi_GetInfo( m_midiPtr );

    m_md->list();
    emit receivedStartingTime( 0 );
    emit backendFullyLoaded();
    emit receivedNoVideo();

    qDebug() << "approx_total_samples is " << wm_info->approx_total_samples;
    while ( 1 ) {
        if ( m_isStop ) {
            qDebug() << "MidiPlayerThread::play:   m_isStop = " << m_isStop;
            break;
        }
        count_diff = wm_info->approx_total_samples - wm_info->current_sample;

        if ( count_diff == 0 ) {
            qDebug() << "MidiPlayerThread::play:   it is count_diff == 0";
            break;
        }

        if ( m_inPause ) {
            usleep( 1000 );
            continue;
        }

        buf.fill( 0 );

        if ( count_diff < buf_size ) {
            buf.resize( count_diff * 4 );
            output_result = WildMidi_GetOutput ( m_midiPtr, buf.data(), ( count_diff * 4 ) );
        } else {
            output_result = WildMidi_GetOutput ( m_midiPtr, buf.data(), buf_size );
        }

        if ( output_result <= 0 ) {
            qDebug() << "MidiPlayerThread::play:   output_result <= 0";
            break;
        }
        prev_sec =  wm_info->current_sample / m_sample_rate;
        if ( prev_sec != cur_sec ) {
            cur_sec = prev_sec;
            emit receivedCurrentSec( cur_sec );
//            qDebug() << "cur_sec is " << cur_sec;
        }

        send_output( buf.data(), output_result );

        wm_info = WildMidi_GetInfo( m_midiPtr );
    }

//    buf.fill( 0, 16384 );
//    send_output( buf.data(), 16384);

//    buf.fill( 0, 16384 );
//    send_output( buf.data(), 16384);
//    send_output( buf.data(), 16384);

//    usleep( 5000 );

    if ( m_midiPtr ) {
        // file was played
        if ( WildMidi_Close( m_midiPtr ) == ( -1 ) ) {
            qDebug() << "oops!";
        }
        m_midiPtr = 0;
    }
    WildMidi_Shutdown();

    close_output();

//    emit processExited();
    m_received_end_of_file = true;

    qDebug() << "MidiPlayerThread::play:   end of play";
}
示例#27
0
文件: audio.c 项目: dreamerc/mpg123
/* Open an audio output module, trying modules in list (comma-separated). */
audio_output_t* open_output_module( const char* names )
{
	mpg123_module_t *module = NULL;
	audio_output_t *ao = NULL;
	int result = 0;
	char *curname, *modnames;

	if(param.usebuffer || names==NULL) return NULL;

	/* Use internal code. */
	if(param.outmode != DECODE_AUDIO) return open_fake_module();

	modnames = strdup(names);
	if(modnames == NULL)
	{
		error("Error allocating memory for module names.");
		return NULL;
	}
	/* Now loop over the list of possible modules to find one that works. */
	curname = strtok(modnames, ",");
	while(curname != NULL)
	{
		char* name = curname;
		curname = strtok(NULL, ",");
		if(param.verbose > 1) fprintf(stderr, "Trying output module %s.\n", name);
		/* Open the module, initial check for availability+libraries. */
		module = open_module( "output", name );
		if(module == NULL) continue;
		/* Check if module supports output */
		if(module->init_output == NULL)
		{
			error1("Module '%s' does not support audio output.", name);
			close_module(module);
			continue; /* Try next one. */
		}
		/* Allocation+initialization of memory for audio output type. */
		ao = alloc_audio_output();
		if(ao==NULL)
		{
			error("Failed to allocate audio output structure.");
			close_module(module);
			break; /* This is fatal. */
		}

		/* Call the init function */
		ao->device = param.output_device;
		ao->flags  = param.output_flags;
		/* Should I do funny stuff with stderr file descriptor instead? */
		if(curname == NULL)
		{
			if(param.verbose > 1)
			fprintf(stderr, "Note: %s is the last output option... showing you any error messages now.\n", name);
		}
		else ao->auxflags |= MPG123_OUT_QUIET; /* Probing, so don't spill stderr with errors. */
		ao->is_open = FALSE;
		ao->module = module; /* Need that to close module later. */
		result = module->init_output(ao);
		if(result == 0)
		{ /* Try to open the device. I'm only interested in actually working modules. */
			result = open_output(ao);
			close_output(ao);
		}
		else error2("Module '%s' init failed: %i", name, result);

		if(result!=0)
		{ /* Try next one... */
			close_module(module);
			free(ao);
			ao = NULL;
		}
		else 
		{ /* All good, leave the loop. */
			if(param.verbose > 1) fprintf(stderr, "Output module '%s' chosen.\n", name);

			ao->auxflags &= ~MPG123_OUT_QUIET;
			break;
		}
	}

	free(modnames);
	if(ao==NULL) error1("Unable to find a working output module in this list: %s", names);

	return ao;
}
示例#28
0
static int output_data(char *buf, int32 nbytes)
{
	unsigned int i;
	int32 samplesToGo;
	char *bufepoint;

    if(pa_active == 0) return -1; 
	
	while((pa_active==1) && (pa_data.samplesToGo > bytesPerInBuffer)){ Pa_Sleep(1);};
	
//	if(pa_data.samplesToGo > DATA_BLOCK_SIZE){ 
//		Sleep(  (pa_data.samplesToGo - DATA_BLOCK_SIZE)/dpm.rate/4  );
//	}
	samplesToGo=pa_data.samplesToGo;
	bufepoint=pa_data.bufepoint;

	if (pa_data.buf+bytesPerInBuffer*2 >= bufepoint + nbytes){
		memcpy(bufepoint, buf, nbytes);
		bufepoint += nbytes;
		//buf += nbytes;
	}else{
		int32 send = pa_data.buf+bytesPerInBuffer*2 - bufepoint;
		if (send != 0) memcpy(bufepoint, buf, send);
		buf += send;
		memcpy(pa_data.buf, buf, nbytes - send);
		bufepoint = pa_data.buf + nbytes - send;
		//buf += nbytes-send;
	}
	samplesToGo += nbytes;

	pa_data.samplesToGo=samplesToGo;
	pa_data.bufepoint=bufepoint;

/*
	if(firsttime==1){
		err = Pa_StartStream( stream );

		if( err != paNoError ) goto error;
		firsttime=0;
	}
*/
#if PORTAUDIO_V19
	if( 0==Pa_IsStreamActive(stream)){
#else
	if( 0==Pa_StreamActive(stream)){
#endif
		err = Pa_StartStream( stream );

		if( err != paNoError ) goto error;
	}
		
//	if(ctl->id_character != 'r' && ctl->id_character != 'A' && ctl->id_character != 'W' && ctl->id_character != 'P')
//	    while((pa_active==1) && (pa_data.samplesToGo > bytesPerInBuffer)){ Pa_Sleep(1);};
//	Pa_Sleep( (pa_data.samplesToGo - bytesPerInBuffer)/dpm.rate * 1000);
	return 0;

error:
	Pa_Terminate(); pa_active=0;
	ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "PortAudio error: %s\n", Pa_GetErrorText( err ) );
	return -1;
}

static void close_output(void)
{	
	if( pa_active==0) return;
#ifdef PORTAUDIO_V19
	if(Pa_IsStreamActive(stream)){
#else
	if(Pa_StreamActive(stream)){
#endif
		Pa_Sleep(  bytesPerInBuffer/dpm.rate*1000  );
	}	
	err = Pa_AbortStream( stream );
    if( (err!=paStreamIsStopped) && (err!=paNoError) ) goto error;
	err = Pa_CloseStream( stream );
//	if( err != paNoError ) goto error;
	Pa_Terminate(); 
	pa_active=0;

#ifdef AU_PORTAUDIO_DLL
#ifndef PORTAUDIO_V19
  free_portaudio_dll();
#endif
#endif

	return;

error:
	Pa_Terminate(); pa_active=0;
#ifdef AU_PORTAUDIO_DLL
#ifndef PORTAUDIO_V19
  free_portaudio_dll();
#endif
#endif
	ctl->cmsg(  CMSG_ERROR, VERB_NORMAL, "PortAudio error: %s\n", Pa_GetErrorText( err ) );
	return;
}


static int acntl(int request, void *arg)
{
    switch(request)
    {
 
      case PM_REQ_GETQSIZ:
		 *(int *)arg = bytesPerInBuffer*2;
    	return 0;
		//break;
      case PM_REQ_GETFILLABLE:
		 *(int *)arg = bytesPerInBuffer*2-pa_data.samplesToGo;
    	return 0;
		//break;
      case PM_REQ_GETFILLED:
		 *(int *)arg = pa_data.samplesToGo;
    	return 0;
		//break;

    	
   	case PM_REQ_DISCARD:
    case PM_REQ_FLUSH:
    	pa_data.samplesToGo=0;
    	pa_data.bufpoint=pa_data.bufepoint;
    	err = Pa_AbortStream( stream );
    	if( (err!=paStreamIsStopped) && (err!=paNoError) ) goto error;
    	err = Pa_StartStream( stream );
    	if(err!=paNoError) goto error;
		return 0;

		//break;

    case PM_REQ_RATE:  
    	{
    		int i;
    		double sampleRateBack;
    		i = *(int *)arg; //* sample rate in and out *
    		close_output();
    		sampleRateBack=dpm.rate;
    		dpm.rate=i;
    		if(0==open_output()){
    			return 0;
    		}else{    		
    			dpm.rate=sampleRateBack;
    			open_output();
    			return -1;
    		}
    	}
    	//break;

//    case PM_REQ_RATE: 
//          return -1;
    	
    case PM_REQ_PLAY_START: //* Called just before playing *
    case PM_REQ_PLAY_END: //* Called just after playing *
        return 0;
      
	default:
    	return -1;

    }
	return -1;
error:
/*
	Pa_Terminate(); pa_active=0;
#ifdef AU_PORTAUDIO_DLL
  free_portaudio_dll();
#endif
*/
	ctl->cmsg(  CMSG_ERROR, VERB_NORMAL, "PortAudio error in acntl : %s\n", Pa_GetErrorText( err ) );
	return -1;
}


static void print_device_list(void){
	PaDeviceIndex maxDeviceIndex, i;
	PaHostApiIndex HostApiIndex;
	const PaDeviceInfo* DeviceInfo;

#if PORTAUDIO_V19
	HostApiIndex=Pa_HostApiTypeIdToHostApiIndex(HostApiTypeId);
#endif
	
	maxDeviceIndex=Pa_GetDeviceCount();
	
	for( i = 0; i < maxDeviceIndex; i++){
		DeviceInfo=Pa_GetDeviceInfo(i);
#if PORTAUDIO_V19
		if( DeviceInfo->hostApi == HostApiIndex){
#endif
			if( DeviceInfo->maxOutputChannels > 0){
				ctl->cmsg(  CMSG_ERROR, VERB_NORMAL, "%2d %s",i,DeviceInfo->name);
			}
#if PORTAUDIO_V19
		}
#endif
	}
}
示例#29
0
static bool do_join()
{
  int i,bytes_to_skip,bytes_to_xfer;
  proc_info output_proc;
  char outfilename[FILENAME_SIZE];
  wlong total=0;
  unsigned char header[CANONICAL_HEADER_SIZE];
  FILE *output;
  wave_info *joined_info;
  bool success;
  progress_info proginfo;

  success = FALSE;

  create_output_filename("","",outfilename);

  for (i=0;i<numfiles;i++)
    total += files[i]->data_size;

  if (all_files_cd_quality && (total % CD_BLOCK_SIZE) != 0) {
    pad_bytes = CD_BLOCK_SIZE - (total % CD_BLOCK_SIZE);
    if (JOIN_NOPAD != pad_type)
      total += pad_bytes;
  }

  if (NULL == (joined_info = new_wave_info(NULL))) {
    st_error("could not allocate memory for joined file information");
  }

  joined_info->chunk_size = total + CANONICAL_HEADER_SIZE - 8;
  joined_info->channels = files[0]->channels;
  joined_info->samples_per_sec = files[0]->samples_per_sec;
  joined_info->avg_bytes_per_sec = files[0]->avg_bytes_per_sec;
  joined_info->rate = files[0]->rate;
  joined_info->block_align = files[0]->block_align;
  joined_info->bits_per_sample = files[0]->bits_per_sample;
  joined_info->data_size = total;
  joined_info->wave_format = files[0]->wave_format;
  joined_info->problems = (files[0]->problems & PROBLEM_NOT_CD_QUALITY);

  if (PROB_ODD_SIZED_DATA(joined_info))
    joined_info->chunk_size++;

  joined_info->total_size = joined_info->chunk_size + 8;
  joined_info->length = joined_info->data_size / joined_info->rate;
  joined_info->exact_length = (double)joined_info->data_size / (double)joined_info->rate;

  length_to_str(joined_info);

  proginfo.initialized = FALSE;
  proginfo.prefix = "Joining";
  proginfo.clause = "-->";
  proginfo.filename1 = files[0]->filename;
  proginfo.filedesc1 = files[0]->m_ss;
  proginfo.filename2 = outfilename;
  proginfo.filedesc2 = joined_info->m_ss;
  proginfo.bytes_total = files[0]->total_size;

  prog_update(&proginfo);

  if (NULL == (output = open_output_stream(outfilename,&output_proc))) {
    st_error("could not open output file");
  }

  make_canonical_header(header,joined_info);

  if (write_n_bytes(output,header,CANONICAL_HEADER_SIZE,&proginfo) != CANONICAL_HEADER_SIZE) {
    prog_error(&proginfo);
    st_warning("error while writing %d-byte WAVE header",CANONICAL_HEADER_SIZE);
    goto cleanup;
  }

  if (all_files_cd_quality && (JOIN_PREPAD == pad_type) && pad_bytes) {
    if (pad_bytes != write_padding(output,pad_bytes,&proginfo)) {
      prog_error(&proginfo);
      st_warning("error while pre-padding with %d zero-bytes",pad_bytes);
      goto cleanup;
    }
  }

  for (i=0;i<numfiles;i++) {
    proginfo.bytes_total = files[i]->total_size;
    proginfo.filename1 = files[i]->filename;
    proginfo.filedesc1 = files[i]->m_ss;
    prog_update(&proginfo);

    if (!open_input_stream(files[i])) {
      prog_error(&proginfo);
      st_warning("could not reopen input file");
      goto cleanup;
    }

    bytes_to_skip = files[i]->header_size;

    while (bytes_to_skip > 0) {
      bytes_to_xfer = min(bytes_to_skip,CANONICAL_HEADER_SIZE);
      if (read_n_bytes(files[i]->input,header,bytes_to_xfer,NULL) != bytes_to_xfer) {
        prog_error(&proginfo);
        st_warning("error while reading %d bytes of data",bytes_to_xfer);
        goto cleanup;
      }
      bytes_to_skip -= bytes_to_xfer;
    }

    if (transfer_n_bytes(files[i]->input,output,files[i]->data_size,&proginfo) != files[i]->data_size) {
      prog_error(&proginfo);
      st_warning("error while transferring %lu bytes of data",files[i]->data_size);
      goto cleanup;
    }

    prog_success(&proginfo);

    close_input_stream(files[i]);
  }

  if (all_files_cd_quality && JOIN_POSTPAD == pad_type && pad_bytes) {
    if (pad_bytes != write_padding(output,pad_bytes,NULL)) {
      prog_error(&proginfo);
      st_warning("error while post-padding with %d zero-bytes",pad_bytes);
      goto cleanup;
    }
  }

  if ((JOIN_NOPAD == pad_type) && PROB_ODD_SIZED_DATA(joined_info) && (1 != write_padding(output,1,NULL))) {
    prog_error(&proginfo);
    st_warning("error while NULL-padding odd-sized data chunk");
    goto cleanup;
  }

  if (all_files_cd_quality) {
    if (JOIN_NOPAD != pad_type) {
      if (pad_bytes)
        st_info("%s-padded output file with %d zero-bytes.\n",((JOIN_PREPAD == pad_type)?"Pre":"Post"),pad_bytes);
      else
        st_info("No padding needed.\n");
    }
    else {
      st_info("Output file was not padded, ");
      if (pad_bytes)
        st_info("though it needs %d bytes of padding.\n",pad_bytes);
      else
        st_info("nor was it needed.\n");
    }
  }

  success = TRUE;

cleanup:
  if ((CLOSE_CHILD_ERROR_OUTPUT == close_output(output,output_proc)) || !success) {
    success = FALSE;
    remove_file(outfilename);
    st_error("failed to join files");
  }

  return success;
}
示例#30
0
static int open_output(void)
{
    int include_enc = 0, exclude_enc = PE_BYTESWAP;
    struct stat sb;
    audio_info_t auinfo;
    char *audio_dev, *audio_ctl_dev, *tmp_audio;


    /* See if the AUDIODEV environment variable is defined, and set the
       audio device accordingly  - Lalit Chhabra 23/Oct/2001 */
    if((audio_dev  = getenv("AUDIODEV")) != NULL)
    {
      dpm.id_name = safe_malloc(strlen(audio_dev));
      dpm.name = safe_malloc(strlen(audio_dev));
      strcpy(dpm.name, audio_dev);
      strcpy(dpm.id_name, audio_dev);

      tmp_audio = safe_malloc(strlen(audio_dev) + 3);
      audio_ctl_dev = safe_malloc(strlen(audio_dev) + 3);

      strcpy(tmp_audio, audio_dev);
      strcpy(audio_ctl_dev, strcat(tmp_audio, "ctl"));
    }
    else
    {
      audio_ctl_dev = safe_malloc(strlen(AUDIO_CTLDEV) + 3);
      strcpy(audio_ctl_dev, AUDIO_CTLDEV);
    }

    output_counter = play_samples_offset = 0;

    /* Open the audio device */
    if((audioctl_fd = open(audio_ctl_dev, O_RDWR)) < 0)
    {
	ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
		  "%s: %s", audio_ctl_dev, strerror(errno));
	return -1;
    }

/* ############## */
#if 0
    if((dpm.fd = open(dpm.name, O_WRONLY | O_NDELAY)) == -1)
    {
	ctl->cmsg(CMSG_WARNING, VERB_NORMAL,
		  "%s: %s", dpm.name, strerror(errno));
	if(errno == EBUSY)
	{
	    if((dpm.fd = open(dpm.name, O_WRONLY)) == -1)
	    {
		ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
			  "%s: %s", dpm.name, strerror(errno));
		close_output();
		return -1;
	    }
	}
    }
#endif

    if((dpm.fd = open(dpm.name, O_WRONLY)) == -1)
    {
	ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
		  "%s: %s", dpm.name, strerror(errno));
	close_output();
	return -1;
    }

    if(stat(dpm.name, &sb) < 0)
    {
	ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
		  "%s: %s", dpm.name, strerror(errno));
	close_output();
	return -1;
    }

    if(!S_ISCHR(sb.st_mode))
    {
	ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
		  "%s: Not a audio device", dpm.name);
	close_output();
	return -1;
    }

    if(sun_audio_getinfo(&auinfo) < 0)
    { 
	/* from Francesco Zanichelli's */
	/* If it doesn't give info, it probably won't take requests
	    either. Assume it's an old device that does 8kHz uLaw only.

	      Disclaimer: I don't know squat about the various Sun audio
		  devices, so if this is not what we should do, I'll gladly
		      accept modifications. */
	ctl->cmsg(CMSG_WARNING, VERB_NORMAL, "Cannot inquire %s", dpm.name);
	include_enc = PE_ULAW|PE_ALAW|PE_MONO;
	exclude_enc = PE_SIGNED|PE_16BIT|PE_BYTESWAP;
	dpm.encoding = validate_encoding(dpm.encoding,
					 include_enc, exclude_enc);
	if(dpm.rate != 8000)
	    ctl->cmsg(CMSG_WARNING, VERB_VERBOSE,
		      "Sample rate is changed %d to 8000",
		      dpm.rate);
	dpm.rate = 8000;
	return 1;
    }

    if(!(dpm.encoding & PE_16BIT))
	exclude_enc |= PE_SIGNED; /* Always unsigned */
    dpm.encoding = validate_encoding(dpm.encoding, include_enc, exclude_enc);

    AUDIO_INITINFO(&auinfo);
    auinfo.play.sample_rate = dpm.rate;
    auinfo.play.channels = (dpm.encoding & PE_MONO) ? 1 : 2;
    auinfo.play.encoding = sun_audio_encoding(dpm.encoding);
    auinfo.play.precision = (dpm.encoding & PE_16BIT) ? 16 : 8;

    if(sun_audio_setinfo(&auinfo) == -1)
    {
	ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
		  "rate=%d, channels=%d, precision=%d, encoding=%s",
		  auinfo.play.sample_rate, auinfo.play.channels,
		  auinfo.play.precision, output_encoding_string(dpm.encoding));
	close_output();
	return -1;
    }

    return 0;
}