コード例 #1
0
ファイル: rts.c プロジェクト: ArthurGodoy/FreeRDP
void rts_cookie_command_read(rdpRpc* rpc, STREAM* s)
{
	stream_seek(s, 16); /* Cookie (16 bytes) */
}
コード例 #2
0
int decode_thread(void *arg) {

    VideoState *is = (VideoState *)arg;
    AVFormatContext *pFormatCtx = NULL;
    AVPacket pkt1, *packet = &pkt1;

    AVDictionary *io_dict = NULL;
    AVIOInterruptCB callback;

    int video_index = -1;
    int audio_index = -1;
    int i;

    is->videoStream=-1;
    is->audioStream=-1;
    is->audio_need_resample = 0;

    global_video_state = is;
    // will interrupt blocking functions if we quit!
    callback.callback = decode_interrupt_cb;
    callback.opaque = is;
    if (avio_open2(&is->io_context, is->filename, 0, &callback, &io_dict)) {
        fprintf(stderr, "Unable to open I/O for %s\n", is->filename);
        return -1;
    }

    // Open video file
    if(avformat_open_input(&pFormatCtx, is->filename, NULL, NULL)!=0)
        return -1; // Couldn't open file

    is->pFormatCtx = pFormatCtx;

    // Retrieve stream information
    if(avformat_find_stream_info(pFormatCtx, NULL)<0)
        return -1; // Couldn't find stream information

    // Dump information about file onto standard error
    av_dump_format(pFormatCtx, 0, is->filename, 0);

    // Find the first video stream
    for(i=0; i<pFormatCtx->nb_streams; i++) {
        if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO &&
                video_index < 0) {
            video_index=i;
        } else if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO &&
                  audio_index < 0) {
            audio_index=i;
        }
    }
    if(audio_index >= 0) {
        stream_component_open(is, audio_index);
    }
    if(video_index >= 0) {
        stream_component_open(is, video_index);
    }

    if(is->videoStream < 0 && is->audioStream < 0) {
        fprintf(stderr, "%s: could not open codecs\n", is->filename);
        goto fail;
    }

#ifdef __RESAMPLER__
    if( audio_index >= 0
            && pFormatCtx->streams[audio_index]->codec->sample_fmt != AV_SAMPLE_FMT_S16) {
        is->audio_need_resample=1;
        is->pResampledOut=NULL;
        is->pSwrCtx = NULL;

        printf("Configure resampler: ");

#ifdef __LIBAVRESAMPLE__
        printf("libAvResample\n");
        is->pSwrCtx = avresample_alloc_context();
#endif

#ifdef __LIBSWRESAMPLE__
        printf("libSwResample\n");
        is->pSwrCtx = swr_alloc();
#endif

        // Some MP3/WAV don't tell this so make assumtion that
        // They are stereo not 5.1
        if (pFormatCtx->streams[audio_index]->codec->channel_layout == 0
                && pFormatCtx->streams[audio_index]->codec->channels == 2) {
            pFormatCtx->streams[audio_index]->codec->channel_layout = AV_CH_LAYOUT_STEREO;
        } else if (pFormatCtx->streams[audio_index]->codec->channel_layout == 0
                   && pFormatCtx->streams[audio_index]->codec->channels == 1) {
            pFormatCtx->streams[audio_index]->codec->channel_layout = AV_CH_LAYOUT_MONO;
        } else if (pFormatCtx->streams[audio_index]->codec->channel_layout == 0
                   && pFormatCtx->streams[audio_index]->codec->channels == 0) {
            pFormatCtx->streams[audio_index]->codec->channel_layout = AV_CH_LAYOUT_STEREO;
            pFormatCtx->streams[audio_index]->codec->channels = 2;
        }

        av_opt_set_int(is->pSwrCtx,"in_channel_layout",
                       pFormatCtx->streams[audio_index]->codec->channel_layout, 0);
        av_opt_set_int(is->pSwrCtx,"in_sample_fmt",
                       pFormatCtx->streams[audio_index]->codec->sample_fmt, 0);
        av_opt_set_int(is->pSwrCtx,"in_sample_rate",
                       pFormatCtx->streams[audio_index]->codec->sample_rate, 0);

        av_opt_set_int(is->pSwrCtx,"out_channel_layout", AV_CH_LAYOUT_STEREO, 0);
        av_opt_set_int(is->pSwrCtx,"out_sample_fmt", AV_SAMPLE_FMT_S16, 0);
        av_opt_set_int(is->pSwrCtx,"out_sample_rate", 44100, 0);

#ifdef __LIBAVRESAMPLE__
        if (avresample_open(is->pSwrCtx) < 0) {
#else
        if (swr_init(is->pSwrCtx) < 0) {
#endif
            fprintf(stderr, " ERROR!! From Samplert: %d Hz Sample format: %s\n",
                    pFormatCtx->streams[audio_index]->codec->sample_rate,
                    av_get_sample_fmt_name(pFormatCtx->streams[audio_index]->codec->sample_fmt));
            fprintf(stderr, "         To 44100 Sample format: s16\n");
            is->audio_need_resample=0;
            is->pSwrCtx = NULL;;
        }

    }
#endif

    // main decode loop

    for(;;) {
        if(is->quit) {
            break;
        }
        // seek stuff goes here
        if(is->seek_req) {
            int stream_index= -1;

            int64_t seek_target = is->seek_pos;

            if     (is->videoStream >= 0) stream_index = is->videoStream;
            else if(is->audioStream >= 0) stream_index = is->audioStream;

            if(stream_index>=0) {
                seek_target= av_rescale_q(seek_target, AV_TIME_BASE_Q,
                                          pFormatCtx->streams[stream_index]->time_base);
            }
            printf("Seek_target: %ld/%ld stream_index: %ld\n",is->seek_pos, seek_target, stream_index);

            if(av_seek_frame(is->pFormatCtx, stream_index, seek_target,
                             is->seek_flags) < 0) {
                fprintf(stderr, "%s: error while seeking\n", is->pFormatCtx->filename);
            } else {
                if(is->audioStream >= 0) {
                    packet_queue_flush(&is->audioq);
                    packet_queue_put(&is->audioq, &flush_pkt);
                }
                if(is->videoStream >= 0) {
                    packet_queue_flush(&is->videoq);
                    packet_queue_put(&is->videoq, &flush_pkt);
                }
            }
            is->seek_req = 0;
        }

        if(is->audioq.size > MAX_AUDIOQ_SIZE ||
                is->videoq.size > MAX_VIDEOQ_SIZE) {
            SDL_Delay(10);
            continue;
        }
        if(av_read_frame(is->pFormatCtx, packet) < 0) {
            if(is->pFormatCtx->pb->error == 0) {
                SDL_Delay(100); /* no error; wait for user input */
                continue;
            } else {
                break;
            }
        }
        // Is this a packet from the video stream?
        if(packet->stream_index == is->videoStream) {
            packet_queue_put(&is->videoq, packet);
        } else if(packet->stream_index == is->audioStream) {
            packet_queue_put(&is->audioq, packet);
        } else {
            av_free_packet(packet);
        }
    }
    /* all done - wait for it */
    while(!is->quit) {
        SDL_Delay(100);
    }
fail: {
        SDL_Event event;
        event.type = FF_QUIT_EVENT;
        event.user.data1 = is;
        SDL_PushEvent(&event);
    }
    return 0;
}

void stream_seek(VideoState *is, int64_t pos, int rel) {

  if(!is->seek_req) {
    is->seek_pos = pos;
    is->seek_flags = rel < 0 ? AVSEEK_FLAG_BACKWARD : 0;
    is->seek_req = 1;
  }
}
int main(int argc, char *argv[]) {

  SDL_Event       event;
  //double          pts;
  VideoState      *is;

  is = av_mallocz(sizeof(VideoState));

  if(argc < 2) {
    fprintf(stderr, "Usage: test <file>\n");
    exit(1);
  }
  // Register all formats and codecs
  av_register_all();
  
  if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
    fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
    exit(1);
  }

  // Make a screen to put our video
#ifndef __DARWIN__
  screen = SDL_SetVideoMode(640, 480, 0, 0);
#else
  screen = SDL_SetVideoMode(640, 480, 24, 0);
#endif
  if(!screen) {
    fprintf(stderr, "SDL: could not set video mode - exiting\n");
    exit(1);
  }

  av_strlcpy(is->filename, argv[1], 1024);

  is->pictq_mutex = SDL_CreateMutex();
  is->pictq_cond = SDL_CreateCond();

  schedule_refresh(is, 40);

  is->av_sync_type = DEFAULT_AV_SYNC_TYPE;
  is->parse_tid = SDL_CreateThread(decode_thread, is);
  if(!is->parse_tid) {
    av_free(is);
    return -1;
  }

  av_init_packet(&flush_pkt);
  flush_pkt.data = (unsigned char *)"FLUSH";
  
  for(;;) {
    double incr, pos;
    SDL_WaitEvent(&event);
    switch(event.type) {
    case SDL_KEYDOWN:
      switch(event.key.keysym.sym) {
      case SDLK_LEFT:
	incr = -10.0;
	goto do_seek;
      case SDLK_RIGHT:
	incr = 10.0;
	goto do_seek;
      case SDLK_UP:
	incr = 60.0;
	goto do_seek;
      case SDLK_DOWN:
	incr = -60.0;
	goto do_seek;
      do_seek:
	if(global_video_state) {
	  pos = get_master_clock(global_video_state);
	  pos += incr;
	  stream_seek(global_video_state, (int64_t)(pos * AV_TIME_BASE), incr);
	}
	break;
      default:
	break;
      }
      break;
    case FF_QUIT_EVENT:
    case SDL_QUIT:
      is->quit = 1;
      /*
       * If the video has finished playing, then both the picture and
       * audio queues are waiting for more data.  Make them stop
       * waiting and terminate normally.
       */
      SDL_CondSignal(is->audioq.cond);
      SDL_CondSignal(is->videoq.cond);
      SDL_Quit();
      exit(0);
      break;
    case FF_ALLOC_EVENT:
      alloc_picture(event.user.data1);
      break;
    case FF_REFRESH_EVENT:
      video_refresh_timer(event.user.data1);
      break;
    default:
      break;
    }
  }
  return 0;
}
コード例 #3
0
ファイル: info.c プロジェクト: zzzhou/FreeRDP
boolean rdp_read_info_packet(STREAM* s, rdpSettings* settings)
{
	uint32 flags;
	uint16 cbDomain;
	uint16 cbUserName;
	uint16 cbPassword;
	uint16 cbAlternateShell;
	uint16 cbWorkingDir;

	stream_seek_uint32(s); /* CodePage */
	stream_read_uint32(s, flags); /* flags */

	settings->autologon = ((flags & INFO_AUTOLOGON) ? True : False);
	settings->remote_app = ((flags & INFO_RAIL) ? True : False);
	settings->console_audio = ((flags & INFO_REMOTECONSOLEAUDIO) ? True : False);
	settings->compression = ((flags & INFO_COMPRESSION) ? True : False);

	stream_read_uint16(s, cbDomain); /* cbDomain */
	stream_read_uint16(s, cbUserName); /* cbUserName */
	stream_read_uint16(s, cbPassword); /* cbPassword */
	stream_read_uint16(s, cbAlternateShell); /* cbAlternateShell */
	stream_read_uint16(s, cbWorkingDir); /* cbWorkingDir */

	if (stream_get_left(s) < cbDomain + 2)
		return False;
	if (cbDomain > 0)
	{
		settings->domain = freerdp_uniconv_in(settings->uniconv, stream_get_tail(s), cbDomain);
		stream_seek(s, cbDomain);
	}
	stream_seek(s, 2);

	if (stream_get_left(s) < cbUserName + 2)
		return False;
	if (cbUserName > 0)
	{
		settings->username = freerdp_uniconv_in(settings->uniconv, stream_get_tail(s), cbUserName);
		stream_seek(s, cbUserName);
	}
	stream_seek(s, 2);

	if (stream_get_left(s) < cbPassword + 2)
		return False;
	if (cbPassword > 0)
	{
		settings->password = freerdp_uniconv_in(settings->uniconv, stream_get_tail(s), cbPassword);
		stream_seek(s, cbPassword);
	}
	stream_seek(s, 2);

	if (stream_get_left(s) < cbAlternateShell + 2)
		return False;
	if (cbAlternateShell > 0)
	{
		settings->shell = freerdp_uniconv_in(settings->uniconv, stream_get_tail(s), cbAlternateShell);
		stream_seek(s, cbAlternateShell);
	}
	stream_seek(s, 2);

	if (stream_get_left(s) < cbWorkingDir + 2)
		return False;
	if (cbWorkingDir > 0)
	{
		settings->directory = freerdp_uniconv_in(settings->uniconv, stream_get_tail(s), cbWorkingDir);
		stream_seek(s, cbWorkingDir);
	}
	stream_seek(s, 2);

	if (settings->rdp_version >= 5)
		return rdp_read_extended_info_packet(s, settings); /* extraInfo */

	return True;
}
コード例 #4
0
ファイル: certificate.c プロジェクト: Arkantos7/FreeRDP
void certificate_read_x509_certificate(rdpCertBlob* cert, rdpCertInfo* info)
{
	STREAM* s;
	int length;
	BYTE padding;
	UINT32 version;
	int modulus_length;
	int exponent_length;

	s = stream_new(0);
	stream_attach(s, cert->data, cert->length);

	ber_read_sequence_tag(s, &length); /* Certificate (SEQUENCE) */

	ber_read_sequence_tag(s, &length); /* TBSCertificate (SEQUENCE) */

	/* Explicit Contextual Tag [0] */
	ber_read_contextual_tag(s, 0, &length, TRUE);
	ber_read_integer(s, &version); /* version (INTEGER) */
	version++;

	/* serialNumber */
	ber_read_integer(s, NULL); /* CertificateSerialNumber (INTEGER) */

	/* signature */
	ber_read_sequence_tag(s, &length); /* AlgorithmIdentifier (SEQUENCE) */
	stream_seek(s, length);

	/* issuer */
	ber_read_sequence_tag(s, &length); /* Name (SEQUENCE) */
	stream_seek(s, length);

	/* validity */
	ber_read_sequence_tag(s, &length); /* Validity (SEQUENCE) */
	stream_seek(s, length);

	/* subject */
	ber_read_sequence_tag(s, &length); /* Name (SEQUENCE) */
	stream_seek(s, length);

	/* subjectPublicKeyInfo */
	ber_read_sequence_tag(s, &length); /* SubjectPublicKeyInfo (SEQUENCE) */

	/* subjectPublicKeyInfo::AlgorithmIdentifier */
	ber_read_sequence_tag(s, &length); /* AlgorithmIdentifier (SEQUENCE) */
	stream_seek(s, length);

	/* subjectPublicKeyInfo::subjectPublicKey */
	ber_read_bit_string(s, &length, &padding); /* BIT_STRING */

	/* RSAPublicKey (SEQUENCE) */
	ber_read_sequence_tag(s, &length); /* SEQUENCE */

	ber_read_integer_length(s, &modulus_length); /* modulus (INTEGER) */

	/* skip zero padding, if any */
	do
	{
		stream_peek_BYTE(s, padding);

		if (padding == 0)
		{
			stream_seek(s, 1);
			modulus_length--;
		}
	}
	while (padding == 0);

	info->ModulusLength = modulus_length;
	info->Modulus = (BYTE*) malloc(info->ModulusLength);
	stream_read(s, info->Modulus, info->ModulusLength);

	ber_read_integer_length(s, &exponent_length); /* publicExponent (INTEGER) */
	stream_read(s, &info->exponent[4 - exponent_length], exponent_length);
	crypto_reverse(info->Modulus, info->ModulusLength);
	crypto_reverse(info->exponent, 4);

	stream_detach(s);
	stream_free(s);
}
コード例 #5
0
ファイル: connection.c プロジェクト: johnsonyes/FreeRDP
static boolean rdp_establish_keys(rdpRdp* rdp)
{
	uint8 client_random[32];
	uint8 crypt_client_random[256 + 8];
	uint32 key_len;
	uint8* mod;
	uint8* exp;
	uint32 length;
	STREAM* s;

	if (rdp->settings->encryption == false)
	{
		/* no RDP encryption */
		return true;
	}

	/* encrypt client random */
	memset(crypt_client_random, 0, sizeof(crypt_client_random));
	memset(client_random, 0x5e, 32);
	crypto_nonce(client_random, 32);
	key_len = rdp->settings->server_cert->cert_info.modulus.length;
	mod = rdp->settings->server_cert->cert_info.modulus.data;
	exp = rdp->settings->server_cert->cert_info.exponent;
	crypto_rsa_encrypt(client_random, 32, key_len, mod, exp, crypt_client_random);

	/* send crypt client random to server */
	length = 7 + 8 + 4 + 4 + key_len + 8;
	s = transport_send_stream_init(rdp->mcs->transport, length);
	tpkt_write_header(s, length);
	tpdu_write_header(s, 2, 0xf0);
	per_write_choice(s, DomainMCSPDU_SendDataRequest << 2);
	per_write_integer16(s, rdp->mcs->user_id, MCS_BASE_CHANNEL_ID);
	per_write_integer16(s, MCS_GLOBAL_CHANNEL_ID, 0);
	stream_write_uint8(s, 0x70);
	length = (4 + 4 + key_len + 8) | 0x8000;
	stream_write_uint16_be(s, length);
	stream_write_uint32(s, 1); /* SEC_CLIENT_RANDOM */
	length = key_len + 8;
	stream_write_uint32(s, length);
	memcpy(s->p, crypt_client_random, length);
	stream_seek(s, length);
	if (transport_write(rdp->mcs->transport, s) < 0)
	{
		return false;
	}

	/* now calculate encrypt / decrypt and update keys */
	if (!security_establish_keys(client_random, rdp))
	{
		return false;
	}

	rdp->do_crypt = true;

	if (rdp->settings->encryption_method == ENCRYPTION_METHOD_FIPS)
	{
		uint8 fips_ivec[8] = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
		rdp->fips_encrypt = crypto_des3_encrypt_init(rdp->fips_encrypt_key, fips_ivec);
		rdp->fips_decrypt = crypto_des3_decrypt_init(rdp->fips_decrypt_key, fips_ivec);

		rdp->fips_hmac = crypto_hmac_new();
		return true;
	}

	rdp->rc4_decrypt_key = crypto_rc4_init(rdp->decrypt_key, rdp->rc4_key_len);
	rdp->rc4_encrypt_key = crypto_rc4_init(rdp->encrypt_key, rdp->rc4_key_len);

	return true;
}
コード例 #6
0
ファイル: imghd.c プロジェクト: CrouchingLlama/openlase-mame
/*
	imgtool_chd_write - interface for writing to a hard disk image
*/
static UINT32 imgtool_chd_write(chd_interface_file *file, UINT64 offset, UINT32 count, const void *buffer)
{
	stream_seek((imgtool_stream *)file, offset, SEEK_SET);
	return stream_write((imgtool_stream *)file, buffer, count);
}
コード例 #7
0
ファイル: demux_fli.c プロジェクト: azuwis/mplayer
static demuxer_t* demux_open_fli(demuxer_t* demuxer){
  sh_video_t *sh_video = NULL;
  fli_frames_t *frames = malloc(sizeof(fli_frames_t));
  int frame_number;
  int speed;
  unsigned int frame_size;
  int magic_number;
  unsigned char * header;

  // go back to the beginning
  stream_reset(demuxer->stream);
  stream_seek(demuxer->stream, 0);

  header = calloc(1, sizeof(BITMAPINFOHEADER) + 128);
  stream_read(demuxer->stream, header + sizeof(BITMAPINFOHEADER), 128);
  stream_seek(demuxer->stream, 0);

  demuxer->movi_start = 128;
  demuxer->movi_end = stream_read_dword_le(demuxer->stream);

  magic_number = stream_read_word_le(demuxer->stream);

  if ((magic_number != 0xAF11) && (magic_number != 0xAF12))
  {
    mp_msg(MSGT_DEMUX, MSGL_ERR, "Bad/unknown magic number (%04x)\n",
	magic_number);
    free(header);
    free(frames);
    return NULL;
  }

  // fetch the number of frames
  frames->num_frames = stream_read_word_le(demuxer->stream);
  frames->current_frame = 0;

  // allocate enough entries for the indices
  //   audit: num_frames is 16bit so it is safe against overflow
  frames->filepos = malloc(frames->num_frames * sizeof(off_t));
  frames->frame_size = malloc(frames->num_frames * sizeof(int));

  // create a new video stream header
  sh_video = new_sh_video(demuxer, 0);

  // make sure the demuxer knows about the new video stream header
  // (even though new_sh_video() ought to take care of it)
  demuxer->video->sh = sh_video;

  // make sure that the video demuxer stream header knows about its
  // parent video demuxer stream (this is getting wacky), or else
  // video_read_properties() will choke
  sh_video->ds = demuxer->video;

  // custom fourcc for internal MPlayer use
  sh_video->format = mmioFOURCC('F', 'L', 'I', 'C');

  sh_video->disp_w = stream_read_word_le(demuxer->stream);
  sh_video->disp_h = stream_read_word_le(demuxer->stream);

  // pass extradata to codec
  sh_video->bih = (BITMAPINFOHEADER*)header;
  sh_video->bih->biSize = sizeof(BITMAPINFOHEADER) + 128;
  sh_video->bih->biWidth = sh_video->disp_w;
  sh_video->bih->biHeight = sh_video->disp_h;

  // skip the video depth and flags
  stream_skip(demuxer->stream, 4);

  // get the speed
  speed = stream_read_word_le(demuxer->stream);
  if (speed == 0)
    speed = 1;
  if (magic_number == 0xAF11)
    speed *= 1000/70;
  sh_video->fps = 1000 / speed;
  sh_video->frametime = 1/sh_video->fps;

  // build the frame index
  stream_seek(demuxer->stream, demuxer->movi_start);
  frame_number = 0;
  while ((!stream_eof(demuxer->stream)) && (frame_number < frames->num_frames))
  {
    frames->filepos[frame_number] = stream_tell(demuxer->stream);
    frame_size = stream_read_dword_le(demuxer->stream);
    magic_number = stream_read_word_le(demuxer->stream);
    stream_skip(demuxer->stream, frame_size - 6);

    // if this chunk has the right magic number, index it
    if ((magic_number == 0xF1FA) || (magic_number == 0xF5FA))
    {
      frames->frame_size[frame_number] = frame_size;
      frame_number++;
    }
  }

  // save the actual number of frames indexed
  frames->num_frames = frame_number;

  demuxer->priv = frames;

  return demuxer;
}
コード例 #8
0
ファイル: nego.c プロジェクト: mehulsbhatt/FreeRDP
boolean nego_send_negotiation_response(rdpNego* nego)
{
	STREAM* s;
	uint8* bm;
	uint8* em;
	int length;
	boolean status;
	rdpSettings* settings;

	status = true;
	settings = nego->transport->settings;

	s = transport_send_stream_init(nego->transport, 256);
	length = TPDU_CONNECTION_CONFIRM_LENGTH;
	stream_get_mark(s, bm);
	stream_seek(s, length);

	if (nego->selected_protocol > PROTOCOL_RDP)
	{
		/* RDP_NEG_DATA must be present for TLS and NLA */
		stream_write_uint8(s, TYPE_RDP_NEG_RSP);
		stream_write_uint8(s, EXTENDED_CLIENT_DATA_SUPPORTED); /* flags */
		stream_write_uint16(s, 8); /* RDP_NEG_DATA length (8) */
		stream_write_uint32(s, nego->selected_protocol); /* selectedProtocol */
		length += 8;
	}
	else if (!settings->rdp_security)
	{
		stream_write_uint8(s, TYPE_RDP_NEG_FAILURE);
		stream_write_uint8(s, 0); /* flags */
		stream_write_uint16(s, 8); /* RDP_NEG_DATA length (8) */
		/*
		 * TODO: Check for other possibilities,
		 *       like SSL_NOT_ALLOWED_BY_SERVER.
		 */
		printf("nego_send_negotiation_response: client supports only Standard RDP Security\n");
		stream_write_uint32(s, SSL_REQUIRED_BY_SERVER);
		length += 8;
		status = false;
	}

	stream_get_mark(s, em);
	stream_set_mark(s, bm);
	tpkt_write_header(s, length);
	tpdu_write_connection_confirm(s, length - 5);
	stream_set_mark(s, em);

	if (transport_write(nego->transport, s) < 0)
		return false;

	if (status)
	{
		/* update settings with negotiated protocol security */
		settings->requested_protocols = nego->requested_protocols;
		settings->selected_protocol = nego->selected_protocol;

		if (settings->selected_protocol == PROTOCOL_RDP)
		{
			settings->tls_security = false;
			settings->nla_security = false;
			settings->rdp_security = true;

			if (!settings->local)
			{
				settings->encryption = true;
				settings->encryption_method = ENCRYPTION_METHOD_40BIT | ENCRYPTION_METHOD_128BIT | ENCRYPTION_METHOD_FIPS;
				settings->encryption_level = ENCRYPTION_LEVEL_CLIENT_COMPATIBLE;
			}

			if (settings->encryption && settings->server_key == NULL && settings->rdp_key_file == NULL)
				return false;
		}
		else if (settings->selected_protocol == PROTOCOL_TLS)
		{
			settings->tls_security = true;
			settings->nla_security = false;
			settings->rdp_security = false;
			settings->encryption = false;
			settings->encryption_method = ENCRYPTION_METHOD_NONE;
			settings->encryption_level = ENCRYPTION_LEVEL_NONE;
		}
		else if (settings->selected_protocol == PROTOCOL_NLA)
		{
			settings->tls_security = true;
			settings->nla_security = true;
			settings->rdp_security = false;
			settings->encryption = false;
			settings->encryption_method = ENCRYPTION_METHOD_NONE;
			settings->encryption_level = ENCRYPTION_LEVEL_NONE;
		}
	}

	return status;
}
コード例 #9
0
ファイル: kerberos.c プロジェクト: mattymo/FreeRDP
void krb_asreq_send(KRB_CONTEXT* krb_ctx, uint8 errcode)
{
	KrbASREQ* krb_asreq;
	PAData** pa_data;
	KrbENCData enc_data;
	KrbENCKey* enckey;
	STREAM* s;
	STREAM* paenc;
	rdpBlob msg;
	rdpBlob* encmsg;
	uint32 curlen, totlen, pai;
	uint8 *bm;
	bm = NULL;
	totlen = pai = 0;
	krb_asreq = krb_asreq_new(krb_ctx, errcode);
	pa_data = krb_asreq->padata;
	enckey = NULL;
	s = stream_new(2048);
	paenc = stream_new(100);
	
	//Begin write asn1 data reversely into stream
	stream_seek(s, 1024);
	stream_seek(paenc, 99);
	
	/* KDC-REQ-BODY (TAG 4) */
	totlen += krb_encode_req_body(s, &(krb_asreq->req_body), krb_asreq->type);
	totlen += krb_encode_contextual_tag(s, 4, totlen);

	/* padata = PA-ENC-TIMESTAMP */
	if(errcode != 0)
	{
		freerdp_blob_alloc(&msg, 21);
		memcpy(msg.data, "\x30\x13\xa0\x11\x18\x0f", 6); // PA-ENC-TS-ENC without optional pausec
		memcpy(((uint8*) msg.data) + 6, krb_asreq->req_body.from, 15);
		enckey = string2key(&(krb_ctx->passwd), krb_ctx->enctype);
		encmsg = crypto_kdcmsg_encrypt(&msg, enckey, 1); //RFC4757 section 3 for msgtype (T=1)
		enc_data.enctype = enckey->enctype;
		enc_data.kvno = -1;
		enc_data.encblob.data = encmsg->data;
		enc_data.encblob.length = encmsg->length;
		curlen = krb_encode_encrypted_data(paenc, &enc_data);
		freerdp_blob_free(&msg);
		msg.data = paenc->p;
		msg.length = curlen;

		/* padata = PA-ENC-TIMESTAMP */
		(*(pa_data + pai))->type = 2;
		(*(pa_data + pai))->value = msg;
		pai++;
		freerdp_blob_free(encmsg);
		xfree(encmsg);
	}
	
	freerdp_blob_alloc(&msg, 7);
	memcpy(msg.data, "\x30\x05\xa0\03\x01\x01", 6); // asn1 data
	*((uint8*)msg.data + 6) = krb_asreq->pa_pac_request;

	/* padata = PA-PAC-REQUEST */
	(*(pa_data + pai))->type = 128;
	(*(pa_data + pai))->value = msg;

	*(pa_data + ++pai) = NULL;

	/* padata (TAG 3) */
	curlen = krb_encode_padata(s, pa_data);
	totlen += curlen + krb_encode_contextual_tag(s, 3, curlen);

	/* MSGTYPE = AS-REQ (TAG 2) */
	totlen += krb_encode_uint8(s, 2, krb_asreq->type);

	/* KERBEROS PROTOCOL VERSION NO (TAG 1)*/
	totlen += krb_encode_uint8(s, 1, krb_asreq->pvno);

	totlen += krb_encode_sequence_tag(s, totlen);
	totlen += krb_encode_application_tag(s, krb_asreq->type, totlen);
	totlen += krb_encode_recordmark(s, totlen);

	/* READY SEND */
	krb_tcp_send(krb_ctx, s->p, totlen);

	/* save stuff */
	krb_ctx->askey = enckey;
	krb_ctx->nonce = krb_asreq->req_body.nonce;
	xfree(krb_ctx->sname);
	krb_ctx->sname = xstrdup(krb_asreq->req_body.sname);
	krb_ctx->ctime = get_local_time(krb_asreq->req_body.from);
	krb_ctx->state = KRB_ASREQ_OK;

	/* clean up */
	freerdp_blob_free(&msg);
	stream_free(s);
	stream_free(paenc);
	krb_free_asreq(krb_asreq);
	xfree(krb_asreq);
}
コード例 #10
0
ファイル: tsmf_main.c プロジェクト: ngraziano/FreeRDP
static int tsmf_on_data_received(IWTSVirtualChannelCallback* pChannelCallback,
                                 uint32 cbSize,
                                 uint8* pBuffer)
{
    int length;
    STREAM* input;
    STREAM* output;
    int error = -1;
    TSMF_IFMAN ifman;
    uint32 MessageId;
    uint32 FunctionId;
    uint32 InterfaceId;
    TSMF_CHANNEL_CALLBACK* callback = (TSMF_CHANNEL_CALLBACK*) pChannelCallback;

    /* 2.2.1 Shared Message Header (SHARED_MSG_HEADER) */
    if (cbSize < 12)
    {
        DEBUG_WARN("invalid size. cbSize=%d", cbSize);
        return 1;
    }
    input = stream_new(0);
    stream_attach(input, (uint8*) pBuffer, cbSize);
    output = stream_new(256);
    stream_seek(output, 8);

    stream_read_uint32(input, InterfaceId);
    stream_read_uint32(input, MessageId);
    stream_read_uint32(input, FunctionId);
    DEBUG_DVC("cbSize=%d InterfaceId=0x%X MessageId=0x%X FunctionId=0x%X",
              cbSize, InterfaceId, MessageId, FunctionId);

    memset(&ifman, 0, sizeof(TSMF_IFMAN));
    ifman.channel_callback = pChannelCallback;
    ifman.decoder_name = ((TSMF_PLUGIN*) callback->plugin)->decoder_name;
    ifman.audio_name = ((TSMF_PLUGIN*) callback->plugin)->audio_name;
    ifman.audio_device = ((TSMF_PLUGIN*) callback->plugin)->audio_device;
    memcpy(ifman.presentation_id, callback->presentation_id, 16);
    ifman.stream_id = callback->stream_id;
    ifman.message_id = MessageId;
    ifman.input = input;
    ifman.input_size = cbSize - 12;
    ifman.output = output;
    ifman.output_pending = False;
    ifman.output_interface_id = InterfaceId;

    switch (InterfaceId)
    {
    case TSMF_INTERFACE_CAPABILITIES | STREAM_ID_NONE:

        switch (FunctionId)
        {
        case RIM_EXCHANGE_CAPABILITY_REQUEST:
            error = tsmf_ifman_rim_exchange_capability_request(&ifman);
            break;

        default:
            break;
        }
        break;

    case TSMF_INTERFACE_DEFAULT | STREAM_ID_PROXY:

        switch (FunctionId)
        {
        case SET_CHANNEL_PARAMS:
            memcpy(callback->presentation_id, stream_get_tail(input), 16);
            stream_seek(input, 16);
            stream_read_uint32(input, callback->stream_id);
            DEBUG_DVC("SET_CHANNEL_PARAMS StreamId=%d", callback->stream_id);
            ifman.output_pending = True;
            error = 0;
            break;

        case EXCHANGE_CAPABILITIES_REQ:
            error = tsmf_ifman_exchange_capability_request(&ifman);
            break;

        case CHECK_FORMAT_SUPPORT_REQ:
            error = tsmf_ifman_check_format_support_request(&ifman);
            break;

        case ON_NEW_PRESENTATION:
            error = tsmf_ifman_on_new_presentation(&ifman);
            break;

        case ADD_STREAM:
            error = tsmf_ifman_add_stream(&ifman);
            break;

        case SET_TOPOLOGY_REQ:
            error = tsmf_ifman_set_topology_request(&ifman);
            break;

        case REMOVE_STREAM:
            error = tsmf_ifman_remove_stream(&ifman);
            break;

        case SHUTDOWN_PRESENTATION_REQ:
            error = tsmf_ifman_shutdown_presentation(&ifman);
            break;

        case ON_STREAM_VOLUME:
            error = tsmf_ifman_on_stream_volume(&ifman);
            break;

        case ON_CHANNEL_VOLUME:
            error = tsmf_ifman_on_channel_volume(&ifman);
            break;

        case SET_VIDEO_WINDOW:
            error = tsmf_ifman_set_video_window(&ifman);
            break;

        case UPDATE_GEOMETRY_INFO:
            error = tsmf_ifman_update_geometry_info(&ifman);
            break;

        case SET_ALLOCATOR:
            error = tsmf_ifman_set_allocator(&ifman);
            break;

        case NOTIFY_PREROLL:
            error = tsmf_ifman_notify_preroll(&ifman);
            break;

        case ON_SAMPLE:
            error = tsmf_ifman_on_sample(&ifman);
            break;

        case ON_FLUSH:
            error = tsmf_ifman_on_flush(&ifman);
            break;

        case ON_END_OF_STREAM:
            error = tsmf_ifman_on_end_of_stream(&ifman);
            break;

        case ON_PLAYBACK_STARTED:
            error = tsmf_ifman_on_playback_started(&ifman);
            break;

        case ON_PLAYBACK_PAUSED:
            error = tsmf_ifman_on_playback_paused(&ifman);
            break;

        case ON_PLAYBACK_RESTARTED:
            error = tsmf_ifman_on_playback_restarted(&ifman);
            break;

        case ON_PLAYBACK_STOPPED:
            error = tsmf_ifman_on_playback_stopped(&ifman);
            break;

        case ON_PLAYBACK_RATE_CHANGED:
            error = tsmf_ifman_on_playback_rate_changed(&ifman);
            break;

        default:
            break;
        }
        break;

    default:
        break;
    }

    stream_detach(input);
    stream_free(input);
    input = NULL;
    ifman.input = NULL;

    if (error == -1)
    {
        switch (FunctionId)
        {
        case RIMCALL_RELEASE:
            /* [MS-RDPEXPS] 2.2.2.2 Interface Release (IFACE_RELEASE)
               This message does not require a reply. */
            error = 0;
            ifman.output_pending = 1;
            break;

        case RIMCALL_QUERYINTERFACE:
            /* [MS-RDPEXPS] 2.2.2.1.2 Query Interface Response (QI_RSP)
               This message is not supported in this channel. */
            error = 0;
            break;
        }

        if (error == -1)
        {
            DEBUG_WARN("InterfaceId 0x%X FunctionId 0x%X not processed.",
                       InterfaceId, FunctionId);
            /* When a request is not implemented we return empty response indicating error */
        }
        error = 0;
    }

    if (error == 0 && !ifman.output_pending)
    {
        /* Response packet does not have FunctionId */
        length = stream_get_length(output);
        stream_set_pos(output, 0);
        stream_write_uint32(output, ifman.output_interface_id);
        stream_write_uint32(output, MessageId);

        DEBUG_DVC("response size %d", length);
        error = callback->channel->Write(callback->channel, length, stream_get_head(output), NULL);
        if (error)
        {
            DEBUG_WARN("response error %d", error);
        }
    }

    stream_free(output);

    return error;
}
コード例 #11
0
ファイル: tutorial07.c プロジェクト: proudzhu/ffmpeg-tutorial
int main(int argc, char *argv[]) {

  SDL_Event       event;
  //double          pts;
  VideoState      *is;

  is = av_mallocz(sizeof(VideoState));

  if(argc < 2) {
    fprintf(stderr, "Usage: test <file>\n");
    exit(1);
  }
  // Register all formats and codecs
  av_register_all();
  
  if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
    fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
    exit(1);
  }

  // Make a screen to put our video
#ifndef __DARWIN__
  screen = SDL_SetVideoMode(640, 480, 0, 0);
#else
  screen = SDL_SetVideoMode(640, 480, 24, 0);
#endif
  if(!screen) {
    fprintf(stderr, "SDL: could not set video mode - exiting\n");
    exit(1);
  }

  av_strlcpy(is->filename, argv[1], 1024);

  is->pictq_mutex = SDL_CreateMutex();
  is->pictq_cond = SDL_CreateCond();

  schedule_refresh(is, 40);

  is->av_sync_type = DEFAULT_AV_SYNC_TYPE;
  is->parse_tid = SDL_CreateThread(decode_thread, is);
  if(!is->parse_tid) {
    av_free(is);
    return -1;
  }

  av_init_packet(&flush_pkt);
  flush_pkt.data = (unsigned char *)"FLUSH";
  
  for(;;) {
    double incr, pos;
    SDL_WaitEvent(&event);
    switch(event.type) {
    case SDL_KEYDOWN:
      switch(event.key.keysym.sym) {
      case SDLK_LEFT:
	incr = -10.0;
	goto do_seek;
      case SDLK_RIGHT:
	incr = 10.0;
	goto do_seek;
      case SDLK_UP:
	incr = 60.0;
	goto do_seek;
      case SDLK_DOWN:
	incr = -60.0;
	goto do_seek;
      do_seek:
	if(global_video_state) {
	  pos = get_master_clock(global_video_state);
	  pos += incr;
	  stream_seek(global_video_state, (int64_t)(pos * AV_TIME_BASE), incr);
	}
	break;
      default:
	break;
      }
      break;
    case FF_QUIT_EVENT:
    case SDL_QUIT:
      is->quit = 1;
      /*
       * If the video has finished playing, then both the picture and
       * audio queues are waiting for more data.  Make them stop
       * waiting and terminate normally.
       */
      SDL_CondSignal(is->audioq.cond);
      SDL_CondSignal(is->videoq.cond);
      SDL_Quit();
      exit(0);
      break;
    case FF_ALLOC_EVENT:
      alloc_picture(event.user.data1);
      break;
    case FF_REFRESH_EVENT:
      video_refresh_timer(event.user.data1);
      break;
    default:
      break;
    }
  }
  return 0;
}
コード例 #12
0
ファイル: demux_vqf.c プロジェクト: HermiG/mplayer2
static demuxer_t* demux_open_vqf(demuxer_t* demuxer) {
  sh_audio_t* sh_audio;
  WAVEFORMATEX* w;
  stream_t *s;
  headerInfo *hi;

  s = demuxer->stream;

  sh_audio = new_sh_audio(demuxer,0);
  sh_audio->wf = w = calloc(1, sizeof(*sh_audio->wf)+sizeof(headerInfo));
  hi = (headerInfo *)&w[1];
  w->wFormatTag = 0x1;
  sh_audio->format = mmioFOURCC('T','W','I','N'); /* TWinVQ */
  w->nChannels = sh_audio->channels = 2;
  w->nSamplesPerSec = sh_audio->samplerate = 44100;
  w->nAvgBytesPerSec = w->nSamplesPerSec*sh_audio->channels*2;
  w->nBlockAlign = 0;
  sh_audio->samplesize = 2;
  w->wBitsPerSample = 8*sh_audio->samplesize;
  w->cbSize = 0;
  strcpy(hi->ID,"TWIN");
  stream_read(s,hi->ID+KEYWORD_BYTES,VERSION_BYTES); /* fourcc+version_id */
  while(1)
  {
    char chunk_id[4];
    unsigned chunk_size;
    hi->size=chunk_size=stream_read_dword(s); /* include itself */
    stream_read(s,chunk_id,4);
    if (chunk_size < 8) return NULL;
    chunk_size -= 8;
    if(AV_RL32(chunk_id)==mmioFOURCC('C','O','M','M'))
    {
    char buf[BUFSIZ];
    unsigned i,subchunk_size;
    if (chunk_size > sizeof(buf) || chunk_size < 20) return NULL;
    if(stream_read(s,buf,chunk_size)!=chunk_size) return NULL;
    i=0;
    subchunk_size      = AV_RB32(buf);
    hi->channelMode    = AV_RB32(buf + 4);
    w->nChannels=sh_audio->channels=hi->channelMode+1; /*0-mono;1-stereo*/
    hi->bitRate        = AV_RB32(buf + 8);
    sh_audio->i_bps=hi->bitRate*1000/8; /* bitrate kbit/s */
    w->nAvgBytesPerSec = sh_audio->i_bps;
    hi->samplingRate   = AV_RB32(buf + 12);
    switch(hi->samplingRate){
    case 44:
        w->nSamplesPerSec=44100;
        break;
    case 22:
        w->nSamplesPerSec=22050;
        break;
    case 11:
        w->nSamplesPerSec=11025;
        break;
    default:
        w->nSamplesPerSec=hi->samplingRate*1000;
        break;
    }
    sh_audio->samplerate=w->nSamplesPerSec;
    hi->securityLevel  = AV_RB32(buf + 16);
    w->nBlockAlign = 0;
    sh_audio->samplesize = 4;
    w->wBitsPerSample = 8*sh_audio->samplesize;
    w->cbSize = 0;
    if (subchunk_size > chunk_size - 4) continue;
    i+=subchunk_size+4;
    while(i + 8 < chunk_size)
    {
        unsigned slen,sid;
        char sdata[BUFSIZ];
        sid  = AV_RL32(buf + i); i+=4;
        slen = AV_RB32(buf + i); i+=4;
        if (slen > sizeof(sdata) - 1 || slen > chunk_size - i) break;
        if(sid==mmioFOURCC('D','S','I','Z'))
        {
        hi->Dsiz=AV_RB32(buf + i);
        continue; /* describes the same info as size of DATA chunk */
        }
        memcpy(sdata,&buf[i],slen); sdata[slen]=0; i+=slen;
        if(sid==mmioFOURCC('N','A','M','E'))
        {
        memcpy(hi->Name,sdata,FFMIN(BUFSIZ,slen));
        demux_info_add(demuxer,"Title",sdata);
        }
        else
        if(sid==mmioFOURCC('A','U','T','H'))
        {
        memcpy(hi->Auth,sdata,FFMIN(BUFSIZ,slen));
        demux_info_add(demuxer,"Author",sdata);
        }
        else
        if(sid==mmioFOURCC('C','O','M','T'))
        {
        memcpy(hi->Comt,sdata,FFMIN(BUFSIZ,slen));
        demux_info_add(demuxer,"Comment",sdata);
        }
        else
        if(sid==mmioFOURCC('(','c',')',' '))
        {
        memcpy(hi->Cpyr,sdata,FFMIN(BUFSIZ,slen));
        demux_info_add(demuxer,"Copyright",sdata);
        }
        else
        if(sid==mmioFOURCC('F','I','L','E'))
        {
        memcpy(hi->File,sdata,FFMIN(BUFSIZ,slen));
        }
        else
        if(sid==mmioFOURCC('A','L','B','M')) demux_info_add(demuxer,"Album",sdata);
        else
        if(sid==mmioFOURCC('Y','E','A','R')) demux_info_add(demuxer,"Date",sdata);
        else
        if(sid==mmioFOURCC('T','R','A','C')) demux_info_add(demuxer,"Track",sdata);
        else
        if(sid==mmioFOURCC('E','N','C','D')) demux_info_add(demuxer,"Encoder",sdata);
        else
        mp_msg(MSGT_DEMUX, MSGL_V, "Unhandled subchunk '%c%c%c%c'='%s'\n",((char *)&sid)[0],((char *)&sid)[1],((char *)&sid)[2],((char *)&sid)[3],sdata);
        /* rest not recognized due to untranslatable Japanese expressions */
    }
    }
    else
    if(AV_RL32(chunk_id)==mmioFOURCC('D','A','T','A'))
    {
    demuxer->movi_start=stream_tell(s);
    demuxer->movi_end=demuxer->movi_start+chunk_size;
    mp_msg(MSGT_DEMUX, MSGL_V, "Found data at %"PRIX64" size %"PRIu64"\n",demuxer->movi_start,demuxer->movi_end);
    /* Done! play it */
    break;
    }
    else
    {
    mp_msg(MSGT_DEMUX, MSGL_V, "Unhandled chunk '%c%c%c%c' %u bytes\n",chunk_id[0],chunk_id[1],chunk_id[2],chunk_id[3],chunk_size);
    stream_skip(s,chunk_size); /*unknown chunk type */
    }
  }

  demuxer->audio->id = 0;
  demuxer->audio->sh = sh_audio;
  sh_audio->ds = demuxer->audio;
  stream_seek(s,demuxer->movi_start);
  demuxer->seekable=0;
  return demuxer;
}
コード例 #13
0
ファイル: rdp.c プロジェクト: bradh/FreeRDP-1.0
void rdp_recv(rdpRdp* rdp)
{
	STREAM* s;
	int length;
	uint16 pduType;
	uint16 pduLength;
	uint16 initiator;
	uint16 channelId;
	uint16 sec_flags;
	enum DomainMCSPDU MCSPDU;

	s = transport_recv_stream_init(rdp->transport, 4096);
	transport_read(rdp->transport, s);

	MCSPDU = DomainMCSPDU_SendDataIndication;
	mcs_read_domain_mcspdu_header(s, &MCSPDU, &length);

	per_read_integer16(s, &initiator, MCS_BASE_CHANNEL_ID); /* initiator (UserId) */
	per_read_integer16(s, &channelId, 0); /* channelId */
	stream_seek(s, 1); /* dataPriority + Segmentation (0x70) */
	per_read_length(s, &pduLength); /* userData (OCTET_STRING) */

	if (rdp->licensed != True)
	{
		rdp_read_security_header(s, &sec_flags);

		if (sec_flags & SEC_PKT_MASK)
		{
			switch (sec_flags & SEC_PKT_MASK)
			{
				case SEC_LICENSE_PKT:
					license_recv(rdp->license, s);
					break;

				case SEC_REDIRECTION_PKT:
					rdp_read_redirection_packet(rdp, s);
					break;

				default:
					//printf("incorrect security flags: 0x%04X\n", sec_flags);
					break;
			}
		}
	}
	else
	{
		rdp_read_share_control_header(s, &pduLength, &pduType, &rdp->settings->pdu_source);

		switch (pduType)
		{
			case PDU_TYPE_DATA:
				rdp_read_data_pdu(rdp, s);
				break;

			case PDU_TYPE_DEMAND_ACTIVE:
				rdp_recv_demand_active(rdp, s, rdp->settings);
				break;

			case PDU_TYPE_DEACTIVATE_ALL:
				rdp_recv_deactivate_all(rdp, s);
				break;

			case PDU_TYPE_SERVER_REDIRECTION:
				rdp_read_enhanced_security_redirection_packet(rdp, s);
				break;

			default:
				printf("incorrect PDU type: 0x%04X\n", pduType);
				break;
		}
	}
}
コード例 #14
0
ファイル: rts.c プロジェクト: ArthurGodoy/FreeRDP
void rts_association_group_id_command_read(rdpRpc* rpc, STREAM* s)
{
	stream_seek(s, 16); /* AssociationGroupId (16 bytes) */
}
コード例 #15
0
ファイル: rdpsnd.c プロジェクト: mgariepy/FreeRDP
static BOOL rdpsnd_server_send_audio_pdu(rdpsnd_server* rdpsnd)
{
	int size;
	BOOL r;
	BYTE* src;
	int frames;
	int fill_size;
	rdpsndFormat* format;
	int tbytes_per_frame;
	STREAM* s = rdpsnd->rdpsnd_pdu;

	format = &rdpsnd->context.client_formats[rdpsnd->context.selected_client_format];
	tbytes_per_frame = format->nChannels * rdpsnd->src_bytes_per_sample;

	if ((format->nSamplesPerSec == rdpsnd->context.src_format.nSamplesPerSec) &&
			(format->nChannels == rdpsnd->context.src_format.nChannels))
	{
		src = rdpsnd->out_buffer;
		frames = rdpsnd->out_pending_frames;
	}
	else
	{
		rdpsnd->dsp_context->resample(rdpsnd->dsp_context, rdpsnd->out_buffer, rdpsnd->src_bytes_per_sample,
			rdpsnd->context.src_format.nChannels, rdpsnd->context.src_format.nSamplesPerSec, rdpsnd->out_pending_frames,
			format->nChannels, format->nSamplesPerSec);
		frames = rdpsnd->dsp_context->resampled_frames;
		src = rdpsnd->dsp_context->resampled_buffer;
	}
	size = frames * tbytes_per_frame;

	if (format->wFormatTag == 0x11)
	{
		rdpsnd->dsp_context->encode_ima_adpcm(rdpsnd->dsp_context,
			src, size, format->nChannels, format->nBlockAlign);
		src = rdpsnd->dsp_context->adpcm_buffer;
		size = rdpsnd->dsp_context->adpcm_size;
	}
	else if (format->wFormatTag == 0x02)
	{
		rdpsnd->dsp_context->encode_ms_adpcm(rdpsnd->dsp_context,
			src, size, format->nChannels, format->nBlockAlign);
		src = rdpsnd->dsp_context->adpcm_buffer;
		size = rdpsnd->dsp_context->adpcm_size;
	}

	rdpsnd->context.block_no = (rdpsnd->context.block_no + 1) % 256;

	/* Fill to nBlockAlign for the last audio packet */
	if ((format->wFormatTag == 0x11 || format->wFormatTag == 0x02) &&
		rdpsnd->out_pending_frames < rdpsnd->out_frames && (size % format->nBlockAlign) != 0)
		fill_size = format->nBlockAlign - (size % format->nBlockAlign);
	else
		fill_size = 0;

	/* WaveInfo PDU */
	stream_set_pos(s, 0);
	stream_write_BYTE(s, SNDC_WAVE); /* msgType */
	stream_write_BYTE(s, 0); /* bPad */
	stream_write_UINT16(s, size + fill_size + 8); /* BodySize */

	stream_write_UINT16(s, 0); /* wTimeStamp */
	stream_write_UINT16(s, rdpsnd->context.selected_client_format); /* wFormatNo */
	stream_write_BYTE(s, rdpsnd->context.block_no); /* cBlockNo */
	stream_seek(s, 3); /* bPad */
	stream_write(s, src, 4);

	WTSVirtualChannelWrite(rdpsnd->rdpsnd_channel, stream_get_head(s), stream_get_length(s), NULL);
	stream_set_pos(s, 0);

	/* Wave PDU */
	stream_check_size(s, size + fill_size);
	stream_write_UINT32(s, 0); /* bPad */
	stream_write(s, src + 4, size - 4);

	if (fill_size > 0)
		stream_write_zero(s, fill_size);

	r = WTSVirtualChannelWrite(rdpsnd->rdpsnd_channel, stream_get_head(s), stream_get_length(s), NULL);
	stream_set_pos(s, 0);

	rdpsnd->out_pending_frames = 0;

	return r;
}
コード例 #16
0
ファイル: kerberos.c プロジェクト: mattymo/FreeRDP
void krb_tgsreq_send(KRB_CONTEXT* krb_ctx, uint8 errcode)
{
	KrbTGSREQ* krb_tgsreq;
	KrbAPREQ* krb_apreq;
	PAData** pa_data;
	Authenticator* krb_auth;
	STREAM* s;
	STREAM* sapreq;
	rdpBlob msg;
	uint32 curlen, totlen, tmp;
	uint8 *bm;
	bm = NULL;
	totlen = tmp = 0;
	krb_tgsreq = krb_tgsreq_new(krb_ctx, errcode);
	krb_auth = xnew(Authenticator);
	pa_data = krb_tgsreq->padata;
	s = stream_new(4096);
	sapreq = stream_new(2048);
	
	//Begin write asn1 data reversely into stream
	stream_seek(s, 4095);
	stream_seek(sapreq, 2047);
	
	/* KDC-REQ-BODY (TAG 4) */
	totlen += krb_encode_req_body(s, &(krb_tgsreq->req_body), krb_tgsreq->type);
	stream_get_mark(s, bm);
	tmp = totlen;
	totlen += krb_encode_contextual_tag(s, 4, totlen);

	msg.data = bm;
	msg.length = tmp;

	/* Authenticator */
	krb_auth->avno = KRB_VERSION;
	krb_auth->cname = krb_ctx->cname;
	krb_auth->crealm = krb_ctx->realm;
	krb_auth->cksumtype = get_cksum_type(krb_ctx->enctype);
	krb_auth->cksum = crypto_kdcmsg_cksum(&msg, krb_ctx->askey, 6); //RFC4757 section 3 for msgtype (T=6)
	krb_auth->ctime = krb_tgsreq->req_body.from;
	krb_auth->cusec = 0;
	crypto_nonce((uint8*)&(krb_auth->seqno), 4);

	/* PA-TGS-REQ */
	krb_apreq = krb_apreq_new(krb_ctx, &(krb_ctx->asticket), krb_auth);
	curlen = krb_encode_apreq(sapreq, krb_apreq);
	msg.data = sapreq->p;
	msg.length = curlen;
	(*pa_data)->type = 1;
	(*pa_data)->value = msg;

	/* PA-DATA (TAG 3) */
	curlen = krb_encode_padata(s, pa_data);
	totlen += curlen + krb_encode_contextual_tag(s, 3, curlen);

	/* MSGTYPE (TAG 2) */
	totlen += krb_encode_uint8(s, 2, krb_tgsreq->type);

	/* VERSION NO (TAG 1) */
	totlen += krb_encode_uint8(s, 1, krb_tgsreq->pvno);

	totlen += krb_encode_sequence_tag(s, totlen);
	totlen += krb_encode_application_tag(s, krb_tgsreq->type, totlen);
	totlen += krb_encode_recordmark(s, totlen);

	/* READY SEND */
	krb_tcp_send(krb_ctx, s->p, totlen);
	
	/* save stuff */
	krb_ctx->nonce = krb_tgsreq->req_body.nonce;
	xfree(krb_ctx->sname);
	krb_ctx->sname = xstrdup(krb_tgsreq->req_body.sname);
	krb_ctx->ctime = get_local_time(krb_tgsreq->req_body.from);
	krb_ctx->state = KRB_TGSREQ_OK;

	/* clean up */
	freerdp_blob_free(krb_auth->cksum);
	xfree(krb_auth->cksum);
	xfree(krb_auth);
	krb_free_tgsreq(krb_tgsreq);
	xfree(krb_tgsreq);
	stream_free(sapreq);
	stream_free(s);
}
コード例 #17
0
ファイル: msx_dsk.c プロジェクト: cdenix/psmame
static int msx_dsk_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
	{
	DSK_IMAGE *image=(DSK_IMAGE*)img;
	UINT8	buf[0x1200];
	int 	i, offset, n1, n2, disks = 0;

	/*  check file name */
	switch (image->format)
		{
		case FORMAT_IMG:
		case FORMAT_DDI:
		case FORMAT_MSX:
			if (strcmpi (fname, "msx.dsk") )
				return IMGTOOLERR_MODULENOTFOUND;
			break;
		case FORMAT_MULTI:
			if (strncmpi (fname, "msx-", 4) )
				return IMGTOOLERR_MODULENOTFOUND;
			offset = 4; disks = 0;
			while ( (fname[offset] >= '0') || (fname[offset] <= '9') )
				disks = disks * 10 + (fname[offset++] - '0');

			if (mame_stricmp (fname + offset, ".dsk") )
				return IMGTOOLERR_MODULENOTFOUND;

			if ( (disks < 1) || (disks > image->disks) )
				return IMGTOOLERR_MODULENOTFOUND;

			break;
		}

	/* copy the file */
	switch (image->format)
		{
		case FORMAT_MSX:
			i = 80; n1 = 0; n2 = 80;
			while (i--)
				{
				stream_seek (image->file_handle, n1++ * 0x1200, SEEK_SET);
				if (0x1200 != stream_read (image->file_handle, buf, 0x1200) )
					return IMGTOOLERR_READERROR;

				if (0x1200 != stream_write (destf, buf, 0x1200) )
					return IMGTOOLERR_WRITEERROR;

				stream_seek (image->file_handle, n2++ * 0x1200, SEEK_SET);
				if (0x1200 != stream_read (image->file_handle, buf, 0x1200) )
					return IMGTOOLERR_READERROR;

				if (0x1200 != stream_write (destf, buf, 0x1200) )
					return IMGTOOLERR_WRITEERROR;
				}

			return 0;
		case FORMAT_IMG:
			offset = 1; i = (image->size / 0x1200);
			break;
		case FORMAT_DDI:
			offset = 0x1200; i = 160;
			break;
		case FORMAT_MULTI:	/* multi disk */
			i = 160; offset = 720*1024 * (disks - 1);
			break;
		default:
			return IMGTOOLERR_UNEXPECTED;
		}

	stream_seek (image->file_handle, offset, SEEK_SET);

	while (i--)
		{
		if (0x1200 != stream_read (image->file_handle, buf, 0x1200) )
			return IMGTOOLERR_READERROR;

		if (0x1200 != stream_write (destf, buf, 0x1200) )
			return IMGTOOLERR_WRITEERROR;
		}

	return 0;
	}
コード例 #18
0
static int demux_ty_fill_buffer( demuxer_t *demux, demux_stream_t *dsds )
{
   int              invalidType = 0;
   int              errorHeader = 0;
   int              recordsDecoded = 0;

   int              readSize;

   int              numberRecs;
   unsigned char    *recPtr;
   int              offset;

   int              counter;

   int              aid;

   TiVoInfo         *tivo = demux->priv;
   unsigned char    *chunk = tivo->chunk;

   if ( demux->stream->type == STREAMTYPE_DVD )
      return 0;

   mp_msg( MSGT_DEMUX, MSGL_DBG3, "ty:ty processing\n" );

   if( demux->stream->eof ) return 0;

   // ======================================================================
   // If we haven't figured out the size of the stream, let's do so
   // ======================================================================
   if ( demux->stream->type == STREAMTYPE_VSTREAM )
   {
      // The vstream code figures out the exact size of the stream
      demux->movi_start = 0;
      demux->movi_end = demux->stream->end_pos;
      tivo->size = demux->stream->end_pos;
   }
   else
   {
      // If its a local file, try to find the Part Headers, so we can
      // calculate the ACTUAL stream size
      // If we can't find it, go off with the file size and hope the
      // extract program did the "right thing"
      if ( tivo->readHeader == 0 )
      {
         loff_t filePos;
         tivo->readHeader = 1;

         filePos = demux->filepos;
         stream_seek( demux->stream, 0 );

         readSize = stream_read( demux->stream, chunk, CHUNKSIZE );

         if ( memcmp( chunk, TMF_SIG, sizeof( TMF_SIG ) ) == 0 )
         {
            mp_msg( MSGT_DEMUX, MSGL_DBG3, "ty:Detected a tmf\n" );
            tivo->tmf = 1;
            ty_tmf_filetoparts( demux, tivo );
            readSize = tmf_load_chunk( demux, tivo, chunk, 0 );
         }

         if ( readSize == CHUNKSIZE && AV_RB32(chunk) == TIVO_PES_FILEID )
         {
               loff_t numberParts;

               readSize = 0;

               if ( tivo->tmf != 1 )
               {
                  loff_t offset;

                  numberParts = demux->stream->end_pos / TIVO_PART_LENGTH;
                  offset = numberParts * TIVO_PART_LENGTH;

                  mp_msg( MSGT_DEMUX, MSGL_DBG3, "ty:ty/ty+Number Parts %"PRId64"\n",
                    (int64_t)numberParts );

                  if ( offset + CHUNKSIZE < demux->stream->end_pos )
                  {
                     stream_seek( demux->stream, offset );
                     readSize = stream_read( demux->stream, chunk, CHUNKSIZE );
                  }
               }
               else
               {
                  numberParts = tivo->tmf_totalparts;
                  offset = numberParts * TIVO_PART_LENGTH;
                  readSize = tmf_load_chunk( demux, tivo, chunk,
                     numberParts * ( TIVO_PART_LENGTH - CHUNKSIZE ) /
                     CHUNKSIZE );
               }

               if ( readSize == CHUNKSIZE && AV_RB32(chunk) == TIVO_PES_FILEID )
               {
                     int size = AV_RB24(chunk + 12);
                     size -= 4;
                     size *= CHUNKSIZE;
                     tivo->size = numberParts * TIVO_PART_LENGTH;
                     tivo->size += size;
                     mp_msg( MSGT_DEMUX, MSGL_DBG3,
                        "ty:Header Calc Stream Size %"PRId64"\n", tivo->size );
               }
         }

         if ( demux->stream->start_pos > 0 )
            filePos = demux->stream->start_pos;
         stream_seek( demux->stream, filePos );
         demux->filepos = stream_tell( demux->stream );
         tivo->whichChunk = filePos / CHUNKSIZE;
      }
      demux->movi_start = 0;
      demux->movi_end = tivo->size;
   }

   // ======================================================================
   // Give a clue as to where we are in the stream
   // ======================================================================
   mp_msg( MSGT_DEMUX, MSGL_DBG3,
      "ty:ty header size %"PRIx64"\n", (int64_t)tivo->size );
   mp_msg( MSGT_DEMUX, MSGL_DBG3,
      "ty:ty which Chunk %d\n", tivo->whichChunk );
   mp_msg( MSGT_DEMUX, MSGL_DBG3,
      "ty:file end_pos   %"PRIx64"\n", (int64_t)demux->stream->end_pos );
   mp_msg( MSGT_DEMUX, MSGL_DBG3,
      "\nty:wanted current offset %"PRIx64"\n", (int64_t)stream_tell( demux->stream ) );

   if ( tivo->size > 0 && stream_tell( demux->stream ) > tivo->size )
   {
         demux->stream->eof = 1;
         return 0;
   }

   do {
   if ( tivo->tmf != 1 )
   {
      // Make sure we are on a 128k boundary
      if ( demux->filepos % CHUNKSIZE != 0 )
      {
         int whichChunk = demux->filepos / CHUNKSIZE;
         if ( demux->filepos % CHUNKSIZE > CHUNKSIZE / 2 )
            whichChunk++;
         stream_seek( demux->stream, whichChunk * CHUNKSIZE );
      }

      demux->filepos = stream_tell( demux->stream );
      tivo->whichChunk = demux->filepos / CHUNKSIZE;
      readSize = stream_read( demux->stream, chunk, CHUNKSIZE );
      if ( readSize != CHUNKSIZE )
         return 0;
   }
   else
   {
      readSize = tmf_load_chunk( demux, tivo, chunk, tivo->whichChunk );
      if ( readSize != CHUNKSIZE )
         return 0;
      tivo->whichChunk++;
   }
   if (AV_RB32(chunk) == TIVO_PES_FILEID)
      mp_msg( MSGT_DEMUX, MSGL_DBG3, "ty:Skipping PART Header\n" );
   } while (AV_RB32(chunk) == TIVO_PES_FILEID);

   mp_msg( MSGT_DEMUX, MSGL_DBG3,
      "\nty:actual current offset %"PRIx64"\n", stream_tell( demux->stream ) -
      CHUNKSIZE );


   // Let's make a Video Demux Stream for MPlayer
   aid = 0x0;
   if( !demux->v_streams[ aid ] ) new_sh_video( demux, aid );
   if( demux->video->id == -1 ) demux->video->id = aid;
   if( demux->video->id == aid )
   {
      demux_stream_t *ds = demux->video;
      if( !ds->sh ) ds->sh = demux->v_streams[ aid ];
   }

   // ======================================================================
   // Finally, we get to actually parse the chunk
   // ======================================================================
   mp_msg( MSGT_DEMUX, MSGL_DBG3, "ty:ty parsing a chunk\n" );
   numberRecs = chunk[ 0 ];
   recPtr = &chunk[ 4 ];
   offset = numberRecs * 16 + 4;
   for ( counter = 0 ; counter < numberRecs ; counter++ )
   {
      int size = AV_RB24(recPtr) >> 4;
      int type = recPtr[ 3 ];
      int nybbleType = recPtr[ 2 ] & 0x0f;
      recordsDecoded++;

      mp_msg( MSGT_DEMUX, MSGL_DBG3,
         "ty:Record Type %x/%x %d\n", nybbleType, type, size );

      // ================================================================
      // Video Parsing
      // ================================================================
      if ( type == 0xe0 )
      {
         if ( size > 0 && size + offset <= CHUNKSIZE )
         {
            int esOffset1 = demux_ty_FindESHeader( VIDEO_NAL, &chunk[ offset ],
               size);
            if ( esOffset1 != -1 )
               tivo->lastVideoPTS = get_ty_pts(
                  &chunk[ offset + esOffset1 + 9 ] );

            // Do NOT Pass the PES Header onto the MPEG2 Decode
            if( nybbleType != 0x06 )
               demux_ty_CopyToDemuxPacket( demux->video,
                  &chunk[ offset ], size, demux->filepos + offset,
                  tivo->lastVideoPTS );
            offset += size;
         }
         else
            errorHeader++;
      }
      // ================================================================
      // Audio Parsing
      // ================================================================
      else if ( type == 0xc0 )
      {
         if ( size > 0 && size + offset <= CHUNKSIZE )
         {
            if( demux->audio->id == -1 )
            {
               if ( nybbleType == 0x02 )
                  continue;    // DTiVo inconclusive, wait for more
               else if ( nybbleType == 0x09 )
               {
                  mp_msg( MSGT_DEMUX, MSGL_DBG3, "ty:Setting AC-3 Audio\n" );
                  aid = 0x80;  // AC-3
               }
               else
               {
                  mp_msg( MSGT_DEMUX, MSGL_DBG3, "ty:Setting MPEG Audio\n" );
                  aid = 0x0;   // MPEG Audio
               }

               demux->audio->id = aid;
               if( !demux->a_streams[ aid ] ) new_sh_audio( demux, aid, NULL );
               if( demux->audio->id == aid )
               {
                  demux_stream_t *ds = demux->audio;
                  if( !ds->sh ) {
                    sh_audio_t* sh_a;
                    ds->sh = demux->a_streams[ aid ];
                    sh_a = (sh_audio_t*)ds->sh;
                    switch(aid & 0xE0){  // 1110 0000 b  (high 3 bit: type  low 5: id)
                      case 0x00: sh_a->format=0x50;break; // mpeg
                      case 0xA0: sh_a->format=0x10001;break;  // dvd pcm
                      case 0x80: if((aid & 0xF8) == 0x88) sh_a->format=0x2001;//dts
                                  else sh_a->format=0x2000;break; // ac3
                    }
                 }
               }
            }

            aid = demux->audio->id;


            // SA DTiVo Audio Data, no PES
            // ================================================
            if ( nybbleType == 0x02 || nybbleType == 0x04 )
            {
               if ( nybbleType == 0x02 && tivo->tivoType == 2 )
                  demux_ty_AddToAudioBuffer( tivo, &chunk[ offset ], size );
               else
               {

                  mp_msg( MSGT_DEMUX, MSGL_DBG3,
                     "ty:Adding Audio Packet Size %d\n", size );
                  demux_ty_CopyToDemuxPacket( demux->audio,
                     &chunk[ offset ], size, ( demux->filepos + offset ),
                     tivo->lastAudioPTS );
               }
            }

            // 3 - MPEG Audio with PES Header, either SA or DTiVo
            // 9 - DTiVo AC3 Audio Data with PES Header
            // ================================================
            if ( nybbleType == 0x03 || nybbleType == 0x09 )
            {
               int esOffset1, esOffset2;
               if ( nybbleType == 0x03 )
               esOffset1 = demux_ty_FindESHeader( AUDIO_NAL, &chunk[ offset ],
                  size);

               // SA PES Header, No Audio Data
               // ================================================
               if ( nybbleType == 0x03 && esOffset1 == 0 && size == 16 )
               {
                  tivo->tivoType = 1;
                  tivo->lastAudioPTS = get_ty_pts( &chunk[ offset +
                     SERIES2_PTS_OFFSET ] );
               }
               else
               // DTiVo Audio with PES Header
               // ================================================
               {
                  tivo->tivoType = 2;

                  demux_ty_AddToAudioBuffer( tivo, &chunk[ offset ], size );
                  demux_ty_FindESPacket( nybbleType == 9 ? AC3_NAL : AUDIO_NAL,
                     tivo->lastAudio, tivo->lastAudioEnd, &esOffset1,
                     &esOffset2 );

                  if ( esOffset1 != -1 && esOffset2 != -1 )
                  {
                     int packetSize = esOffset2 - esOffset1;
                     int headerSize;
                     int ptsOffset;

                     if ( IsValidAudioPacket( packetSize, &ptsOffset,
                           &headerSize ) )
                     {
                        mp_msg( MSGT_DEMUX, MSGL_DBG3,
                           "ty:Adding DTiVo Audio Packet Size %d\n",
                           packetSize );

                        tivo->lastAudioPTS = get_ty_pts(
                           &tivo->lastAudio[ esOffset1 + ptsOffset ] );

                        if (nybbleType == 9) headerSize = 0;
                        demux_ty_CopyToDemuxPacket
                        (
                           demux->audio,
                           &tivo->lastAudio[ esOffset1 + headerSize ],
                           packetSize - headerSize,
                           demux->filepos + offset,
                           tivo->lastAudioPTS
                        );

                     }

                     // Collapse the Audio Buffer
                     tivo->lastAudioEnd -= esOffset2;
                     memmove( &tivo->lastAudio[ 0 ],
                        &tivo->lastAudio[ esOffset2 ],
                        tivo->lastAudioEnd );
                  }
               }
            }

            offset += size;
         }
         else
            errorHeader++;
      }
      // ================================================================
      // 1 = Closed Caption
      // 2 = Extended Data Services
      // ================================================================
      else if ( type == 0x01 || type == 0x02 )
      {
                        unsigned char lastXDS[ 16 ];
         int b = AV_RB24(recPtr) >> 4;
         b &= 0x7f7f;

         mp_msg( MSGT_DEMUX, MSGL_DBG3, "ty:%s %04x\n", type == 1 ? "CC" : "XDS", b);

         lastXDS[ 0x00 ] = 0x00;
         lastXDS[ 0x01 ] = 0x00;
         lastXDS[ 0x02 ] = 0x01;
         lastXDS[ 0x03 ] = 0xb2;
         lastXDS[ 0x04 ] = 'T';
         lastXDS[ 0x05 ] = 'Y';
         lastXDS[ 0x06 ] = type;
         lastXDS[ 0x07 ] = b >> 8;
         lastXDS[ 0x08 ] = b;
         if ( subcc_enabled )
            demux_ty_CopyToDemuxPacket( demux->video, lastXDS, 0x09,
               demux->filepos + offset, tivo->lastVideoPTS );
      }
      // ================================================================
      // Unknown
      // ================================================================
      else
      {
         if ( size > 0 && size + offset <= CHUNKSIZE )
コード例 #19
0
ファイル: cache.c プロジェクト: Deadsign/mpv
// Runs in the cache thread.
// Returns true if reading was attempted, and the mutex was shortly unlocked.
static bool cache_fill(struct priv *s)
{
    int64_t read = s->read_filepos;
    int len = 0;

    // drop cache contents only if seeking backward or too much fwd.
    // This is also done for on-disk files, since it loses the backseek cache.
    // That in turn can cause major bandwidth increase and performance
    // issues with e.g. mov or badly interleaved files
    if (read < s->min_filepos || read > s->max_filepos + s->seek_limit) {
        MP_VERBOSE(s, "Dropping cache at pos %"PRId64", "
                   "cached range: %"PRId64"-%"PRId64".\n", read,
                   s->min_filepos, s->max_filepos);
        cache_drop_contents(s);
    }

    if (stream_tell(s->stream) != s->max_filepos && s->seekable) {
        MP_VERBOSE(s, "Seeking underlying stream: %"PRId64" -> %"PRId64"\n",
                   stream_tell(s->stream), s->max_filepos);
        stream_seek(s->stream, s->max_filepos);
        if (stream_tell(s->stream) != s->max_filepos)
            goto done;
    }

    // number of buffer bytes which should be preserved in backwards direction
    int64_t back = mp_clipi64(read - s->min_filepos, 0, s->back_size);

    // number of buffer bytes that are valid and can be read
    int64_t newb = FFMAX(s->max_filepos - read, 0);

    // max. number of bytes that can be written (starting from max_filepos)
    int64_t space = s->buffer_size - (newb + back);

    // offset into the buffer that maps to max_filepos
    int pos = s->max_filepos - s->offset;
    if (pos >= s->buffer_size)
        pos -= s->buffer_size; // wrap-around

    if (space < FILL_LIMIT) {
        s->idle = true;
        s->reads++; // don't stuck main thread
        return false;
    }

    // limit to end of buffer (without wrapping)
    if (pos + space >= s->buffer_size)
        space = s->buffer_size - pos;

    // limit read size (or else would block and read the entire buffer in 1 call)
    space = FFMIN(space, s->stream->read_chunk);

    // back+newb+space <= buffer_size
    int64_t back2 = s->buffer_size - (space + newb); // max back size
    if (s->min_filepos < (read - back2))
        s->min_filepos = read - back2;

    // The read call might take a long time and block, so drop the lock.
    pthread_mutex_unlock(&s->mutex);
    len = stream_read_partial(s->stream, &s->buffer[pos], space);
    pthread_mutex_lock(&s->mutex);

    double pts;
    if (stream_control(s->stream, STREAM_CTRL_GET_CURRENT_TIME, &pts) <= 0)
        pts = MP_NOPTS_VALUE;
    for (int64_t b_pos = pos; b_pos < pos + len + BYTE_META_CHUNK_SIZE;
         b_pos += BYTE_META_CHUNK_SIZE)
    {
        s->bm[b_pos / BYTE_META_CHUNK_SIZE] = (struct byte_meta){.stream_pts = pts};
    }

    s->max_filepos += len;
    if (pos + len == s->buffer_size)
        s->offset += s->buffer_size; // wrap...

done:
    s->eof = len <= 0;
    s->idle = s->eof;
    s->reads++;
    if (s->eof)
        MP_VERBOSE(s, "EOF reached.\n");

    pthread_cond_signal(&s->wakeup);

    return true;
}
コード例 #20
0
static demuxer_t* demux_open_roq(demuxer_t* demuxer)
{
  sh_video_t *sh_video = NULL;
  sh_audio_t *sh_audio = NULL;

  roq_data_t *roq_data = malloc(sizeof(roq_data_t));
  int chunk_id;
  int chunk_size;
  int chunk_arg;
  int last_chunk_id = 0;
  int largest_audio_chunk = 0;
  int fps;

  roq_data->total_chunks = 0;
  roq_data->current_chunk = 0;
  roq_data->total_video_chunks = 0;
  roq_data->chunks = NULL;

  // position the stream and start traversing
  stream_seek(demuxer->stream, 6);
  fps = stream_read_word_le(demuxer->stream);
  while (!stream_eof(demuxer->stream))
  {
    chunk_id = stream_read_word_le(demuxer->stream);
    chunk_size = stream_read_dword_le(demuxer->stream);
    chunk_arg = stream_read_word_le(demuxer->stream);

    // this is the only useful header info in the file
    if (chunk_id == RoQ_INFO)
    {
      // there should only be one RoQ_INFO chunk per file
      if (sh_video)
      {
        mp_msg(MSGT_DECVIDEO, MSGL_WARN, "Found more than one RoQ_INFO chunk\n");
        stream_skip(demuxer->stream, 8);
      }
      else
      {
        // this is a good opportunity to create a video stream header
        sh_video = new_sh_video(demuxer, 0);
        // make sure the demuxer knows about the new stream header
        demuxer->video->sh = sh_video;
        // make sure that the video demuxer stream header knows about its
        // parent video demuxer stream
        sh_video->ds = demuxer->video;

        sh_video->disp_w = stream_read_word_le(demuxer->stream);
        sh_video->disp_h = stream_read_word_le(demuxer->stream);
        stream_skip(demuxer->stream, 4);

        // custom fourcc for internal MPlayer use
        sh_video->format = mmioFOURCC('R', 'o', 'Q', 'V');

        // constant frame rate
        sh_video->fps = fps;
        sh_video->frametime = 1 / sh_video->fps;
      }
    }
    else if ((chunk_id == RoQ_SOUND_MONO) ||
      (chunk_id == RoQ_SOUND_STEREO))
    {
      // create the audio stream header if it hasn't been created it
      if (sh_audio == NULL)
      {
        // make the header first
        sh_audio = new_sh_audio(demuxer, 0);
        // make sure the demuxer knows about the new stream header
        demuxer->audio->sh = sh_audio;
        // make sure that the audio demuxer stream header knows about its
        // parent audio demuxer stream
        sh_audio->ds = demuxer->audio;

        // go through the bother of making a WAVEFORMATEX structure
        sh_audio->wf = malloc(sizeof(WAVEFORMATEX));

        // custom fourcc for internal MPlayer use
        sh_audio->format = mmioFOURCC('R', 'o', 'Q', 'A');
        if (chunk_id == RoQ_SOUND_STEREO)
          sh_audio->wf->nChannels = 2;
        else
          sh_audio->wf->nChannels = 1;
        // always 22KHz, 16-bit
        sh_audio->wf->nSamplesPerSec = 22050;
        sh_audio->wf->wBitsPerSample = 16;
      }

      // index the chunk
      roq_data->chunks = (roq_chunk_t *)realloc(roq_data->chunks,
        (roq_data->total_chunks + 1) * sizeof (roq_chunk_t));
      roq_data->chunks[roq_data->total_chunks].chunk_type = CHUNK_TYPE_AUDIO;
      roq_data->chunks[roq_data->total_chunks].chunk_offset = 
        stream_tell(demuxer->stream) - 8;
      roq_data->chunks[roq_data->total_chunks].chunk_size = chunk_size + 8;
      roq_data->chunks[roq_data->total_chunks].running_audio_sample_count =
        roq_data->total_audio_sample_count;

      // audio housekeeping
      if (chunk_size > largest_audio_chunk)
        largest_audio_chunk = chunk_size;
      roq_data->total_audio_sample_count += 
        (chunk_size / sh_audio->wf->nChannels);

      stream_skip(demuxer->stream, chunk_size);
      roq_data->total_chunks++;
    }
    else if ((chunk_id == RoQ_QUAD_CODEBOOK) ||
      ((chunk_id == RoQ_QUAD_VQ) && (last_chunk_id != RoQ_QUAD_CODEBOOK)))
    {
      // index a new chunk if it's a codebook or quad VQ not following a
      // codebook
      roq_data->chunks = (roq_chunk_t *)realloc(roq_data->chunks,
        (roq_data->total_chunks + 1) * sizeof (roq_chunk_t));
      roq_data->chunks[roq_data->total_chunks].chunk_type = CHUNK_TYPE_VIDEO;
      roq_data->chunks[roq_data->total_chunks].chunk_offset = 
        stream_tell(demuxer->stream) - 8;
      roq_data->chunks[roq_data->total_chunks].chunk_size = chunk_size + 8;
      roq_data->chunks[roq_data->total_chunks].video_chunk_number = 
        roq_data->total_video_chunks++;

      stream_skip(demuxer->stream, chunk_size);
      roq_data->total_chunks++;
    }
    else if ((chunk_id == RoQ_QUAD_VQ) && (last_chunk_id == RoQ_QUAD_CODEBOOK))
    {
      // if it's a quad VQ chunk following a codebook chunk, extend the last
      // chunk
      roq_data->chunks[roq_data->total_chunks - 1].chunk_size += (chunk_size + 8);
      stream_skip(demuxer->stream, chunk_size);
    }
    else if (!stream_eof(demuxer->stream))
    {
        mp_msg(MSGT_DECVIDEO, MSGL_WARN, "Unknown RoQ chunk ID: %04X\n", chunk_id);
    }

    last_chunk_id = chunk_id;
  }

  // minimum output buffer size = largest audio chunk * 2, since each byte
  // in the DPCM encoding effectively represents 1 16-bit sample
  // (store it in wf->nBlockAlign for the time being since init_audio() will
  // step on it anyway)
  if (sh_audio)
    sh_audio->wf->nBlockAlign = largest_audio_chunk * 2;

  roq_data->current_chunk = 0;

  demuxer->priv = roq_data;

  stream_reset(demuxer->stream);

  return demuxer;
}
コード例 #21
0
ファイル: Test7.cpp プロジェクト: soffio/FFmpegTutorial
int main(int argc, char* argv[]) {
//	SetUnhandledExceptionFilter(callback);
	SDL_Event event;
	VideoState* is = NULL;
	is = (VideoState*) av_mallocz(sizeof(VideoState));

	if (argc < 2) {
		fprintf(stderr, "Usage: test <file>\n");
		exit(1);
	}

	av_register_all();

	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
		fprintf(stderr, "Could't not initialize SDL - %s\n", SDL_GetError());
		exit(1);
	}

	screen = SDL_CreateWindow("Hello World", SDL_WINDOWPOS_CENTERED,
	SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_OPENGL);
	if (!screen) {
		printf("Could not initialize SDL -%s\n", SDL_GetError());
		return -1;
	}
	render = SDL_CreateRenderer(screen, -1, 0);

	screen_mutex = SDL_CreateMutex();

	av_strlcpy(is->filename, argv[1], sizeof(is->filename));

	is->pictq_mutex = SDL_CreateMutex();
	is->pictq_cond = SDL_CreateCond();

	schedule_refresh(is, 40);

	is->av_sync_type = DEFAULT_AV_SYNC_TYPE;
	is->parse_tid = SDL_CreateThread(decode_thread, "decode_thread", is);
	if (!is->parse_tid) {
		av_free(is);
		return -1;
	}

	av_init_packet(&flush_pkt);
	flush_pkt.data = (unsigned char*) "FLUSH";

	for (;;) {
		double incr, pos;
		SDL_WaitEvent(&event);
		switch (event.type) {
		case SDL_KEYDOWN:
			switch (event.key.keysym.sym) {
			case SDLK_LEFT:
				incr = -10.0;
				goto do_seek;
			case SDLK_RIGHT:
				incr = 10.0;
				goto do_seek;
			case SDLK_UP:
				incr = 60.0;
				goto do_seek;
			case SDLK_DOWN:
				incr = -60.0;
				goto do_seek;
				do_seek: if (global_video_state) {
					pos = get_master_clock(global_video_state);
					pos += incr;
					stream_seek(global_video_state,
							(int64_t) (pos * AV_TIME_BASE), incr);
				}
				break;
			default:
				break;
			}
			break;
		case FF_QUIT_EVENT:
		case SDL_QUIT:
			is->quit = 1;
			SDL_Quit();
			return 0;
			break;
		case FF_REFRESH_EVENT:
			video_refresh_timer(event.user.data1);
			break;
		default:
			break;
		}
	}
	return 0;
}
コード例 #22
0
ファイル: stream.c プロジェクト: haifenghuang/foundation_lib
string_t
stream_read_string(stream_t* stream) {
	char buffer[128];
	char* outbuffer = buffer;
	size_t outsize = sizeof(buffer);
	size_t cursize = 0;
	size_t read, i;
	bool binary = stream_is_binary(stream);

	if (!(stream->mode & STREAM_IN))
		return (string_t) { 0, 0 };

	if (stream_is_sequential(stream)) {
		//Single byte reading since we can't seek backwards (and don't want to block on network sockets)
		char c;
		if (!binary) {
			//Consume whitespace
			while (!stream_eos(stream)) {
				read = stream->vtable->read(stream, &c, 1);
				if (!read)
					break;
				if ((c != ' ') && (c != '\n') && (c != '\r') && (c != '\t')) {
					buffer[cursize++] = c;
					break;
				}
			}
		}

		if (cursize > 0) {
			while (!stream_eos(stream)) {
				read = stream->vtable->read(stream, &c, 1);
				if (!read)
					break;
				if (!c)
					break;
				if (!binary && ((c == ' ') || (c == '\n') || (c == '\r') || (c == '\t')))
					break;
				if (cursize + 1 >= outsize) {
					outsize += 512;
					if (outbuffer != buffer) {
						outbuffer = memory_reallocate(outbuffer, outsize, 0, cursize);
					}
					else {
						outbuffer = memory_allocate(0, outsize, 0, MEMORY_PERSISTENT);
						memcpy(outbuffer, buffer, sizeof(buffer));
					}
				}
				outbuffer[cursize++] = c;
			}

			outbuffer[cursize] = 0; //lint !e661
		}
	}
	else {
		if (!binary) {
			//Consume whitespace
			while (!stream_eos(stream)) {
				read = stream->vtable->read(stream, buffer, 16);
				if (!read)
					break;
				for (i = 0; i < read; ++i) {
					char c = buffer[i];
					if ((c != ' ') && (c != '\n') && (c != '\r') && (c != '\t'))
						break;
				}
				if (i < read) {
					stream_seek(stream, (ssize_t)i - (ssize_t)read, STREAM_SEEK_CURRENT);
					break;
				}
			}
		}

		while (!stream_eos(stream)) {
			if (outbuffer != buffer)
				read = stream->vtable->read(stream, buffer, sizeof(buffer));
			else
				read = stream->vtable->read(stream, buffer + cursize, sizeof(buffer) - cursize);
			if (!read)
				break;
			for (i = 0; i < read; ++i) {
				char c = buffer[i];
				if (!c)
					break;
				if (!binary && ((c == ' ') || (c == '\n') || (c == '\r') || (c == '\t')))
					break;
			}
			if (i) {
				if (cursize + i >= outsize) {
					outsize += 512;
					if (outbuffer != buffer) {
						outbuffer = memory_reallocate(outbuffer, outsize, 0, cursize);
					}
					else {
						FOUNDATION_ASSERT(cursize == 0);   //Or internal assumptions about code flow is incorrect
						outbuffer = memory_allocate(0, outsize, 0, MEMORY_PERSISTENT);
						memcpy(outbuffer, buffer, i);
					}
				}
				else if (outbuffer != buffer)
					memcpy(outbuffer + cursize, buffer, i);
				cursize += i;
			}
			if (i < sizeof(buffer)) {
				if ((i + 1) < read)
					stream_seek(stream, (ssize_t)(1 + i) - (ssize_t)read, STREAM_SEEK_CURRENT);
				break;
			}
		}

		outbuffer[cursize] = 0;
	}

	if (outbuffer == buffer) {
		if (cursize == 0)
			return (string_t) { 0, 0 };
		outbuffer = memory_allocate(0, cursize + 1, 0, MEMORY_PERSISTENT);
		memcpy(outbuffer, buffer, cursize);
		outbuffer[cursize] = 0;
	}

	return (string_t) { outbuffer, cursize };
}
コード例 #23
0
ファイル: rdp.c プロジェクト: gcracker/FreeRDP
void rdp_read_security_header(STREAM* s, uint16* flags)
{
	/* Basic Security Header */
	stream_read_uint16(s, *flags); /* flags */
	stream_seek(s, 2); /* flagsHi (unused) */
}
コード例 #24
0
ファイル: stream.c プロジェクト: haifenghuang/foundation_lib
string_t
stream_read_string_buffer(stream_t* stream, char* outbuffer, size_t size) {
	char buffer[128];
	size_t cursize = 0;
	size_t read, i;
	bool binary = stream_is_binary(stream);

	if (!(stream->mode & STREAM_IN) || !outbuffer || !size) {
		if (outbuffer && size)
			outbuffer[0] = 0;
		return (string_t) { outbuffer, 0 };
	}

	--size;

	if (stream_is_sequential(stream)) {
		//Single byte reading since we can't seek backwards (and don't want to block on network sockets)
		char c;
		if (!binary) {
			//Consume whitespace
			while (!stream_eos(stream)) {
				read = stream->vtable->read(stream, &c, 1);
				if (!read)
					break;
				if ((c != ' ') && (c != '\n') && (c != '\r') && (c != '\t')) {
					outbuffer[cursize++] = c;
					break;
				}
			}
		}

		if (cursize > 0) {
			while (!stream_eos(stream) && (cursize < size)) {
				read = stream->vtable->read(stream, &c, 1);
				if (!read)
					break;
				if (!c)
					break;
				if (!binary && ((c == ' ') || (c == '\n') || (c == '\r') || (c == '\t')))
					break;
				outbuffer[cursize++] = c;
			}
		}
	}
	else {
		if (!binary) {
			//Consume whitespace
			while (!stream_eos(stream)) {
				read = stream->vtable->read(stream, buffer, 16);
				if (!read)
					break;
				for (i = 0; i < read; ++i) {
					char c = buffer[i];
					if ((c != ' ') && (c != '\n') && (c != '\r') && (c != '\t'))
						break;
				}
				if (i < read) {
					stream_seek(stream, (ssize_t)i - (ssize_t)read, STREAM_SEEK_CURRENT);
					break;
				}
			}
		}

		while (!stream_eos(stream) && (cursize < size)) {
			read = stream->vtable->read(stream, buffer, 128);
			if (!read)
				break;
			for (i = 0; i < read; ++i) {
				char c = buffer[i];
				if (!c)
					break;
				if (!binary && ((c == ' ') || (c == '\n') || (c == '\r') || (c == '\t')))
					break;
			}
			if (!i)
				break;
			if (cursize + i > size)
				i = size - cursize;
			memcpy(outbuffer + cursize, buffer, i);
			cursize += i;
			if (i < 128) {
				if ((i + 1) < read)
					stream_seek(stream, (ssize_t)(1 + i) - (ssize_t)read, STREAM_SEEK_CURRENT);
				break;
			}
		}
	}

	if (cursize < size)
		outbuffer[cursize] = 0;

	return (string_t) {outbuffer, cursize};
}
コード例 #25
0
void read_avi_header(demuxer_t *demuxer,int index_mode){
sh_audio_t *sh_audio=NULL;
sh_video_t *sh_video=NULL;
int stream_id=-1;
int idxfix_videostream=0;
int idxfix_divx=0;
avi_priv_t* priv=demuxer->priv;
off_t list_end=0;

//---- AVI header:
priv->idx_size=0;
priv->audio_streams=0;
while(1){
  int id=stream_read_dword_le(demuxer->stream);
  unsigned chunksize,size2;
  static int last_fccType=0;
  static int last_fccHandler=0;
  char* hdr=NULL;
  //
  if(stream_eof(demuxer->stream)) break;
  // Imply -forceidx if -saveidx is specified
  if (index_file_save)
    index_mode = 2;
  //
  if(id==mmioFOURCC('L','I','S','T')){
    unsigned len=stream_read_dword_le(demuxer->stream);   // list size
    id=stream_read_dword_le(demuxer->stream);             // list type
    mp_msg(MSGT_HEADER,MSGL_DBG2,"LIST %.4s  len=%u\n",(char *) &id,len);
    if(len >= 4) {
	len -= 4;
	list_end=stream_tell(demuxer->stream)+((len+1)&(~1));
    } else {
	mp_msg(MSGT_HEADER,MSGL_WARN,MSGTR_MPDEMUX_AVIHDR_EmptyList);
	list_end = 0;
    }
    mp_msg(MSGT_HEADER,MSGL_V,"list_end=0x%X\n",(int)list_end);
    if(id==listtypeAVIMOVIE){
      // found MOVI header
      if(!demuxer->movi_start) demuxer->movi_start=stream_tell(demuxer->stream);
      demuxer->movi_end=stream_tell(demuxer->stream)+len;
      mp_msg(MSGT_HEADER,MSGL_V,MSGTR_MPDEMUX_AVIHDR_FoundMovieAt,(int)demuxer->movi_start,(int)demuxer->movi_end);
      if(demuxer->stream->end_pos>demuxer->movi_end) demuxer->movi_end=demuxer->stream->end_pos;
      if(index_mode==-2 || index_mode==2 || index_mode==0)
        break; // reading from non-seekable source (stdin) or forced index or no index forced
      if(list_end>0) stream_seek(demuxer->stream,list_end); // skip movi
      list_end=0;
    }
    continue;
  }
  size2=stream_read_dword_le(demuxer->stream);
  mp_msg(MSGT_HEADER,MSGL_DBG2,"CHUNK %.4s  len=%u\n",(char *) &id,size2);
  chunksize=(size2+1)&(~1);
  switch(id){

    // Indicates where the subject of the file is archived
    case mmioFOURCC('I','A','R','L'): hdr="Archival Location";break;
    // Lists the artist of the original subject of the file;
    // for example, "Michaelangelo."
    case mmioFOURCC('I','A','R','T'): hdr="Artist";break;
    // Lists the name of the person or organization that commissioned
    // the subject of the file; for example "Pope Julian II."
    case mmioFOURCC('I','C','M','S'): hdr="Commissioned";break;
    // Provides general comments about the file or the subject
    // of the file. If the comment is several sentences long, end each
    // sentence with a period. Do not include new-line characters.
    case mmioFOURCC('I','C','M','T'): hdr="Comments";break;
    // Records the copyright information for the file; for example,
    // "Copyright Encyclopedia International 1991." If there are multiple
    // copyrights, separate them by semicolon followed by a space.
    case mmioFOURCC('I','C','O','P'): hdr="Copyright";break;
    // Describes whether an image has been cropped and, if so, how it
    // was cropped; for example, "lower-right corner."
    case mmioFOURCC('I','C','R','D'): hdr="Creation Date";break;
    // Describes whether an image has been cropped and, if so, how it
    // was cropped; for example, "lower-right corner."
    case mmioFOURCC('I','C','R','P'): hdr="Cropped";break;
    // Specifies the size of the original subject of the file; for
    // example, "8.5 in h, 11 in w."
    case mmioFOURCC('I','D','I','M'): hdr="Dimensions";break;
    // Stores dots per inch setting of the digitizer used to
    // produce the file, such as "300."
    case mmioFOURCC('I','D','P','I'): hdr="Dots Per Inch";break;
    // Stores the of the engineer who worked on the file. If there are
    // multiple engineers, separate the names by a semicolon and a blank;
    // for example, "Smith, John; Adams, Joe."
    case mmioFOURCC('I','E','N','G'): hdr="Engineer";break;
    // Describes the original work, such as "landscape,", "portrait,"
    // "still liefe," etc.
    case mmioFOURCC('I','G','N','R'): hdr="Genre";break;
    // Provides a list of keywords that refer to the file or subject of the
    // file. Separate multiple keywords with a semicolon and a blank;
    // for example, "Seattle, aerial view; scenery."
    case mmioFOURCC('I','K','E','Y'): hdr="Keywords";break;
    // ILGT - Describes the changes in the lightness settings on the digitizer
    // required to produce the file. Note that the format of this information
    // depends on the hardware used.
    case mmioFOURCC('I','L','G','T'): hdr="Lightness";break;
    // IMED - Decribes the original subject of the file, such as
    // "computer image," "drawing," "lithograph," and so on.
    case mmioFOURCC('I','M','E','D'): hdr="Medium";break;
    // INAM - Stores the title of the subject of the file, such as
    // "Seattle from Above."
    case mmioFOURCC('I','N','A','M'): hdr="Title";break;
    // IPLT - Specifies the number of colors requested when digitizing
    // an image, such as "256."
    case mmioFOURCC('I','P','L','T'): hdr="Palette Setting";break;
    // IPRD - Specifies the name of title the file was originally intended
    // for, such as "Encyclopedia of Pacific Northwest Geography."
    case mmioFOURCC('I','P','R','D'): hdr="Product";break;
    // ISBJ - Decsribes the contents of the file, such as
    // "Aerial view of Seattle."
    case mmioFOURCC('I','S','B','J'): hdr="Subject";break;
    // ISFT - Identifies the name of the software packages used to create the
    // file, such as "Microsoft WaveEdit"
    case mmioFOURCC('I','S','F','T'): hdr="Software";break;
    // ISHP - Identifies the change in sharpness for the digitizer
    // required to produce the file (the format depends on the hardware used).
    case mmioFOURCC('I','S','H','P'): hdr="Sharpness";break;
    // ISRC - Identifies the name of the person or organization who
    // suplied the original subject of the file; for example, "Try Research."
    case mmioFOURCC('I','S','R','C'): hdr="Source";break;
    // ISRF - Identifies the original form of the material that was digitized,
    // such as "slide," "paper," "map," and so on. This is not necessarily
    // the same as IMED
    case mmioFOURCC('I','S','R','F'): hdr="Source Form";break;
    // ITCH - Identifies the technician who digitized the subject file;
    // for example, "Smith, John."
    case mmioFOURCC('I','T','C','H'): hdr="Technician";break;
    case mmioFOURCC('I','S','M','P'): hdr="Time Code";break;
    case mmioFOURCC('I','D','I','T'): hdr="Digitization Time";break;

    case ckidAVIMAINHDR:          // read 'avih'
      stream_read(demuxer->stream,(char*) &avih,FFMIN(size2,sizeof(avih)));
      le2me_MainAVIHeader(&avih); // swap to machine endian
      chunksize-=FFMIN(size2,sizeof(avih));
      if( mp_msg_test(MSGT_HEADER,MSGL_V) ) print_avih(&avih,MSGL_V); // else print_avih_flags(&avih,MSGL_V);
      break;
    case ckidSTREAMHEADER: {      // read 'strh'
      AVIStreamHeader h;
      stream_read(demuxer->stream,(char*) &h,FFMIN(size2,sizeof(h)));
      le2me_AVIStreamHeader(&h);  // swap to machine endian
      chunksize-=FFMIN(size2,sizeof(h));
      ++stream_id;
      if(h.fccType==streamtypeVIDEO){
        sh_video=new_sh_video(demuxer,stream_id);
        mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_VideoID, "aviheader", stream_id);
        memcpy(&sh_video->video,&h,sizeof(h));
        sh_video->stream_delay = (float)sh_video->video.dwStart * sh_video->video.dwScale/sh_video->video.dwRate;
      } else
      if(h.fccType==streamtypeAUDIO){
        sh_audio=new_sh_audio(demuxer,stream_id);
        mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_AudioID, "aviheader", stream_id);
        memcpy(&sh_audio->audio,&h,sizeof(h));
        sh_audio->stream_delay = (float)sh_audio->audio.dwStart * sh_audio->audio.dwScale/sh_audio->audio.dwRate;
      }
      last_fccType=h.fccType;
      last_fccHandler=h.fccHandler;
      if( mp_msg_test(MSGT_HEADER,MSGL_V) ) print_strh(&h,MSGL_V);
      break; }
    case mmioFOURCC('i', 'n', 'd', 'x'): {
      uint32_t i;
      avisuperindex_chunk *s;

      if(!index_mode) break;

      if(chunksize<=24){
        break;
      }
      priv->suidx_size++;
      priv->suidx = realloc_struct(priv->suidx, priv->suidx_size, sizeof (avisuperindex_chunk));
      s = &priv->suidx[priv->suidx_size-1];

      chunksize-=24;
      memcpy(s->fcc, "indx", 4);
      s->dwSize = size2;
      s->wLongsPerEntry = stream_read_word_le(demuxer->stream);
      s->bIndexSubType = stream_read_char(demuxer->stream);
      s->bIndexType = stream_read_char(demuxer->stream);
      s->nEntriesInUse = stream_read_dword_le(demuxer->stream);
      *(uint32_t *)s->dwChunkId = stream_read_dword_le(demuxer->stream);
      stream_read(demuxer->stream, (char *)s->dwReserved, 3*4);
      memset(s->dwReserved, 0, 3*4);

      print_avisuperindex_chunk(s,MSGL_V);

      // Check and fix this useless crap
      if(s->wLongsPerEntry != sizeof (avisuperindex_entry)/4) {
          mp_msg (MSGT_HEADER, MSGL_WARN, "Broken super index chunk size: %u\n",s->wLongsPerEntry);
          s->wLongsPerEntry = sizeof(avisuperindex_entry)/4;
      }
      if( ((chunksize/4)/s->wLongsPerEntry) < s->nEntriesInUse){
        mp_msg (MSGT_HEADER, MSGL_WARN, "Broken super index chunk\n");
        s->nEntriesInUse = (chunksize/4)/s->wLongsPerEntry;
      }

      s->aIndex = calloc(s->nEntriesInUse, sizeof (avisuperindex_entry));
      s->stdidx = calloc(s->nEntriesInUse, sizeof (avistdindex_chunk));

      // now the real index of indices
      for (i=0; i<s->nEntriesInUse; i++) {
	  chunksize-=16;
	  s->aIndex[i].qwOffset = stream_read_qword_le(demuxer->stream);
	  s->aIndex[i].dwSize = stream_read_dword_le(demuxer->stream);
	  s->aIndex[i].dwDuration = stream_read_dword_le(demuxer->stream);
	  mp_msg (MSGT_HEADER, MSGL_V, "ODML (%.4s): [%d] 0x%016"PRIx64" 0x%04x %u\n",
		  (s->dwChunkId), i,
		  (uint64_t)s->aIndex[i].qwOffset, s->aIndex[i].dwSize, s->aIndex[i].dwDuration);
      }

      break; }
    case ckidSTREAMFORMAT: {      // read 'strf'
      if(last_fccType==streamtypeVIDEO){
        sh_video->bih=calloc(FFMAX(chunksize, sizeof(BITMAPINFOHEADER)), 1);
//        sh_video->bih=malloc(chunksize); memset(sh_video->bih,0,chunksize);
        mp_msg(MSGT_HEADER,MSGL_V,MSGTR_MPDEMUX_AVIHDR_FoundBitmapInfoHeader,chunksize,sizeof(BITMAPINFOHEADER));
        stream_read(demuxer->stream,(char*) sh_video->bih,chunksize);
	le2me_BITMAPINFOHEADER(sh_video->bih);  // swap to machine endian
	if (sh_video->bih->biSize > chunksize && sh_video->bih->biSize > sizeof(BITMAPINFOHEADER))
		sh_video->bih->biSize = chunksize;
	// fixup MS-RLE header (seems to be broken for <256 color files)
	if(sh_video->bih->biCompression<=1 && sh_video->bih->biSize==40)
	    sh_video->bih->biSize=chunksize;
        if( mp_msg_test(MSGT_HEADER,MSGL_V) ) print_video_header(sh_video->bih,MSGL_V);
        chunksize=0;
        sh_video->fps=(float)sh_video->video.dwRate/(float)sh_video->video.dwScale;
        sh_video->frametime=(float)sh_video->video.dwScale/(float)sh_video->video.dwRate;
        sh_video->format = sh_video->bih->biCompression;
//        if(demuxer->video->id==-1) demuxer->video->id=stream_id;
        // IdxFix:
        idxfix_videostream=stream_id;
        switch(sh_video->bih->biCompression){
	case mmioFOURCC('M', 'P', 'G', '4'):
	case mmioFOURCC('m', 'p', 'g', '4'):
	case mmioFOURCC('D', 'I', 'V', '1'):
          idxfix_divx=3; // set index recovery mpeg4 flavour: msmpeg4v1
	  mp_msg(MSGT_HEADER,MSGL_V,MSGTR_MPDEMUX_AVIHDR_RegeneratingKeyfTableForMPG4V1);
	  break;
        case mmioFOURCC('D', 'I', 'V', '3'):
	case mmioFOURCC('d', 'i', 'v', '3'):
	case mmioFOURCC('D', 'I', 'V', '4'):
        case mmioFOURCC('d', 'i', 'v', '4'):
	case mmioFOURCC('D', 'I', 'V', '5'):
	case mmioFOURCC('d', 'i', 'v', '5'):
	case mmioFOURCC('D', 'I', 'V', '6'):
        case mmioFOURCC('d', 'i', 'v', '6'):
	case mmioFOURCC('M', 'P', '4', '3'):
	case mmioFOURCC('m', 'p', '4', '3'):
	case mmioFOURCC('M', 'P', '4', '2'):
	case mmioFOURCC('m', 'p', '4', '2'):
	case mmioFOURCC('D', 'I', 'V', '2'):
        case mmioFOURCC('A', 'P', '4', '1'):
          idxfix_divx=1; // set index recovery mpeg4 flavour: msmpeg4v3
	  mp_msg(MSGT_HEADER,MSGL_V,MSGTR_MPDEMUX_AVIHDR_RegeneratingKeyfTableForDIVX3);
	  break;
        case mmioFOURCC('D', 'I', 'V', 'X'):
        case mmioFOURCC('d', 'i', 'v', 'x'):
        case mmioFOURCC('D', 'X', '5', '0'):
        case mmioFOURCC('X', 'V', 'I', 'D'):
        case mmioFOURCC('x', 'v', 'i', 'd'):
        case mmioFOURCC('F', 'M', 'P', '4'):
        case mmioFOURCC('f', 'm', 'p', '4'):
          idxfix_divx=2; // set index recovery mpeg4 flavour: generic mpeg4
	  mp_msg(MSGT_HEADER,MSGL_V,MSGTR_MPDEMUX_AVIHDR_RegeneratingKeyfTableForMPEG4);
	  break;
        }
      } else
      if(last_fccType==streamtypeAUDIO){
	unsigned wf_size = chunksize<sizeof(WAVEFORMATEX)?sizeof(WAVEFORMATEX):chunksize;
        sh_audio->wf=calloc(wf_size,1);
//        sh_audio->wf=malloc(chunksize); memset(sh_audio->wf,0,chunksize);
        mp_msg(MSGT_HEADER,MSGL_V,MSGTR_MPDEMUX_AVIHDR_FoundWaveFmt,chunksize,sizeof(WAVEFORMATEX));
        stream_read(demuxer->stream,(char*) sh_audio->wf,chunksize);
	le2me_WAVEFORMATEX(sh_audio->wf);
	if (sh_audio->wf->cbSize != 0 &&
	    wf_size < sizeof(WAVEFORMATEX)+sh_audio->wf->cbSize) {
	    sh_audio->wf=realloc(sh_audio->wf, sizeof(WAVEFORMATEX)+sh_audio->wf->cbSize);
	}
	sh_audio->format=sh_audio->wf->wFormatTag;
	if (sh_audio->format == 1 &&
	    last_fccHandler == mmioFOURCC('A', 'x', 'a', 'n'))
	    sh_audio->format = last_fccHandler;
	sh_audio->i_bps=sh_audio->wf->nAvgBytesPerSec;
        chunksize=0;
        if( mp_msg_test(MSGT_HEADER,MSGL_V) ) print_wave_header(sh_audio->wf,MSGL_V);
	++priv->audio_streams;
//        if(demuxer->audio->id==-1) demuxer->audio->id=stream_id;
      }
      break;
    }
    case mmioFOURCC('v', 'p', 'r', 'p'): {
	VideoPropHeader *vprp = malloc(chunksize);
	unsigned int i;
	stream_read(demuxer->stream, (void*)vprp, chunksize);
	le2me_VideoPropHeader(vprp);
	chunksize -= sizeof(*vprp)-sizeof(vprp->FieldInfo);
	chunksize /= sizeof(VIDEO_FIELD_DESC);
	if (vprp->nbFieldPerFrame > chunksize) {
	    vprp->nbFieldPerFrame = chunksize;
	}
	chunksize = 0;
	for (i=0; i<vprp->nbFieldPerFrame; i++) {
		le2me_VIDEO_FIELD_DESC(&vprp->FieldInfo[i]);
	}
	if (sh_video) {
		sh_video->aspect = GET_AVI_ASPECT(vprp->dwFrameAspectRatio);
	}
	if( mp_msg_test(MSGT_HEADER,MSGL_V) ) print_vprp(vprp,MSGL_V);
	free(vprp);
	break;
    }
    case mmioFOURCC('d', 'm', 'l', 'h'): {
	// dmlh 00 00 00 04 frms
	unsigned int total_frames = stream_read_dword_le(demuxer->stream);
	mp_msg(MSGT_HEADER,MSGL_V,MSGTR_MPDEMUX_AVIHDR_FoundAVIV2Header, chunksize, total_frames);
	stream_skip(demuxer->stream, chunksize-4);
	chunksize = 0;
    }
    break;
    case ckidAVINEWINDEX:
    if(demuxer->movi_end>stream_tell(demuxer->stream))
	demuxer->movi_end=stream_tell(demuxer->stream); // fixup movi-end
    if(index_mode && !priv->isodml){
      int i;
      priv->idx_size=size2>>4;
      mp_msg(MSGT_HEADER,MSGL_V,MSGTR_MPDEMUX_AVIHDR_ReadingIndexBlockChunksForFrames,
        priv->idx_size,avih.dwTotalFrames, (int64_t)stream_tell(demuxer->stream));
      priv->idx=malloc(priv->idx_size<<4);
//      printf("\nindex to %p !!!!! (priv=%p)\n",priv->idx,priv);
      stream_read(demuxer->stream,(char*)priv->idx,priv->idx_size<<4);
      for (i = 0; i < priv->idx_size; i++) {	// swap index to machine endian
	AVIINDEXENTRY *entry=(AVIINDEXENTRY*)priv->idx + i;
	le2me_AVIINDEXENTRY(entry);
	/*
	 * We (ab)use the upper word for bits 32-47 of the offset, so
	 * we'll clear them here.
	 * FIXME: AFAIK no codec uses them, but if one does it will break
	 */
	entry->dwFlags&=0xffff;
      }
      chunksize-=priv->idx_size<<4;
      if( mp_msg_test(MSGT_HEADER,MSGL_DBG2) ) print_index(priv->idx,priv->idx_size,MSGL_DBG2);
    }
    break;
    /* added May 2002 */
    case mmioFOURCC('R','I','F','F'): {
	char riff_type[4];

	mp_msg(MSGT_HEADER, MSGL_V, MSGTR_MPDEMUX_AVIHDR_AdditionalRIFFHdr);
	stream_read(demuxer->stream, riff_type, sizeof riff_type);
	if (strncmp(riff_type, "AVIX", sizeof riff_type))
	    mp_msg(MSGT_HEADER, MSGL_WARN, MSGTR_MPDEMUX_AVIHDR_WarnNotExtendedAVIHdr);
	else {
		/*
		 * We got an extended AVI header, so we need to switch to
		 * ODML to get seeking to work, provided we got indx chunks
		 * in the header (suidx_size > 0).
		 */
		if (priv->suidx_size > 0)
			priv->isodml = 1;
	}
	chunksize = 0;
	list_end = 0; /* a new list will follow */
	break; }
    case ckidAVIPADDING:
	stream_skip(demuxer->stream, chunksize);
	chunksize = 0;
	break;
  }
  if(hdr){
    mp_msg(MSGT_HEADER,MSGL_V,"hdr=%s  size=%u\n",hdr,size2);
    if(size2==3)
      chunksize=1; // empty
    else {
      char buf[256];
      int len=(size2<250)?size2:250;
      stream_read(demuxer->stream,buf,len);
      chunksize-=len;
      buf[len]=0;
      mp_msg(MSGT_HEADER,MSGL_V,"%-10s: %s\n",hdr,buf);
      demux_info_add(demuxer, hdr, buf);
    }
  }
  mp_msg(MSGT_HEADER,MSGL_DBG2,"list_end=0x%"PRIX64"  pos=0x%"PRIX64"  chunksize=0x%"PRIX64"  next=0x%"PRIX64"\n",
      (int64_t)list_end, (int64_t)stream_tell(demuxer->stream),
      (int64_t)chunksize, (int64_t)chunksize+(int64_t)stream_tell(demuxer->stream));
  if(list_end>0 &&
     chunksize+stream_tell(demuxer->stream) == list_end) list_end=0;
  if(list_end>0 && chunksize+stream_tell(demuxer->stream)>list_end){
      mp_msg(MSGT_HEADER,MSGL_V,MSGTR_MPDEMUX_AVIHDR_BrokenChunk,chunksize,(char *) &id);
      stream_seek(demuxer->stream,list_end);
      list_end=0;
  } else
  if(chunksize>0) stream_skip(demuxer->stream,chunksize); else
  if((int)chunksize<0) mp_msg(MSGT_HEADER,MSGL_WARN,"chunksize=%u  (id=%.4s)\n",chunksize,(char *) &id);

}
コード例 #26
0
ファイル: stream.c プロジェクト: haifenghuang/foundation_lib
uint128_t
stream_md5(stream_t* stream) {
	size_t cur, ic, lastc, num, limit;
	md5_t md5;
	uint128_t ret = uint128_null();
	unsigned char buf[1025];
	bool ignore_lf = false;

	if (stream->vtable->md5)
		return stream->vtable->md5(stream);

	if (stream_is_sequential(stream) || !(stream->mode & STREAM_IN))
		return ret;

	cur = stream_tell(stream);
	stream_seek(stream, 0, STREAM_SEEK_BEGIN);

	md5_initialize(&md5);
	limit = sizeof(buf)-1;
	buf[limit] = 0;

	while (!stream_eos(stream)) {
		num = stream->vtable->read(stream, buf, limit);
		if (!num)
			continue;
		if (stream->mode & STREAM_BINARY)
			md5_digest(&md5, buf, (size_t)num);
		else {
			//If last buffer ended with CR, ignore a leading LF
			lastc = 0;
			if (ignore_lf && (buf[0] == '\n'))
				lastc = 1;
			ignore_lf = false;

			//Digest one line at a time
			//Treat all line endings (LF, CR, CR+LF) as Unix style LF. If file has mixed line endings
			//(for example, one line ending in a single CR and next is empty and ending in a single LF),
			//it will not work!
			/*lint -e{850} */
			for (ic = lastc; ic < num && ic < limit; ++ic) {
				bool was_cr = (buf[ic] == '\r');
				bool was_lf = (buf[ic] == '\n');
				if (was_cr || was_lf) {
					if (was_cr && (ic == limit-1))
						ignore_lf = true; //Make next buffer ignore leading LF as it is part of CR+LF
					buf[ic] = '\n';
					md5_digest(&md5, buf + lastc, (size_t)((ic - lastc) + 1)); //Include the LF
					if (was_cr && (buf[ic + 1] == '\n'))  //Check for CR+LF
						++ic;
					lastc = ic + 1;
				}
			}
			if (lastc < num)
				md5_digest(&md5, buf + lastc, (size_t)(num - lastc));
		}
	}

	stream_seek(stream, (ssize_t)cur, STREAM_SEEK_BEGIN);

	md5_digest_finalize(&md5);
	ret = md5_get_digest_raw(&md5);
	md5_finalize(&md5);

	return ret;
}
コード例 #27
0
ファイル: vzdos.c プロジェクト: coinhelper/jsmess
static imgtoolerr_t vzdos_writefile(imgtool_partition *partition, int offset, imgtool_stream *sourcef, vzdos_dirent *entry)
{
	imgtoolerr_t ret;
	imgtool_image *img = imgtool_partition_image(partition);
	int index, track, sector, toread, next_track, next_sector;
	vzdos_dirent temp_entry;
	UINT64 filesize = 0, freespace = 0;
	UINT8 buffer[DATA_SIZE + 2];
	char filename[9];

	/* is the image writeable? */
	if (floppy_is_read_only(imgtool_floppy(img)))
		return IMGTOOLERR_READONLY;

	/* check for already existing filename -> overwrite */
	strcpy(filename, entry->fname);
	filename[vzdos_get_fname_len(entry->fname) + 1] = 0x00;
	ret = vzdos_get_dirent_fname(img, filename, &temp_entry);
	if (!ret) {
		/* file already exists, delete it */
		ret = vzdos_diskimage_deletefile(partition, filename);
		if (ret) return ret;
	} else if (ret != IMGTOOLERR_FILENOTFOUND) {
		/* another error occurred, return it */
		return ret;
	}

	ret = (imgtoolerr_t)stream_seek(sourcef, offset, SEEK_SET);
	if (ret) return ret;

	/* check if there is enough space */
	filesize = stream_size(sourcef) - offset;

	ret = vzdos_diskimage_freespace(partition, &freespace);
	if (ret) return ret;

	if (filesize > freespace)
		return IMGTOOLERR_NOSPACE;

	/* get next free track and sector */
	ret = vzdos_free_trackmap(img, &track, &sector);
	if (ret) return ret;

	entry->end_address = entry->start_address + (unsigned int) filesize;
	entry->start_track   = track;
	entry->start_sector  = sector;

	/* search for next free directory entry */
	for (index = 0; index < MAX_DIRENTS; index++) {
		ret = vzdos_get_dirent(img, index, &temp_entry);
		if (ret == IMGTOOLERR_FILENOTFOUND)
			break;
		else if (ret)
			return (ret);
	}

	/* write directory entry to disk */
	ret = vzdos_set_dirent(img, index, *entry);
	if (ret) return ret;

	next_track  = 0;
	next_sector = 0;

	/* write data to disk */
	while (filesize > 0) {

		toread = filesize > DATA_SIZE ? DATA_SIZE : filesize;
		stream_read(sourcef, buffer, toread);

		filesize -= toread;

		/* mark sector as used */
		ret = vzdos_set_trackmap(img, track, sector);
		if (ret) return ret;

		/* get track and sector for next sector */
		if (filesize > 0) {
			ret = vzdos_free_trackmap(img, &next_track, &next_sector);
			if (ret) return ret;
		} else {
			next_track = 0;
			next_sector = 0;
		}
		buffer[DATA_SIZE]     = next_track;
		buffer[DATA_SIZE + 1] = next_sector;

		/* write sector to disk */
		ret = vzdos_write_sector_data(img, track, sector, buffer);
		if (ret) return ret;

		track  = next_track;
		sector = next_sector;
	}

	return IMGTOOLERR_SUCCESS;

}
コード例 #28
0
ファイル: drive_main.c プロジェクト: KimDongChun/FreeRDP
static void drive_process_irp_create(DRIVE_DEVICE* disk, IRP* irp)
{
	char* path;
	int status;
	UINT32 FileId;
	DRIVE_FILE* file;
	BYTE Information;
	UINT32 DesiredAccess;
	UINT32 CreateDisposition;
	UINT32 CreateOptions;
	UINT32 PathLength;

	stream_read_UINT32(irp->input, DesiredAccess);
	stream_seek(irp->input, 16); /* AllocationSize(8), FileAttributes(4), SharedAccess(4) */
	stream_read_UINT32(irp->input, CreateDisposition);
	stream_read_UINT32(irp->input, CreateOptions);
	stream_read_UINT32(irp->input, PathLength);

	status = ConvertFromUnicode(CP_UTF8, 0, (WCHAR*) stream_get_tail(irp->input),
			PathLength / 2, &path, 0, NULL, NULL);

	if (status < 1)
		path = (char*) calloc(1, 1);

	FileId = irp->devman->id_sequence++;

	file = drive_file_new(disk->path, path, FileId,
		DesiredAccess, CreateDisposition, CreateOptions);

	if (file == NULL)
	{
		irp->IoStatus = STATUS_UNSUCCESSFUL;
		FileId = 0;
		Information = 0;

		DEBUG_WARN("failed to create %s.", path);
	}
	else if (file->err)
	{
		FileId = 0;
		Information = 0;

		/* map errno to windows result */
		irp->IoStatus = drive_map_posix_err(file->err);
		drive_file_free(file);
	}
	else
	{
		list_enqueue(disk->files, file);

		switch (CreateDisposition)
		{
			case FILE_SUPERSEDE:
			case FILE_OPEN:
			case FILE_CREATE:
			case FILE_OVERWRITE:
				Information = FILE_SUPERSEDED;
				break;
			case FILE_OPEN_IF:
				Information = FILE_OPENED;
				break;
			case FILE_OVERWRITE_IF:
				Information = FILE_OVERWRITTEN;
				break;
			default:
				Information = 0;
				break;
		}
		DEBUG_SVC("%s(%d) created.", file->fullpath, file->id);
	}

	stream_write_UINT32(irp->output, FileId);
	stream_write_BYTE(irp->output, Information);

	free(path);

	irp->Complete(irp);
}
コード例 #29
0
ファイル: info.c プロジェクト: zzzhou/FreeRDP
void rdp_recv_logon_plain_notify(rdpRdp* rdp, STREAM* s)
{
	stream_seek(s, 576); /* pad */
}
コード例 #30
0
ファイル: iflopimg.c プロジェクト: Archlogic/libretro-mame
static int imgtool_floppy_seekproc(void *file, INT64 offset, int whence)
{
	stream_seek((imgtool_stream *) file, offset, whence);
	return 0;
}