Example #1
0
void LLTextureCache::writeEntryAndClose(S32 idx, Entry& entry)
{
	if (idx >= 0)
	{
		if (!mReadOnly)
		{
			entry.mTime = time(NULL);
			if(entry.mImageSize < entry.mBodySize)
			{
				// Just say no, due to my messing around to cache discards other than 0 we can end up here
				// after recalling an image from cache at a lower discard than cached. RC
				return;
			}

			llassert_always(entry.mImageSize == 0 || entry.mImageSize == -1 || entry.mImageSize > entry.mBodySize);
			if (entry.mBodySize > 0)
			{
				mTexturesSizeMap[entry.mID] = entry.mBodySize;
			}
// 			llinfos << "Updating TE: " << idx << ": " << id << " Size: " << entry.mBodySize << " Time: " << entry.mTime << llendl;
			S32 offset = sizeof(EntriesInfo) + idx * sizeof(Entry);
			LLAPRFile* aprfile = openHeaderEntriesFile(false, offset);
			S32 bytes_written = aprfile->write((void*)&entry, (S32)sizeof(Entry));
			llassert_always(bytes_written == sizeof(Entry));
			mHeaderEntriesMaxWriteIdx = llmax(mHeaderEntriesMaxWriteIdx, idx);
			closeHeaderEntriesFile();
		}
	}
}
BOOL LLStateDiagram::saveDotFile(const std::string& filename)
{
	LLAPRFile outfile ;
	outfile.open(filename, LL_APR_W);
	
	// <FS:ND> Remove LLVolatileAPRPool/apr_file_t and use FILE* instead
	// apr_file_t* dot_file = outfile.getFileHandle() ;
	LLAPRFile::tFiletype* dot_file = outfile.getFileHandle() ;
	// </FS:ND>

	if (!dot_file)
	{
		LL_WARNS() << "LLStateDiagram::saveDotFile() : Couldn't open " << filename << " to save state diagram." << LL_ENDL;
		return FALSE;
	}
	apr_file_printf(dot_file, "digraph StateMachine {\n\tsize=\"100,100\";\n\tfontsize=40;\n\tlabel=\"Finite State Machine\";\n\torientation=landscape\n\tratio=.77\n");
	
	StateMap::iterator state_it;
	for(state_it = mStates.begin(); state_it != mStates.end(); ++state_it)
	{
		apr_file_printf(dot_file, "\t\"%s\" [fontsize=28,shape=box]\n", state_it->first->getName().c_str());
	}
	apr_file_printf(dot_file, "\t\"All States\" [fontsize=30,style=bold,shape=box]\n");

	Transitions::iterator transitions_it;
	for(transitions_it = mDefaultTransitions.begin(); transitions_it != mDefaultTransitions.end(); ++transitions_it)
	{
		apr_file_printf(dot_file, "\t\"All States\" -> \"%s\" [label = \"%s\",fontsize=24];\n", transitions_it->second->getName().c_str(), 
			transitions_it->second->getName().c_str());
	}

	if (mDefaultState)
	{
		apr_file_printf(dot_file, "\t\"All States\" -> \"%s\";\n", mDefaultState->getName().c_str());
	}

	
	for(state_it = mStates.begin(); state_it != mStates.end(); ++state_it)
	{
		LLFSMState *state = state_it->first;

		Transitions::iterator transitions_it;
		for(transitions_it = state_it->second.begin();
			transitions_it != state_it->second.end();
			++transitions_it)
		{
			std::string state_name = state->getName();
			std::string target_name = transitions_it->second->getName();
			std::string transition_name = transitions_it->first->getName();
			apr_file_printf(dot_file, "\t\"%s\" -> \"%s\" [label = \"%s\",fontsize=24];\n", state->getName().c_str(), 
				target_name.c_str(), 
				transition_name.c_str());
		}
	}

	apr_file_printf(dot_file, "}\n");

	return TRUE;
}
Example #3
0
void LLObjectBackup::uploadNextAsset()
{
	if (mTexturesList.empty())
	{
		llinfos << "Texture list is empty, moving to rez stage." << llendl;
		mCurrentAsset = LLUUID::null;
		importFirstObject();
		return;
	}

	updateImportNumbers();

	std::list<LLUUID>::iterator iter;
	iter = mTexturesList.begin();
	LLUUID id = *iter;
	mTexturesList.pop_front();

	llinfos << "Got texture ID " << id << ": trying to upload" << llendl;

	mCurrentAsset = id;
	std::string struid;
	id.toString(struid);
	std::string filename = mFolder + "//" + struid;
	LLAssetID uuid;
	LLTransactionID tid;

	// generate a new transaction ID for this asset
	tid.generate();
	uuid = tid.makeAssetID(gAgent.getSecureSessionID());

	S32 file_size;
	LLAPRFile outfile;
	outfile.open(filename, LL_APR_RB, LLAPRFile::global, &file_size);
	if (outfile.getFileHandle())
	{
		const S32 buf_size = 65536;	
		U8 copy_buf[buf_size];
		LLVFile file(gVFS, uuid,  LLAssetType::AT_TEXTURE, LLVFile::WRITE);
		file.setMaxSize(file_size);
		while ((file_size = outfile.read(copy_buf, buf_size)))
		{
			file.write(copy_buf, file_size);
		}
		outfile.close();
	}
	else
	{
		llwarns << "Unable to access output file " << filename << llendl;
		uploadNextAsset();
		return;
	}

	 myupload_new_resource(tid, LLAssetType::AT_TEXTURE, struid, struid, 0,
		LLAssetType::AT_TEXTURE, LLInventoryType::defaultForAssetType(LLAssetType::AT_TEXTURE),
		0x0, "Uploaded texture", NULL, NULL);
}
	void completedRaw(
		const LLChannelDescriptors& channels,
		const LLIOPipe::buffer_ptr_t& buffer)
	{
		completedHeader();

		if (!isGoodStatus())
		{
			if (getStatus() == HTTP_NOT_MODIFIED)
			{
				LL_INFOS("fsdata") << "Got [304] not modified for " << mURL << LL_ENDL;
			}
			else
			{
				LL_WARNS("fsdata") << "Error fetching " << mURL << " Status: [" << getStatus() << "]" << LL_ENDL;
			}
			return;
		}

		S32 data_size = buffer->countAfter(channels.in(), NULL);
		if (data_size <= 0)
		{
			LL_WARNS("fsdata") << "Received zero data for " << mURL << LL_ENDL;
			return;
		}

		U8* data = new U8[data_size];
		buffer->readAfter(channels.in(), NULL, data, data_size);

		// basic check for valid data received
		LLXMLNodePtr xml_root;
		if ( (!LLXMLNode::parseBuffer(data, data_size, xml_root, NULL)) || (xml_root.isNull()) || (!xml_root->hasName("script_library")) )
		{
			LL_WARNS("fsdata") << "Could not read the script library data from "<< mURL << LL_ENDL;
			delete[] data;
			data = NULL;
			return;
		}
		
		LLAPRFile outfile ;
		outfile.open(mFilename, LL_APR_WB);
		if (!outfile.getFileHandle())
		{
			LL_WARNS("fsdata") << "Unable to open file for writing: " << mFilename << LL_ENDL;
		}
		else
		{
			LL_INFOS("fsdata") << "Saving " << mFilename << LL_ENDL;
			outfile.write(data, data_size);
			outfile.close() ;
		}
		delete[] data;
		data = NULL;
	}
Example #5
0
static std::string createListenPls( const std::string &url )
{
	LLDir *d = gDirUtilp;
	std::string filename = d->getCacheDir() + d->getDirDelimiter() + "listen.pls";
	LLAPRFile file;

	if(file.open(filename, APR_WRITE | APR_CREATE | APR_TRUNCATE) == APR_SUCCESS) {
		std::string playlist = llformat("[playlist]\nNumberOfEntries=1\nFile1=%s\n", url.c_str());
		file.write(playlist.c_str(), playlist.length());
		return filename;
	}

	return "";
}
Example #6
0
void LLTextureCache::writeEntriesAndClose(const std::vector<Entry>& entries)
{
	S32 num_entries = entries.size();
	llassert_always(num_entries == mHeaderEntriesInfo.mEntries);
	
	if (!mReadOnly)
	{
		LLAPRFile* aprfile = openHeaderEntriesFile(false, (S32)sizeof(EntriesInfo));
		for (S32 idx=0; idx<num_entries; idx++)
		{
			S32 bytes_written = aprfile->write((void*)(&entries[idx]), (S32)sizeof(Entry));
			llassert_always(bytes_written == sizeof(Entry));
		}
		mHeaderEntriesMaxWriteIdx = llmax(mHeaderEntriesMaxWriteIdx, num_entries-1);
		closeHeaderEntriesFile();
	}
}
Example #7
0
U32 LLTextureCache::openAndReadEntries(std::vector<Entry>& entries)
{
	U32 num_entries = mHeaderEntriesInfo.mEntries;

	mHeaderIDMap.clear();
	mTexturesSizeMap.clear();
	mFreeList.clear();
	mTexturesSizeTotal = 0;

	LLAPRFile* aprfile = openHeaderEntriesFile(false, (S32)sizeof(EntriesInfo));
	for (U32 idx=0; idx<num_entries; idx++)
	{
		Entry entry;
		S32 bytes_read = aprfile->read((void*)(&entry), (S32)sizeof(Entry));
		if (bytes_read < sizeof(Entry))
		{
			llwarns << "Corrupted header entries, failed at " << idx << " / " << num_entries << llendl;
			closeHeaderEntriesFile();
			purgeAllTextures(false);
			return 0;
		}
		entries.push_back(entry);
// 		llinfos << "ENTRY: " << entry.mTime << " TEX: " << entry.mID << " IDX: " << idx << " Size: " << entry.mImageSize << llendl;
		if (entry.mImageSize < 0)
		{
			mFreeList.insert(idx);
		}
		else
		{
			mHeaderIDMap[entry.mID] = idx;
			if (entry.mBodySize > 0)
			{
				mTexturesSizeMap[entry.mID] = entry.mBodySize;
				mTexturesSizeTotal += entry.mBodySize;
			}
			llassert_always(entry.mImageSize == 0 || entry.mImageSize > entry.mBodySize);
		}
	}
	closeHeaderEntriesFile();
	return num_entries;
}
void LLPreviewAnim::exportasdotAnim( void *userdata )
{

		LLPreviewAnim* self = (LLPreviewAnim*) userdata;
		
		const LLInventoryItem *item = self->getItem();
		
		//LLVOAvatar* avatar = gAgent.getAvatarObject();
		//LLMotion*   motion = avatar->findMotion(item->getAssetUUID());
		//LLKeyframeMotion* motionp = (LLKeyframeMotion*)motion;
		//if (motionp)
		{
			
			//U32 size = motionp->getFileSize();
			//U8* buffer = new U8[size];
			
			//LLDataPackerBinaryBuffer dp(buffer, size);
			//if(motionp->serialize(dp))
			{
				
				std::string filename = item->getName() + ".animatn";
				LLFilePicker& picker = LLFilePicker::instance();
				if(!picker.getSaveFile( LLFilePicker::FFSAVE_ALL, filename.c_str() ) )
				{
					// User canceled save.
					return;
				}
				std::string name = picker.getFirstFile();
				std::string save_filename(name);
				LLAPRFile infile ;
				infile.open(save_filename.c_str(), LL_APR_WB, LLAPRFile::local);
				apr_file_t *fp = infile.getFileHandle();
				if(fp)infile.write(self->mAnimBuffer, self->mAnimBufferSize);
				
				infile.close();
			}
			//delete[] buffer;
		}
//whole file imported from onyx thomas shikami gets credit for the exporter
}
Example #9
0
void LLTextureCache::writeEntryAndClose(S32 idx, Entry& entry)
{
	if (idx >= 0)
	{
		if (!mReadOnly)
		{
			entry.mTime = time(NULL);
			llassert_always(entry.mImageSize == 0 || entry.mImageSize == -1 || entry.mImageSize > entry.mBodySize);
			if (entry.mBodySize > 0)
			{
				mTexturesSizeMap[entry.mID] = entry.mBodySize;
			}
// 			llinfos << "Updating TE: " << idx << ": " << id << " Size: " << entry.mBodySize << " Time: " << entry.mTime << llendl;
			S32 offset = sizeof(EntriesInfo) + idx * sizeof(Entry);
			LLAPRFile* aprfile = openHeaderEntriesFile(false, offset);
			S32 bytes_written = aprfile->write((void*)&entry, (S32)sizeof(Entry));
			llassert_always(bytes_written == sizeof(Entry));
			mHeaderEntriesMaxWriteIdx = llmax(mHeaderEntriesMaxWriteIdx, idx);
			closeHeaderEntriesFile();
		}
	}
}
S32 check_for_invalid_wav_formats(const std::string& in_fname, std::string& error_msg)
{
	U16 num_channels = 0;
	U32 sample_rate = 0;
	U32 bits_per_sample = 0;
	U32 physical_file_size = 0;
	U32 chunk_length = 0;
	U32 raw_data_length = 0;
	U32 bytes_per_sec = 0;
	BOOL uncompressed_pcm = FALSE;

	unsigned char wav_header[44];		/*Flawfinder: ignore*/

	error_msg.clear();

	// ********************************
	LLAPRFile infile ;
	infile.open(in_fname,LL_APR_RB);
	// ********************************
	if (!infile.getFileHandle())
	{
		error_msg = "CannotUploadSoundFile";
		return(LLVORBISENC_SOURCE_OPEN_ERR);
	}

	infile.read(wav_header, 44);
	physical_file_size = infile.seek(APR_END,0);

	if (strncmp((char *)&(wav_header[0]),"RIFF",4))
	{
		error_msg = "SoundFileNotRIFF";
		return(LLVORBISENC_WAV_FORMAT_ERR);
	}

	if (strncmp((char *)&(wav_header[8]),"WAVE",4))
	{
		error_msg = "SoundFileNotRIFF";
		return(LLVORBISENC_WAV_FORMAT_ERR);
	}
	
	// parse the chunks
	
	U32 file_pos = 12;  // start at the first chunk (usually fmt but not always)
	
	while ((file_pos + 8)< physical_file_size)
	{
		infile.seek(APR_SET,file_pos);
		infile.read(wav_header, 44);

		chunk_length = ((U32) wav_header[7] << 24) 
			+ ((U32) wav_header[6] << 16) 
			+ ((U32) wav_header[5] << 8) 
			+ wav_header[4];

		if (chunk_length > physical_file_size - file_pos - 4)
		{
			infile.close();
			error_msg = "SoundFileInvalidChunkSize";
			return(LLVORBISENC_CHUNK_SIZE_ERR);
		}

//		llinfos << "chunk found: '" << wav_header[0] << wav_header[1] << wav_header[2] << wav_header[3] << "'" << llendl;

		if (!(strncmp((char *)&(wav_header[0]),"fmt ",4)))
		{
			if ((wav_header[8] == 0x01) && (wav_header[9] == 0x00))
			{
				uncompressed_pcm = TRUE;
			}
			num_channels = ((U16) wav_header[11] << 8) + wav_header[10];
			sample_rate = ((U32) wav_header[15] << 24) 
				+ ((U32) wav_header[14] << 16) 
				+ ((U32) wav_header[13] << 8) 
				+ wav_header[12];
			bits_per_sample = ((U16) wav_header[23] << 8) + wav_header[22];
			bytes_per_sec = ((U32) wav_header[19] << 24) 
				+ ((U32) wav_header[18] << 16) 
				+ ((U32) wav_header[17] << 8) 
				+ wav_header[16];
		}
		else if (!(strncmp((char *)&(wav_header[0]),"data",4)))
		{
			raw_data_length = chunk_length;			
		}
		file_pos += (chunk_length + 8);
		chunk_length = 0;
	} 
	// ****************
	infile.close();
	// ****************

	if (!uncompressed_pcm)
	{	
		 error_msg = "SoundFileNotPCM";
		  return(LLVORBISENC_PCM_FORMAT_ERR);
	}
	
	if ((num_channels < 1) || (num_channels > LLVORBIS_CLIP_MAX_CHANNELS))
	{	
		error_msg = "SoundFileInvalidChannelCount";
		return(LLVORBISENC_MULTICHANNEL_ERR);
	}

	if (sample_rate != LLVORBIS_CLIP_SAMPLE_RATE)
	{	
		error_msg = "SoundFileInvalidSampleRate";
		return(LLVORBISENC_UNSUPPORTED_SAMPLE_RATE);
	}
	
	if ((bits_per_sample != 16) && (bits_per_sample != 8))
	{		 
		error_msg = "SoundFileInvalidWordSize";
		return(LLVORBISENC_UNSUPPORTED_WORD_SIZE);
	}

	if (!raw_data_length)
	{
		error_msg = "SoundFileInvalidHeader";
		return(LLVORBISENC_CLIP_TOO_LONG);		 
	}

	F32 clip_length = (F32)raw_data_length/(F32)bytes_per_sec;
		
	if (clip_length > LLVORBIS_CLIP_MAX_TIME)
	{
		error_msg = "SoundFileInvalidTooLong";
		return(LLVORBISENC_CLIP_TOO_LONG);		 
	}

    return(LLVORBISENC_NOERR);
}
S32 encode_vorbis_file(const std::string& in_fname, const std::string& out_fname)
{
#define READ_BUFFER 1024
	unsigned char readbuffer[READ_BUFFER*4+44];   /* out of the data segment, not the stack */	/*Flawfinder: ignore*/

	ogg_stream_state os; /* take physical pages, weld into a logical stream of packets */
	ogg_page         og; /* one Ogg bitstream page.  Vorbis packets are inside */
	ogg_packet       op; /* one raw packet of data for decode */
	
	vorbis_info      vi; /* struct that stores all the static vorbis bitstream settings */
	vorbis_comment   vc; /* struct that stores all the user comments */
	
	vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
	vorbis_block     vb; /* local working space for packet->PCM decode */
	
	int eos=0;
	int result;

	U16 num_channels = 0;
	U32 sample_rate = 0;
	U32 bits_per_sample = 0;

	S32 format_error = 0;
	std::string error_msg;
	if ((format_error = check_for_invalid_wav_formats(in_fname, error_msg)))
	{
		llwarns << error_msg << ": " << in_fname << llendl;
		return(format_error);
	}

#if 1
	unsigned char wav_header[44];	/*Flawfinder: ignore*/

	S32 data_left = 0;

	LLAPRFile infile ;
	infile.open(in_fname,LL_APR_RB);
	if (!infile.getFileHandle())
	{
		llwarns << "Couldn't open temporary ogg file for writing: " << in_fname
			<< llendl;
		return(LLVORBISENC_SOURCE_OPEN_ERR);
	}

	LLAPRFile outfile ;
	outfile.open(out_fname,LL_APR_WPB);
	if (!outfile.getFileHandle())
	{
		llwarns << "Couldn't open upload sound file for reading: " << in_fname
			<< llendl;
		return(LLVORBISENC_DEST_OPEN_ERR);
	}
	
	 // parse the chunks
	 U32 chunk_length = 0;
	 U32 file_pos = 12;  // start at the first chunk (usually fmt but not always)
	 
	 while (infile.eof() != APR_EOF)
	 {
		 infile.seek(APR_SET,file_pos);
		 infile.read(wav_header, 44);
		 
		 chunk_length = ((U32) wav_header[7] << 24) 
			 + ((U32) wav_header[6] << 16) 
			 + ((U32) wav_header[5] << 8) 
			 + wav_header[4];
		 
//		 llinfos << "chunk found: '" << wav_header[0] << wav_header[1] << wav_header[2] << wav_header[3] << "'" << llendl;
		 
		 if (!(strncmp((char *)&(wav_header[0]),"fmt ",4)))
		 {
			 num_channels = ((U16) wav_header[11] << 8) + wav_header[10];
			 sample_rate = ((U32) wav_header[15] << 24) 
				 + ((U32) wav_header[14] << 16) 
				 + ((U32) wav_header[13] << 8) 
				 + wav_header[12];
			 bits_per_sample = ((U16) wav_header[23] << 8) + wav_header[22];
		 }
	 	 else if (!(strncmp((char *)&(wav_header[0]),"data",4)))
		 {
			 infile.seek(APR_SET,file_pos+8);
			 // leave the file pointer at the beginning of the data chunk data
			 data_left = chunk_length;			
			 break;
		 }
		 file_pos += (chunk_length + 8);
		 chunk_length = 0;
	 } 
	 

	 /********** Encode setup ************/
	 
	 /* choose an encoding mode */
	 /* (mode 0: 44kHz stereo uncoupled, roughly 128kbps VBR) */
	 vorbis_info_init(&vi);

	 // always encode to mono

	 // SL-52913 & SL-53779 determined this quality level to be our 'good
	 // enough' general-purpose quality level with a nice low bitrate.
	 // Equivalent to oggenc -q0.5
	 F32 quality = 0.05f;
//	 quality = (bitrate==128000 ? 0.4f : 0.1);

//	 if (vorbis_encode_init(&vi, /* num_channels */ 1 ,sample_rate, -1, bitrate, -1))
	 if (vorbis_encode_init_vbr(&vi, /* num_channels */ 1 ,sample_rate, quality))
//	 if (vorbis_encode_setup_managed(&vi,1,sample_rate,-1,bitrate,-1) ||
//		vorbis_encode_ctl(&vi,OV_ECTL_RATEMANAGE_AVG,NULL) ||
//		vorbis_encode_setup_init(&vi))
	{
		llwarns << "unable to initialize vorbis codec at quality " << quality << llendl;
		//		llwarns << "unable to initialize vorbis codec at bitrate " << bitrate << llendl;
		return(LLVORBISENC_DEST_OPEN_ERR);
	}
	 
	 /* add a comment */
	 vorbis_comment_init(&vc);
//	 vorbis_comment_add(&vc,"Linden");
	 
	 /* set up the analysis state and auxiliary encoding storage */
	 vorbis_analysis_init(&vd,&vi);
	 vorbis_block_init(&vd,&vb);
	 
	 /* set up our packet->stream encoder */
	 /* pick a random serial number; that way we can more likely build
		chained streams just by concatenation */
	 ogg_stream_init(&os, ll_rand());
	 
	 /* Vorbis streams begin with three headers; the initial header (with
		most of the codec setup parameters) which is mandated by the Ogg
		bitstream spec.  The second header holds any comment fields.  The
		third header holds the bitstream codebook.  We merely need to
		make the headers, then pass them to libvorbis one at a time;
		libvorbis handles the additional Ogg bitstream constraints */
	 
	 {
		 ogg_packet header;
		 ogg_packet header_comm;
		 ogg_packet header_code;
		 
		 vorbis_analysis_headerout(&vd,&vc,&header,&header_comm,&header_code);
		 ogg_stream_packetin(&os,&header); /* automatically placed in its own
											  page */
		 ogg_stream_packetin(&os,&header_comm);
		 ogg_stream_packetin(&os,&header_code);
		 
		 /* We don't have to write out here, but doing so makes streaming 
		  * much easier, so we do, flushing ALL pages. This ensures the actual
		  * audio data will start on a new page
		  */
		 while(!eos){
			 int result=ogg_stream_flush(&os,&og);
			 if(result==0)break;
			 outfile.write(og.header, og.header_len);
			 outfile.write(og.body, og.body_len);
		 }
		 
	 }
	 
	 
	 while(!eos)
	 {
		 long bytes_per_sample = bits_per_sample/8;

		 long bytes=(long)infile.read(readbuffer,llclamp((S32)(READ_BUFFER*num_channels*bytes_per_sample),0,data_left)); /* stereo hardwired here */
		 
		 if (bytes==0)
		 {
			 /* end of file.  this can be done implicitly in the mainline,
				but it's easier to see here in non-clever fashion.
				Tell the library we're at end of stream so that it can handle
				the last frame and mark end of stream in the output properly */

			 vorbis_analysis_wrote(&vd,0);
//			 eos = 1;
			 
		 }
		 else
		 {
			 long i;
			 long samples;
			 int temp;

			 data_left -= bytes;
             /* data to encode */
			 
			 /* expose the buffer to submit data */
			 float **buffer=vorbis_analysis_buffer(&vd,READ_BUFFER);
			
			 i = 0;
			 samples = bytes / (num_channels * bytes_per_sample);

			 if (num_channels == 2)
			 {
				 if (bytes_per_sample == 2)
				 {
					 /* uninterleave samples */
					 for(i=0; i<samples ;i++)
					 {
					 	 temp =  ((signed char *)readbuffer)[i*4+1];	/*Flawfinder: ignore*/
						 temp += ((signed char *)readbuffer)[i*4+3];	/*Flawfinder: ignore*/
						 temp <<= 8;
						 temp += readbuffer[i*4];
						 temp += readbuffer[i*4+2];

						 buffer[0][i] = ((float)temp) / 65536.f;
					 }
				 }
				 else // presume it's 1 byte per which is unsigned (F#@%ing wav "standard")
				 {
					 /* uninterleave samples */
					 for(i=0; i<samples ;i++)
					 {
					 	 temp  = readbuffer[i*2+0];
						 temp += readbuffer[i*2+1];
						 temp -= 256;
						 buffer[0][i] = ((float)temp) / 256.f;
					 }
				 } 
			 }
			 else if (num_channels == 1)
			 {
				 if (bytes_per_sample == 2)
				 {
					 for(i=0; i < samples ;i++)
					 {
					 	 temp = ((signed char*)readbuffer)[i*2+1];
						 temp <<= 8;
						 temp += readbuffer[i*2];
						 buffer[0][i] = ((float)temp) / 32768.f;
					 }
				 }
				 else // presume it's 1 byte per which is unsigned (F#@%ing wav "standard")
				 {
					 for(i=0; i < samples ;i++)
					 {
						 temp = readbuffer[i];
						 temp -= 128;
						 buffer[0][i] = ((float)temp) / 128.f;
					 }
				 }
			 }
				
			 /* tell the library how much we actually submitted */
			 vorbis_analysis_wrote(&vd,i);
		 }
			 
		 /* vorbis does some data preanalysis, then divvies up blocks for
			more involved (potentially parallel) processing.  Get a single
			block for encoding now */
		 while(vorbis_analysis_blockout(&vd,&vb)==1)
		 {
			 
			 /* analysis */
			/* Do the main analysis, creating a packet */
			vorbis_analysis(&vb, NULL);
			vorbis_bitrate_addblock(&vb);

			while(vorbis_bitrate_flushpacket(&vd, &op)) 
			{
			 
			 /* weld the packet into the bitstream */
			 ogg_stream_packetin(&os,&op);
			 
			 /* write out pages (if any) */
			 while(!eos)
			 {
				 result = ogg_stream_pageout(&os,&og);

				 if(result==0)
				 	break;

				 outfile.write(og.header, og.header_len);
				 outfile.write(og.body, og.body_len);
				 
				 /* this could be set above, but for illustrative purposes, I do
					it here (to show that vorbis does know where the stream ends) */
				 
				 if(ogg_page_eos(&og))
				 	eos=1;
				 
			 }
			}
		 }
	 }
	 
	 
	 
	 /* clean up and exit.  vorbis_info_clear() must be called last */
	 
	 ogg_stream_clear(&os);
	 vorbis_block_clear(&vb);
	 vorbis_dsp_clear(&vd);
	 vorbis_comment_clear(&vc);
	 vorbis_info_clear(&vi);
	 
	 /* ogg_page and ogg_packet structs always point to storage in
		libvorbis.  They're never freed or manipulated directly */
	 
//	 fprintf(stderr,"Vorbis encoding: Done.\n");
	 llinfos << "Vorbis encoding: Done." << llendl;
	 
#endif
	 return(LLVORBISENC_NOERR);
	 
}
Example #12
0
//------------------------------------------------------------------------
// LLBVHLoader::loadTranslationTable()
//------------------------------------------------------------------------
ELoadStatus LLBVHLoader::loadTranslationTable(const char *fileName)
{
	mLineNumber = 0;
	mTranslations.clear();
	mConstraints.clear();

	//--------------------------------------------------------------------
	// open file
	//--------------------------------------------------------------------
	std::string path = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS,fileName);

	LLAPRFile infile ;
	infile.open(path, LL_APR_R);
	apr_file_t *fp = infile.getFileHandle();
	if (!fp)
		return E_ST_NO_XLT_FILE;

	llinfos << "NOTE: Loading translation table: " << fileName << llendl;

	//--------------------------------------------------------------------
	// register file to be closed on function exit
	//--------------------------------------------------------------------
	
	//--------------------------------------------------------------------
	// load header
	//--------------------------------------------------------------------
	if ( ! getLine(fp) )
		return E_ST_EOF;
	if ( strncmp(mLine, "Translations 1.0", 16) )
		return E_ST_NO_XLT_HEADER;

	//--------------------------------------------------------------------
	// load data one line at a time
	//--------------------------------------------------------------------
	BOOL loadingGlobals = FALSE;
	Translation *trans = NULL;
	while ( getLine(fp) )
	{
		//----------------------------------------------------------------
		// check the 1st token on the line to determine if it's empty or a comment
		//----------------------------------------------------------------
		char token[128]; /* Flawfinder: ignore */
		if ( sscanf(mLine, " %127s", token) != 1 )	/* Flawfinder: ignore */
			continue;

		if (token[0] == '#')
			continue;

		//----------------------------------------------------------------
		// check if a [jointName] or [GLOBALS] was specified.
		//----------------------------------------------------------------
		if (token[0] == '[')
		{
			char name[128]; /* Flawfinder: ignore */
			if ( sscanf(mLine, " [%127[^]]", name) != 1 )
				return E_ST_NO_XLT_NAME;

			if (strcmp(name, "GLOBALS")==0)
			{
				loadingGlobals = TRUE;
				continue;
			}
			else
			{
				loadingGlobals = FALSE;
				Translation &newTrans = mTranslations[ name ];
				trans = &newTrans;
				continue;
			}
		}

		//----------------------------------------------------------------
		// check for optional emote 
		//----------------------------------------------------------------
		if (loadingGlobals && LLStringUtil::compareInsensitive(token, "emote")==0)
		{
			char emote_str[1024];	/* Flawfinder: ignore */
			if ( sscanf(mLine, " %*s = %1023s", emote_str) != 1 )	/* Flawfinder: ignore */
				return E_ST_NO_XLT_EMOTE;

			mEmoteName.assign( emote_str );
//			llinfos << "NOTE: Emote: " << mEmoteName.c_str() << llendl;
			continue;
		}


		//----------------------------------------------------------------
		// check for global priority setting
		//----------------------------------------------------------------
		if (loadingGlobals && LLStringUtil::compareInsensitive(token, "priority")==0)
		{
			S32 priority;
			if ( sscanf(mLine, " %*s = %d", &priority) != 1 )
				return E_ST_NO_XLT_PRIORITY;

			mPriority = priority;
//			llinfos << "NOTE: Priority: " << mPriority << llendl;
			continue;
		}

		//----------------------------------------------------------------
		// check for global loop setting
		//----------------------------------------------------------------
		if (loadingGlobals && LLStringUtil::compareInsensitive(token, "loop")==0)
		{
			char trueFalse[128];		/* Flawfinder: ignore */
			trueFalse[0] = '\0';
			
			F32 loop_in = 0.f;
			F32 loop_out = 1.f;

			if ( sscanf(mLine, " %*s = %f %f", &loop_in, &loop_out) == 2 )
			{
				mLoop = TRUE;
			}
			else if ( sscanf(mLine, " %*s = %127s", trueFalse) == 1 )	/* Flawfinder: ignore */	
			{
				mLoop = (LLStringUtil::compareInsensitive(trueFalse, "true")==0);
			}
			else
			{
				return E_ST_NO_XLT_LOOP;
			}

			mLoopInPoint = loop_in * mDuration;
			mLoopOutPoint = loop_out * mDuration;

			continue;
		}

		//----------------------------------------------------------------
		// check for global easeIn setting
		//----------------------------------------------------------------
		if (loadingGlobals && LLStringUtil::compareInsensitive(token, "easein")==0)
		{
			F32 duration;
			char type[128];	/* Flawfinder: ignore */
			if ( sscanf(mLine, " %*s = %f %127s", &duration, type) != 2 )	/* Flawfinder: ignore */
				return E_ST_NO_XLT_EASEIN;

			mEaseIn = duration;
			continue;
		}

		//----------------------------------------------------------------
		// check for global easeOut setting
		//----------------------------------------------------------------
		if (loadingGlobals && LLStringUtil::compareInsensitive(token, "easeout")==0)
		{
			F32 duration;
			char type[128];		/* Flawfinder: ignore */
			if ( sscanf(mLine, " %*s = %f %127s", &duration, type) != 2 )	/* Flawfinder: ignore */
				return E_ST_NO_XLT_EASEOUT;

			mEaseOut = duration;
			continue;
		}

		//----------------------------------------------------------------
		// check for global handMorph setting
		//----------------------------------------------------------------
		if (loadingGlobals && LLStringUtil::compareInsensitive(token, "hand")==0)
		{
			S32 handMorph;
			if (sscanf(mLine, " %*s = %d", &handMorph) != 1)
				return E_ST_NO_XLT_HAND;

			mHand = handMorph;
			continue;
		}

		if (loadingGlobals && LLStringUtil::compareInsensitive(token, "constraint")==0)
		{
			Constraint constraint;

			// try reading optional target direction
			if(sscanf( /* Flawfinder: ignore */
				mLine,
				" %*s = %d %f %f %f %f %15s %f %f %f %15s %f %f %f %f %f %f", 
				&constraint.mChainLength,
				&constraint.mEaseInStart,
				&constraint.mEaseInStop,
				&constraint.mEaseOutStart,
				&constraint.mEaseOutStop,
				constraint.mSourceJointName,
				&constraint.mSourceOffset.mV[VX],
				&constraint.mSourceOffset.mV[VY],
				&constraint.mSourceOffset.mV[VZ],
				constraint.mTargetJointName,
				&constraint.mTargetOffset.mV[VX],
				&constraint.mTargetOffset.mV[VY],
				&constraint.mTargetOffset.mV[VZ],
				&constraint.mTargetDir.mV[VX],
				&constraint.mTargetDir.mV[VY],
				&constraint.mTargetDir.mV[VZ]) != 16)
			{
				if(sscanf( /* Flawfinder: ignore */
					mLine,
					" %*s = %d %f %f %f %f %15s %f %f %f %15s %f %f %f", 
					&constraint.mChainLength,
					&constraint.mEaseInStart,
					&constraint.mEaseInStop,
					&constraint.mEaseOutStart,
					&constraint.mEaseOutStop,
					constraint.mSourceJointName,
					&constraint.mSourceOffset.mV[VX],
					&constraint.mSourceOffset.mV[VY],
					&constraint.mSourceOffset.mV[VZ],
					constraint.mTargetJointName,
					&constraint.mTargetOffset.mV[VX],
					&constraint.mTargetOffset.mV[VY],
					&constraint.mTargetOffset.mV[VZ]) != 13)
				{
					return E_ST_NO_CONSTRAINT;
				}
			}
			else
			{
				// normalize direction
				if (!constraint.mTargetDir.isExactlyZero())
				{
					constraint.mTargetDir.normVec();
				}

			}
			
			constraint.mConstraintType = CONSTRAINT_TYPE_POINT;
			mConstraints.push_back(constraint);
			continue;
		}

		if (loadingGlobals && LLStringUtil::compareInsensitive(token, "planar_constraint")==0)
		{
			Constraint constraint;

			// try reading optional target direction
			if(sscanf( /* Flawfinder: ignore */
				mLine,
				" %*s = %d %f %f %f %f %15s %f %f %f %15s %f %f %f %f %f %f", 
				&constraint.mChainLength,
				&constraint.mEaseInStart,
				&constraint.mEaseInStop,
				&constraint.mEaseOutStart,
				&constraint.mEaseOutStop,
				constraint.mSourceJointName,
				&constraint.mSourceOffset.mV[VX],
				&constraint.mSourceOffset.mV[VY],
				&constraint.mSourceOffset.mV[VZ],
				constraint.mTargetJointName,
				&constraint.mTargetOffset.mV[VX],
				&constraint.mTargetOffset.mV[VY],
				&constraint.mTargetOffset.mV[VZ],
				&constraint.mTargetDir.mV[VX],
				&constraint.mTargetDir.mV[VY],
				&constraint.mTargetDir.mV[VZ]) != 16)
			{
				if(sscanf( /* Flawfinder: ignore */
					mLine,
					" %*s = %d %f %f %f %f %15s %f %f %f %15s %f %f %f", 
					&constraint.mChainLength,
					&constraint.mEaseInStart,
					&constraint.mEaseInStop,
					&constraint.mEaseOutStart,
					&constraint.mEaseOutStop,
					constraint.mSourceJointName,
					&constraint.mSourceOffset.mV[VX],
					&constraint.mSourceOffset.mV[VY],
					&constraint.mSourceOffset.mV[VZ],
					constraint.mTargetJointName,
					&constraint.mTargetOffset.mV[VX],
					&constraint.mTargetOffset.mV[VY],
					&constraint.mTargetOffset.mV[VZ]) != 13)
				{
					return E_ST_NO_CONSTRAINT;
				}
			}
			else
			{
				// normalize direction
				if (!constraint.mTargetDir.isExactlyZero())
				{
					constraint.mTargetDir.normVec();
				}

			}
			
			constraint.mConstraintType = CONSTRAINT_TYPE_PLANE;
			mConstraints.push_back(constraint);
			continue;
		}


		//----------------------------------------------------------------
		// at this point there must be a valid trans pointer
		//----------------------------------------------------------------
		if ( ! trans )
			return E_ST_NO_XLT_NAME;

		//----------------------------------------------------------------
		// check for ignore flag
		//----------------------------------------------------------------
		if ( LLStringUtil::compareInsensitive(token, "ignore")==0 )
		{
			char trueFalse[128];	/* Flawfinder: ignore */
			if ( sscanf(mLine, " %*s = %127s", trueFalse) != 1 )	/* Flawfinder: ignore */
				return E_ST_NO_XLT_IGNORE;

			trans->mIgnore = (LLStringUtil::compareInsensitive(trueFalse, "true")==0);
			continue;
		}

		//----------------------------------------------------------------
		// check for relativepos flag
		//----------------------------------------------------------------
		if ( LLStringUtil::compareInsensitive(token, "relativepos")==0 )
		{
			F32 x, y, z;
			char relpos[128];	/* Flawfinder: ignore */
			if ( sscanf(mLine, " %*s = %f %f %f", &x, &y, &z) == 3 )
			{
				trans->mRelativePosition.setVec( x, y, z );
			}
			else if ( sscanf(mLine, " %*s = %127s", relpos) == 1 )	/* Flawfinder: ignore */
			{
				if ( LLStringUtil::compareInsensitive(relpos, "firstkey")==0 )
				{
					trans->mRelativePositionKey = TRUE;
				}
				else
				{
					return E_ST_NO_XLT_RELATIVE;
				}
			}
			else
			{
				return E_ST_NO_XLT_RELATIVE;
			}

			continue;
		}

		//----------------------------------------------------------------
		// check for relativerot flag
		//----------------------------------------------------------------
		if ( LLStringUtil::compareInsensitive(token, "relativerot")==0 )
		{
			//F32 x, y, z;
			char relpos[128];	/* Flawfinder: ignore */
			if ( sscanf(mLine, " %*s = %127s", relpos) == 1 )	/* Flawfinder: ignore */
			{
				if ( LLStringUtil::compareInsensitive(relpos, "firstkey")==0 )
				{
					trans->mRelativeRotationKey = TRUE;
				}
				else
				{
					return E_ST_NO_XLT_RELATIVE;
				}
			}
			else
			{
				return E_ST_NO_XLT_RELATIVE;
			}

			continue;
		}

		//----------------------------------------------------------------
		// check for outname value
		//----------------------------------------------------------------
		if ( LLStringUtil::compareInsensitive(token, "outname")==0 )
		{
			char outName[128];	/* Flawfinder: ignore */
			if ( sscanf(mLine, " %*s = %127s", outName) != 1 )	/* Flawfinder: ignore */
				return E_ST_NO_XLT_OUTNAME;

			trans->mOutName = outName;
			continue;
		}

		//----------------------------------------------------------------
		// check for frame matrix value
		//----------------------------------------------------------------
		if ( LLStringUtil::compareInsensitive(token, "frame")==0 )
		{
			LLMatrix3 fm;
			if ( sscanf(mLine, " %*s = %f %f %f, %f %f %f, %f %f %f",
					&fm.mMatrix[0][0], &fm.mMatrix[0][1], &fm.mMatrix[0][2],
					&fm.mMatrix[1][0], &fm.mMatrix[1][1], &fm.mMatrix[1][2],
					&fm.mMatrix[2][0], &fm.mMatrix[2][1], &fm.mMatrix[2][2]	) != 9 )
				return E_ST_NO_XLT_MATRIX;

			trans->mFrameMatrix = fm;
			continue;
		}

		//----------------------------------------------------------------
		// check for offset matrix value
		//----------------------------------------------------------------
		if ( LLStringUtil::compareInsensitive(token, "offset")==0 )
		{
			LLMatrix3 om;
			if ( sscanf(mLine, " %*s = %f %f %f, %f %f %f, %f %f %f",
					&om.mMatrix[0][0], &om.mMatrix[0][1], &om.mMatrix[0][2],
					&om.mMatrix[1][0], &om.mMatrix[1][1], &om.mMatrix[1][2],
					&om.mMatrix[2][0], &om.mMatrix[2][1], &om.mMatrix[2][2]	) != 9 )
				return E_ST_NO_XLT_MATRIX;

			trans->mOffsetMatrix = om;
			continue;
		}

		//----------------------------------------------------------------
		// check for mergeparent value
		//----------------------------------------------------------------
		if ( LLStringUtil::compareInsensitive(token, "mergeparent")==0 )
		{
			char mergeParentName[128];	/* Flawfinder: ignore */
			if ( sscanf(mLine, " %*s = %127s", mergeParentName) != 1 )	/* Flawfinder: ignore */
				return E_ST_NO_XLT_MERGEPARENT;

			trans->mMergeParentName = mergeParentName;
			continue;
		}

		//----------------------------------------------------------------
		// check for mergechild value
		//----------------------------------------------------------------
		if ( LLStringUtil::compareInsensitive(token, "mergechild")==0 )
		{
			char mergeChildName[128];	/* Flawfinder: ignore */
			if ( sscanf(mLine, " %*s = %127s", mergeChildName) != 1 )	/* Flawfinder: ignore */
				return E_ST_NO_XLT_MERGECHILD;

			trans->mMergeChildName = mergeChildName;
			continue;
		}

		//----------------------------------------------------------------
		// check for per-joint priority
		//----------------------------------------------------------------
		if ( LLStringUtil::compareInsensitive(token, "priority")==0 )
		{
			S32 priority;
			if ( sscanf(mLine, " %*s = %d", &priority) != 1 )
				return E_ST_NO_XLT_PRIORITY;

			trans->mPriorityModifier = priority;
			continue;
		}

	}

	infile.close() ;
	return E_ST_OK;
}
Example #13
0
void upload_new_resource(const std::string& src_filename, std::string name,
			 std::string desc, S32 compression_info,
			 LLAssetType::EType destination_folder_type,
			 LLInventoryType::EType inv_type,
			 U32 next_owner_perms,
			 U32 group_perms,
			 U32 everyone_perms,
			 const std::string& display_name,
			 LLAssetStorage::LLStoreAssetCallback callback,
			 S32 expected_upload_cost,
			 void *userdata)
{	
	// Generate the temporary UUID.
	std::string filename = gDirUtilp->getTempFilename();
	LLTransactionID tid;
	LLAssetID uuid;
	
	LLSD args;

	std::string exten = gDirUtilp->getExtension(src_filename);
	LLAssetType::EType asset_type = LLAssetType::AT_NONE;
	std::string error_message;

	BOOL error = FALSE;
	
	if (exten.empty())
	{
		std::string short_name = gDirUtilp->getBaseFileName(filename);
		
		// No extension
		error_message = llformat(
				"No file extension for the file: '%s'\nPlease make sure the file has a correct file extension",
				short_name.c_str());
		args["FILE"] = short_name;
 		upload_error(error_message, "NofileExtension", filename, args);
		return;
	}
	else if( exten == "bmp")
	{
		asset_type = LLAssetType::AT_TEXTURE;
		if (!LLViewerImageList::createUploadFile(src_filename,
												 filename,
												 IMG_CODEC_BMP ))
		{
			error_message = llformat( "Problem with file %s:\n\n%s\n",
					src_filename.c_str(), LLImage::getLastError().c_str());
			args["FILE"] = src_filename;
			args["ERROR"] = LLImage::getLastError();
			upload_error(error_message, "ProblemWithFile", filename, args);
			return;
		}
	}
	else if( exten == "tga")
	{
		asset_type = LLAssetType::AT_TEXTURE;
		if (!LLViewerImageList::createUploadFile(src_filename,
												 filename,
												 IMG_CODEC_TGA ))
		{
			error_message = llformat("Problem with file %s:\n\n%s\n",
					src_filename.c_str(), LLImage::getLastError().c_str());
			args["FILE"] = src_filename;
			args["ERROR"] = LLImage::getLastError();
			upload_error(error_message, "ProblemWithFile", filename, args);
			return;
		}
	}
	else if( exten == "jpg" || exten == "jpeg")
	{
		asset_type = LLAssetType::AT_TEXTURE;
		if (!LLViewerImageList::createUploadFile(src_filename,
												 filename,
												 IMG_CODEC_JPEG ))
		{
			error_message = llformat("Problem with file %s:\n\n%s\n",
					src_filename.c_str(), LLImage::getLastError().c_str());
			args["FILE"] = src_filename;
			args["ERROR"] = LLImage::getLastError();
			upload_error(error_message, "ProblemWithFile", filename, args);
			return;
		}
	}
 	else if( exten == "png")
 	{
 		asset_type = LLAssetType::AT_TEXTURE;
 		if (!LLViewerImageList::createUploadFile(src_filename,
 												 filename,
 												 IMG_CODEC_PNG ))
 		{
 			error_message = llformat("Problem with file %s:\n\n%s\n",
 					src_filename.c_str(), LLImage::getLastError().c_str());
 			args["FILE"] = src_filename;
 			args["ERROR"] = LLImage::getLastError();
 			upload_error(error_message, "ProblemWithFile", filename, args);
 			return;
 		}
 	}
	else if(exten == "wav")
	{
		asset_type = LLAssetType::AT_SOUND;  // tag it as audio
		S32 encode_result = 0;

		llinfos << "Attempting to encode wav as an ogg file" << llendl;

		encode_result = encode_vorbis_file(src_filename, filename);
		
		if (LLVORBISENC_NOERR != encode_result)
		{
			switch(encode_result)
			{
				case LLVORBISENC_DEST_OPEN_ERR:
				    error_message = llformat( "Couldn't open temporary compressed sound file for writing: %s\n", filename.c_str());
					args["FILE"] = filename;
					upload_error(error_message, "CannotOpenTemporarySoundFile", filename, args);
					break;

				default:	
				  error_message = llformat("Unknown vorbis encode failure on: %s\n", src_filename.c_str());
					args["FILE"] = src_filename;
					upload_error(error_message, "UnknownVorbisEncodeFailure", filename, args);
					break;	
			}	
			return;
		}
	}
	else if(exten == "ogg")
	{
		asset_type = LLAssetType::AT_SOUND;  // tag it as audio
		filename = src_filename;
	}
	else if(exten == "tmp")	 	
	{	 	
		// This is a generic .lin resource file	 	
         asset_type = LLAssetType::AT_OBJECT;	 	
         LLFILE* in = LLFile::fopen(src_filename, "rb");		/* Flawfinder: ignore */	 	
         if (in)	 	
         {	 	
                 // read in the file header	 	
                 char buf[16384];		/* Flawfinder: ignore */ 	
                 S32 read;		/* Flawfinder: ignore */	 	
                 S32  version;	 	
                 if (fscanf(in, "LindenResource\nversion %d\n", &version))	 	
                 {	 	
                         if (2 == version)	 	
                         {
								// *NOTE: This buffer size is hard coded into scanf() below.
                                 char label[MAX_STRING];		/* Flawfinder: ignore */	 	
                                 char value[MAX_STRING];		/* Flawfinder: ignore */	 	
                                 S32  tokens_read;	 	
                                 while (fgets(buf, 1024, in))	 	
                                 {	 	
                                         label[0] = '\0';	 	
                                         value[0] = '\0';	 	
                                         tokens_read = sscanf(	/* Flawfinder: ignore */
											 buf,
											 "%254s %254s\n",
											 label, value);	 	

                                         llinfos << "got: " << label << " = " << value	 	
                                                         << llendl;	 	

                                         if (EOF == tokens_read)	 	
                                         {	 	
                                                 fclose(in);	 	
                                                 error_message = llformat("corrupt resource file: %s", src_filename.c_str());
												 args["FILE"] = src_filename;
												 upload_error(error_message, "CorruptResourceFile", filename, args);
                                                 return;
                                         }	 	

                                         if (2 == tokens_read)	 	
                                         {	 	
                                                 if (! strcmp("type", label))	 	
                                                 {	 	
                                                         asset_type = (LLAssetType::EType)(atoi(value));	 	
                                                 }	 	
                                         }	 	
                                         else	 	
                                         {	 	
                                                 if (! strcmp("_DATA_", label))	 	
                                                 {	 	
                                                         // below is the data section	 	
                                                         break;	 	
                                                 }	 	
                                         }	 	
                                         // other values are currently discarded	 	
                                 }	 	

                         }	 	
                         else	 	
                         {	 	
                                 fclose(in);	 	
                                 error_message = llformat("unknown linden resource file version in file: %s", src_filename.c_str());
								 args["FILE"] = src_filename;
								 upload_error(error_message, "UnknownResourceFileVersion", filename, args);
                                 return;
                         }	 	
                 }	 	
                 else	 	
                 {	 	
                         // this is an original binary formatted .lin file	 	
                         // start over at the beginning of the file	 	
                         fseek(in, 0, SEEK_SET);	 	

                         const S32 MAX_ASSET_DESCRIPTION_LENGTH = 256;	 	
                         const S32 MAX_ASSET_NAME_LENGTH = 64;	 	
                         S32 header_size = 34 + MAX_ASSET_DESCRIPTION_LENGTH + MAX_ASSET_NAME_LENGTH;	 	
                         S16     type_num;	 	

                         // read in and throw out most of the header except for the type	 	
                         if (fread(buf, header_size, 1, in) != 1)
						 {
							 llwarns << "Short read" << llendl;
						 }
                         memcpy(&type_num, buf + 16, sizeof(S16));		/* Flawfinder: ignore */	 	
                         asset_type = (LLAssetType::EType)type_num;	 	
                 }	 	

                 // copy the file's data segment into another file for uploading	 	
                 LLFILE* out = LLFile::fopen(filename, "wb");		/* Flawfinder: ignore */	
                 if (out)	 	
                 {	 	
                         while((read = fread(buf, 1, 16384, in)))		/* Flawfinder: ignore */	 	
                         {	 	
							 if (fwrite(buf, 1, read, out) != read)
							 {
								 llwarns << "Short write" << llendl;
							 }
                         }	 	
                         fclose(out);	 	
                 }	 	
                 else	 	
                 {	 	
                         fclose(in);	 	
                         error_message = llformat( "Unable to create output file: %s", filename.c_str());
						 args["FILE"] = filename;
						 upload_error(error_message, "UnableToCreateOutputFile", filename, args);
                         return;
                 }	 	

                 fclose(in);	 	
         }	 	
         else	 	
         {	 	
                 llinfos << "Couldn't open .lin file " << src_filename << llendl;	 	
         }	 	
	}
	else if(exten == "ogg")
	{
		asset_type = LLAssetType::AT_SOUND;  // tag it as audio
		filename = src_filename;
	}
	else if (exten == "bvh")
	{
		// <edit> THE FUCK WE DON'T
		//error_message = llformat("We do not currently support bulk upload of animation files\n");
		//upload_error(error_message, "DoNotSupportBulkAnimationUpload", filename, args);
		//return;
		asset_type = LLAssetType::AT_ANIMATION;
		S32 file_size;
		LLAPRFile fp;
		
		if(!fp.open(src_filename, LL_APR_RB, LLAPRFile::local, &file_size))
		{
			args["ERROR_MESSAGE"] = llformat("Couldn't read file %s\n", src_filename.c_str());
			LLNotifications::instance().add("ErrorMessage", args);
			return;
		}
		char* file_buffer = new char[file_size + 1];
		if(!fp.read(file_buffer, file_size))
		{
			fp.close();
			delete[] file_buffer;
			args["ERROR_MESSAGE"] = llformat("Couldn't read file %s\n", src_filename.c_str());
			LLNotifications::instance().add("ErrorMessage", args);
			return;
		}
		  ELoadStatus load_status = E_ST_OK;
			S32 line_number = 0; 
			 LLBVHLoader* loaderp = new LLBVHLoader(file_buffer, load_status, line_number);
			///  LLBVHLoader* loaderp = new LLBVHLoader(file_buffer);
		if(!loaderp->isInitialized())
		{
			fp.close();
			delete[] file_buffer;
			args["ERROR_MESSAGE"] = llformat("Couldn't convert file %s to internal animation format\n", src_filename.c_str());
			LLNotifications::instance().add("ErrorMessage", args);
			return;
		}
		S32 buffer_size = loaderp->getOutputSize();
		U8* buffer = new U8[buffer_size];
		LLDataPackerBinaryBuffer dp(buffer, buffer_size);
		loaderp->serialize(dp);
		LLAPRFile apr_file;
		apr_file.open(filename, LL_APR_WB, LLAPRFile::local);
		apr_file.write(buffer, buffer_size);
		delete[] file_buffer;
		delete[] buffer;
		fp.close();
		apr_file.close();
		// </edit>
	}
	// <edit>
	else if (exten == "animatn" || exten == "anim" || exten == "neil")
	{
		asset_type = LLAssetType::AT_ANIMATION;
		filename = src_filename;
	}
	else if(exten == "j2k" || exten == "jp2" || exten == "texture" || exten == "j2c")
	{
		asset_type = LLAssetType::AT_TEXTURE;
		filename = src_filename;
	}
	else if(exten == "gesture")
	{
		asset_type = LLAssetType::AT_GESTURE;
		filename = src_filename;
	}
	else if(exten == "notecard")
	{
		asset_type = LLAssetType::AT_NOTECARD;
		filename = src_filename;
	}
	else if(exten == "lsl" || exten == "txt" || exten == "lso" | exten == "rtf")
	{
		asset_type = LLAssetType::AT_LSL_TEXT;
		filename = src_filename;
	}
	else if(exten == "eyes" || exten == "gloves" || exten == "hair" || exten == "jacket" || exten == "pants" || exten == "shape" || exten == "shirt" || exten == "shoes" || exten == "skin" || exten == "skirt" || exten == "socks" || exten == "underpants" || exten == "tattoo" || exten == "alpha" || exten == "undershirt" || exten == "bodypart" || exten == "clothing")
	{
		asset_type = LLAssetType::AT_CLOTHING;
		filename = src_filename;
	}
	// </edit>
	else
	{
		// Unknown extension
		// *TODO: Translate?
		// <edit>
		//error_message = llformat("Unknown file extension .%s\nExpected .wav, .tga, .bmp, .jpg, .jpeg, or .bvh", exten.c_str());
		error_message = llformat("Unknown file extension .%s\nExpected .wav, .tga, .bmp, .jpg, .jpeg, .bvh, .animatn, .ogg, .gesture, .notecard, .lsl, .eyes, .gloves, .hair, .jacket, .pants, .shape, .shirt, .shoes, .skin, .skirt, .socks, .underpants, .undershirt, .bodypart, .clothing, .jp2, .j2k, or .j2c", exten.c_str());
		// </edit>
		error = TRUE;;
	}

	// gen a new transaction ID for this asset
	tid.generate();

	if (!error)
	{
		uuid = tid.makeAssetID(gAgent.getSecureSessionID());
		// copy this file into the vfs for upload
		S32 file_size;
		LLAPRFile infile ;
		infile.open(filename, LL_APR_RB, LLAPRFile::local, &file_size);
		if (infile.getFileHandle())
		{
			LLVFile file(gVFS, uuid, asset_type, LLVFile::WRITE);

			file.setMaxSize(file_size);

			const S32 buf_size = 65536;
			U8 copy_buf[buf_size];
			while ((file_size = infile.read(copy_buf, buf_size)))
			{
				file.write(copy_buf, file_size);
			}
		}
		else
		{
			error_message = llformat( "Unable to access output file: %s", filename.c_str());
			error = TRUE;
		}
	}

	if (!error)
	{
		std::string t_disp_name = display_name;
		if (t_disp_name.empty())
		{
			t_disp_name = src_filename;
		}
		// <edit> hack to create scripts and gestures
		if(exten == "lsl" || exten == "gesture" || exten == "notecard" || exten == "txt" || exten == "rtf" || exten == "lso")
		{
			LLInventoryType::EType inv_type = LLInventoryType::IT_GESTURE;
			if(exten == "lsl") inv_type = LLInventoryType::IT_LSL;
			else if(exten == "gesture") inv_type = LLInventoryType::IT_GESTURE;
			else if(exten == "notecard") inv_type = LLInventoryType::IT_NOTECARD;
			create_inventory_item(	gAgent.getID(),
									gAgent.getSessionID(),
									gInventory.findCategoryUUIDForType(asset_type),
									LLTransactionID::tnull,
									name,
									uuid.asString(), // fake asset id, but in vfs
									asset_type,
									inv_type,
									NOT_WEARABLE,
									PERM_ITEM_UNRESTRICTED,
									new NewResourceItemCallback);
		}
		else
		// </edit>
		upload_new_resource(tid, asset_type, name, desc, compression_info, // tid
				    destination_folder_type, inv_type, next_owner_perms, group_perms, everyone_perms,
				    display_name, callback, expected_upload_cost, userdata);
	}
	else
	{
		llwarns << error_message << llendl;
		LLSD args;
		args["ERROR_MESSAGE"] = error_message;
		LLNotifications::instance().add("ErrorMessage", args);
		if(LLFile::remove(filename) == -1)
		{
			lldebugs << "unable to remove temp file" << llendl;
		}
		LLFilePicker::instance().reset();
	}
}
Example #14
0
bool LLLFSThread::Request::processRequest()
{
	bool complete = false;
	if (mOperation ==  FILE_READ)
	{
		llassert(mOffset >= 0);
		LLAPRFile infile ; // auto-closes
		infile.open(mFileName, LL_APR_RB, mThread->getLocalAPRFilePool());
		if (!infile.getFileHandle())
		{
			llwarns << "LLLFS: Unable to read file: " << mFileName << llendl;
			mBytesRead = 0; // fail
			return true;
		}
		S32 off;
		if (mOffset < 0)
			off = infile.seek(APR_END, 0);
		else
			off = infile.seek(APR_SET, mOffset);
		llassert_always(off >= 0);
		mBytesRead = infile.read(mBuffer, mBytes );
		complete = true;
// 		llinfos << "LLLFSThread::READ:" << mFileName << " Bytes: " << mBytesRead << llendl;
	}
	else if (mOperation ==  FILE_WRITE)
	{
		apr_int32_t flags = APR_CREATE|APR_WRITE|APR_BINARY;
		if (mOffset < 0)
			flags |= APR_APPEND;
		LLAPRFile outfile ; // auto-closes
		outfile.open(mFileName, flags, mThread->getLocalAPRFilePool());
		if (!outfile.getFileHandle())
		{
			llwarns << "LLLFS: Unable to write file: " << mFileName << llendl;
			mBytesRead = 0; // fail
			return true;
		}
		if (mOffset >= 0)
		{
			S32 seek = outfile.seek(APR_SET, mOffset);
			if (seek < 0)
			{
				llwarns << "LLLFS: Unable to write file (seek failed): " << mFileName << llendl;
				mBytesRead = 0; // fail
				return true;
			}
		}
		mBytesRead = outfile.write(mBuffer, mBytes );
		complete = true;
// 		llinfos << "LLLFSThread::WRITE:" << mFileName << " Bytes: " << mBytesRead << "/" << mBytes << " Offset:" << mOffset << llendl;
	}
	else
	{
		llerrs << "LLLFSThread::unknown operation: " << (S32)mOperation << llendl;
	}
	return complete;
}
void ImportTracker::send_inventory(LLSD& prim)
{
	U32 local_id = prim["LocalID"].asInteger();
	if (prim.has("inventory"))
	{
		std::string assetpre = asset_dir + gDirUtilp->getDirDelimiter();
		LLSD inventory = prim["inventory"];
		for (LLSD::array_iterator inv = inventory.beginArray(); inv != inventory.endArray(); ++inv)
		{
			LLSD item = (*inv);
			InventoryImportInfo* data = new InventoryImportInfo;
			data->localid = local_id;
			LLTransactionID tid;
			tid.generate();
			LLUUID assetid = tid.makeAssetID(gAgent.getSecureSessionID());
			data->tid = tid;
			data->assetid = assetid;
			data->type = LLAssetType::lookup(item["type"].asString());////LLAssetType::EType(U32(item["type"].asInteger()));
			data->name = item["name"].asString();
			data->description = item["desc"].asString();
			if(item.has("item_id"))
			{
				//cmdline_printchat("item id found");
				std::string filename = assetpre + item["item_id"].asString() + "." + item["type"].asString();
				//S32 file_size;
				//LLAPRFile infile ;
				//infile.open(filename, LL_APR_RB, NULL, &file_size);
				//apr_file_t* fp = infile.getFileHandle();
				//if(fp)
				if(LLFile::isfile(filename))
				{
					//cmdline_printchat("file "+filename+" exists");
					data->filename = filename;
					//infile.close();
				}else
				{
					//cmdline_printchat("file "+filename+" does not exist");
					delete data;
					continue;
				}
			}else
			{
				//cmdline_printchat("item id not found");
				delete data;
				continue;
			}

			data->wear_type = NOT_WEARABLE;

			//if(data->type == LLAssetType::AT_LSL_TEXT)
			{
				data->inv_type = LLInventoryType::defaultForAssetType(data->type);
				//printchat("is script");
				data->compiled = false;
				//
				switch(data->type)
				{
				case LLAssetType::AT_TEXTURE:
				case LLAssetType::AT_TEXTURE_TGA:
					//cmdline_printchat("case textures");
					{
						std::string url = gAgent.getRegion()->getCapability("NewFileAgentInventory");
						S32 file_size;
						LLAPRFile infile ;
						infile.open(data->filename, LL_APR_RB, NULL, &file_size);
						if (infile.getFileHandle())
						{
							//cmdline_printchat("got file handle");
							LLVFile file(gVFS, data->assetid, data->type, LLVFile::WRITE);
							file.setMaxSize(file_size);
							const S32 buf_size = 65536;
							U8 copy_buf[buf_size];
							while ((file_size = infile.read(copy_buf, buf_size)))
							{
								file.write(copy_buf, file_size);
							}
							LLSD body;
							body["folder_id"] = gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH);
							body["asset_type"] = LLAssetType::lookup(data->type);
							body["inventory_type"] = LLInventoryType::lookup(data->inv_type);
							body["name"] = data->name;
							body["description"] = data->description;
							body["next_owner_mask"] = LLSD::Integer(U32_MAX);
							body["group_mask"] = LLSD::Integer(U32_MAX);
							body["everyone_mask"] = LLSD::Integer(U32_MAX);
							body["expected_upload_cost"] = LLSD::Integer(LLGlobalEconomy::Singleton::getInstance()->getPriceUpload());
							//cmdline_printchat("posting "+ data->assetid.asString());
							LLHTTPClient::post(url, body, new JCImportInventoryResponder(body, data->assetid, data->type,data));
							//error = TRUE;
						}
					}
					break;
				case LLAssetType::AT_CLOTHING:
				case LLAssetType::AT_BODYPART:
					//cmdline_printchat("case cloth/bodypart");
					{
						S32 file_size;
						LLAPRFile infile ;
						infile.open(data->filename, LL_APR_RB, NULL, &file_size);
						if (infile.getFileHandle())
						{
							//cmdline_printchat("got file handle @ cloth");
							LLVFile file(gVFS, data->assetid, data->type, LLVFile::WRITE);
							file.setMaxSize(file_size);
							const S32 buf_size = 65536;
							U8 copy_buf[buf_size];
							while ((file_size = infile.read(copy_buf, buf_size)))
							{
								file.write(copy_buf, file_size);
							}

							LLFILE* fp = LLFile::fopen(data->filename, "rb");
							if(fp)//HACK LOL LOL LOL
							{
								LLWearable* wearable = new LLWearable(LLUUID::null);
								wearable->importFile( fp );
								//if (!res)
								{
									data->wear_type = wearable->getType();
								}
								delete wearable;
							}
							//cmdline_printchat("storing "+data->assetid.asString());
							gAssetStorage->storeAssetData(data->tid, data->type,
												JCImportInventorycallback,
												(void*)data,
												FALSE,
												TRUE,
												FALSE);
						}
					}
					break;
				case LLAssetType::AT_NOTECARD:
					//cmdline_printchat("case notecard");
					{
						//std::string agent_url = gAgent.getRegion()->getCapability("UpdateNotecardAgentInventory");
						LLPointer<LLInventoryCallback> cb = new JCPostInvCallback(data);
						LLPermissions perm;
						LLUUID parent_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH);
						create_inventory_item(gAgent.getID(), gAgent.getSessionID(),
							gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH), data->tid, data->name,
							data->description, data->type, LLInventoryType::defaultForAssetType(data->type), data->wear_type,
							LLFloaterPerms::getNextOwnerPerms(),
							cb);
					}
					break;
				case LLAssetType::AT_LSL_TEXT:
					{
						LLPointer<LLInventoryCallback> cb = new JCPostInvCallback(data);
						LLPermissions perm;
						LLUUID parent_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH);
						create_inventory_item(gAgent.getID(), gAgent.getSessionID(),
							gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH), data->tid, data->name,
							data->description, data->type, LLInventoryType::defaultForAssetType(data->type), data->wear_type,
							LLFloaterPerms::getNextOwnerPerms(),
							cb);
					}
					break;
				case LLAssetType::AT_SCRIPT://this shouldn't happen as this is legacy shit
				case LLAssetType::AT_GESTURE://we don't import you atm...
				default:
					break;
				}
				asset_insertions += 1;
			}
		}
	}
}
Example #16
0
        virtual void uploadComplete(const LLSD& content)
        {
		llinfos << "Adding " << content["new_inventory_item"].asUUID() << " " << content["new_asset"].asUUID() << " to inventory." << llendl;
		//LLPointer<LLInventoryCallback> cb = new LLImportTransferCallback(mData);
		
                if(mPostData["folder_id"].asUUID().notNull())
		{
			LLPermissions perm;
			U32 everyone_perms = PERM_NONE;
			U32 group_perms = PERM_NONE;
			U32 next_owner_perms = PERM_ALL;
			perm.init(gAgent.getID(), gAgent.getID(), LLUUID::null, LLUUID::null);
			if(content.has("new_next_owner_mask"))
			{
				// This is a new sim that provides creation perms so use them.
				// Do not assume we got the perms we asked for in mPostData 
				// since the sim may not have granted them all.
				everyone_perms = content["new_everyone_mask"].asInteger();
				group_perms = content["new_group_mask"].asInteger();
				next_owner_perms = content["new_next_owner_mask"].asInteger();
			}
			else 
			{
				// This old sim doesn't provide creation perms so use old assumption-based perms.
				if(mPostData["inventory_type"].asString() != "snapshot")
				{
					next_owner_perms = PERM_MOVE | PERM_TRANSFER;
				}
			}
			perm.initMasks(PERM_ALL, PERM_ALL, everyone_perms, group_perms, next_owner_perms);
			S32 creation_date_now = time_corrected();
			LLPointer<LLViewerInventoryItem> item = new LLViewerInventoryItem(content["new_inventory_item"].asUUID(),
												mPostData["folder_id"].asUUID(),
												perm,
												content["new_asset"].asUUID(),
												mData->type,
												mData->inv_type,
												mPostData["name"].asString(),
												mPostData["description"].asString(),
												LLSaleInfo::DEFAULT,
												LLInventoryItemFlags::II_FLAGS_NONE,
												creation_date_now);
			gInventory.updateItem(item);
			gInventory.notifyObservers();
			LLXmlImport::sTextureReplace[mData->oldassetid] = content["new_asset"].asUUID();
		}
		LLXmlImport::sUploadedAssets++;
		if(!LLXmlImport::sImportInProgress) return;
		LLFloaterImportProgress::update();
		if(LLXmlImport::sUploadedAssets < LLXmlImport::sTotalAssets)
		{
			LLImportAssetData* data = LLXmlImport::sXmlImportOptions->mAssets[LLXmlImport::sUploadedAssets];
		        data->folderid = mData->folderid;
			std::string url = gAgent.getRegion()->getCapability("NewFileAgentInventory");
			if(!url.empty())
			{
				LLPointer<LLImageJ2C> integrity_test = new LLImageJ2C;
				if( !integrity_test->loadAndValidate( data->filename ) )
				{
					llinfos << "Image: " << data->filename << " is corrupt." << llendl;
				}
				S32 file_size;
				LLAPRFile infile ;
				infile.open(data->filename, LL_APR_RB, LLAPRFile::short_lived, &file_size);
				if (infile.getFileHandle())
				{
					LLVFile file(gVFS, data->assetid, data->type, LLVFile::WRITE);
					file.setMaxSize(file_size);
					const S32 buf_size = 65536;
					U8 copy_buf[buf_size];
					while ((file_size = infile.read(copy_buf, buf_size)))
					{
						file.write(copy_buf, file_size);
					}
					
					LLSD body;
					body["folder_id"] = data->folderid;
					body["asset_type"] = LLAssetType::lookup(data->type);
					body["inventory_type"] = LLInventoryType::lookup(data->inv_type);
					body["name"] = data->name;
					body["description"] = data->description;
					body["next_owner_mask"] = LLSD::Integer(U32_MAX);
					body["group_mask"] = LLSD::Integer(U32_MAX);
					body["everyone_mask"] = LLSD::Integer(U32_MAX);
					body["expected_upload_cost"] = LLSD::Integer(LLGlobalEconomy::Singleton::getInstance()->getPriceUpload());
					LLHTTPClient::post(url, body, new LLImportInventoryResponder(body, data->assetid, data->type,data));
				}
			}
			else
				llinfos << "NewFileAgentInventory does not exist!!!!" << llendl;
		}
		else
			LLXmlImport::finish_init();
		
                
        }
LLAssetType::EType LLAssetConverter::convert(std::string src_filename, std::string filename)
{
	std::string exten = gDirUtilp->getExtension(src_filename);
	LLAssetType::EType asset_type = LLAssetType::AT_NONE;
	if (exten.empty())
		return LLAssetType::AT_NONE;
	else if(exten == "bmp")
	{
		asset_type = LLAssetType::AT_TEXTURE;
		if (!LLViewerTextureList::createUploadFile(src_filename,
												 filename,
												 IMG_CODEC_BMP ))
		{
			return LLAssetType::AT_NONE;
		}
	}
	else if( exten == "tga")
	{
		asset_type = LLAssetType::AT_TEXTURE;
		if (!LLViewerTextureList::createUploadFile(src_filename,
												 filename,
												 IMG_CODEC_TGA ))
		{
			return LLAssetType::AT_NONE;
		}
	}
	else if( exten == "jpg" || exten == "jpeg")
	{
		asset_type = LLAssetType::AT_TEXTURE;
		if (!LLViewerTextureList::createUploadFile(src_filename,
												 filename,
												 IMG_CODEC_JPEG ))
		{
			return LLAssetType::AT_NONE;
		}
	}
 	else if( exten == "png")
 	{
 		asset_type = LLAssetType::AT_TEXTURE;
 		if (!LLViewerTextureList::createUploadFile(src_filename,
 												 filename,
 												 IMG_CODEC_PNG ))
 		{
 			return LLAssetType::AT_NONE;
 		}
 	}
	else if(exten == "wav")
	{
		asset_type = LLAssetType::AT_SOUND;
		if(encode_vorbis_file(src_filename, filename) != LLVORBISENC_NOERR)
		{
			return LLAssetType::AT_NONE;
		}
	}
	else if(exten == "ogg")
	{
		asset_type = LLAssetType::AT_SOUND;
		if(!copyFile(src_filename, filename))
		{
			return LLAssetType::AT_NONE;
		}
	}
	//else if(exten == "tmp") FIXME
	else if (exten == "bvh")
	{

		asset_type = LLAssetType::AT_ANIMATION;
		S32 file_size;
		LLAPRFile fp;
		fp.open(src_filename, LL_APR_RB, LLAPRFile::global, &file_size);
		if(!fp.getFileHandle()) return LLAssetType::AT_NONE;
		char* file_buffer = new char[file_size + 1];
		ELoadStatus load_status = E_ST_OK;
		S32 line_number = 0; 
		LLBVHLoader* loaderp = new LLBVHLoader(file_buffer, load_status, line_number);
		
		if(load_status == E_ST_NO_XLT_FILE)
		{
			llwarns << "NOTE: No translation table found." << llendl;
		}
		else
		{
			llwarns << "ERROR: [line: " << line_number << "] " << STATUS[load_status].c_str() << llendl;
		}
		S32 buffer_size = loaderp->getOutputSize();
		U8* buffer = new U8[buffer_size];
		LLDataPackerBinaryBuffer dp(buffer, buffer_size);
		loaderp->serialize(dp);
		LLAPRFile apr_file(filename, LL_APR_WB, LLAPRFile::global);
		apr_file.write(buffer, buffer_size);
		delete[] file_buffer;
		delete[] buffer;
		fp.close();
		apr_file.close();
	}
	else if (exten == "animatn")
	{
		asset_type = LLAssetType::AT_ANIMATION;
		if(!copyFile(src_filename, filename))
		{
			return LLAssetType::AT_NONE;
		}
	}
	else if(exten == "jp2" || exten == "j2k" || exten == "j2c")
	{
		asset_type = LLAssetType::AT_TEXTURE;
		if(!copyFile(src_filename, filename))
		{
			return LLAssetType::AT_NONE;
		}
	}
	else if(exten == "gesture")
	{
		asset_type = LLAssetType::AT_GESTURE;
		if(!copyFile(src_filename, filename))
		{
			return LLAssetType::AT_NONE;
		}
	}
	else if(exten == "notecard")
	{
		asset_type = LLAssetType::AT_NOTECARD;
		if(!copyFile(src_filename, filename))
		{
			return LLAssetType::AT_NONE;
		}
	}
	else if(exten == "lsl")
	{
		asset_type = LLAssetType::AT_LSL_TEXT;
		if(!copyFile(src_filename, filename))
		{
			return LLAssetType::AT_NONE;
		}
	}
	else if(exten == "eyes" || exten == "gloves" || exten == "hair" || exten == "jacket" || exten == "pants" || exten == "shape" || exten == "shirt" || exten == "shoes" || exten == "skin" || exten == "skirt" || exten == "socks" || exten == "underpants" || exten == "undershirt" || exten == "bodypart" || exten == "clothing" || exten == "physics")
	{
		asset_type = LLAssetType::AT_CLOTHING;
		if(!copyFile(src_filename, filename))
		{
			return LLAssetType::AT_NONE;
		}
	}
	else
	{
		llwarns << "Unhandled extension" << llendl;
		return LLAssetType::AT_NONE;
	}
	return asset_type;
}
//-----------------------------------------------------------------------------
// loadMotions()
//-----------------------------------------------------------------------------
BOOL LLKeyframeMotionParam::loadMotions()
{
	//-------------------------------------------------------------------------
	// Load named file by concatenating the character prefix with the motion name.
	// Load data into a buffer to be parsed.
	//-------------------------------------------------------------------------
	//std::string path = gDirUtilp->getExpandedFilename(LL_PATH_MOTIONS,mCharacter->getAnimationPrefix())
	//	+ "_" + getName() + ".llp";
	//RN: deprecated unused reference to "motion" directory
	std::string path;


	//-------------------------------------------------------------------------
	// open the file
	//-------------------------------------------------------------------------
	S32 fileSize = 0;
	LLAPRFile infile ;
	infile.open(path, LL_APR_R, NULL, &fileSize);

	// <FS:ND> Remove LLVolatileAPRPool/apr_file_t and use FILE* instead
	// apr_file_t* fp = infile.getFileHandle() ;
	LLAPRFile::tFiletype* fp = infile.getFileHandle() ;
	// </FS:ND>

	if (!fp || fileSize == 0)
	{
		LL_INFOS() << "ERROR: can't open: " << path << LL_ENDL;
		return FALSE;
	}

	// allocate a text buffer
	std::vector<char> text(fileSize+1);

	//-------------------------------------------------------------------------
	// load data from file into buffer
	//-------------------------------------------------------------------------
	bool error = false;
	char *p = &text[0];
	while ( 1 )
	{
		if (apr_file_eof(fp) == APR_EOF)
		{
			break;
		}
		if (apr_file_gets(p, 1024, fp) != APR_SUCCESS)
		{
			error = true;
			break;
		}
		while ( *(++p) )
			;
	}

	//-------------------------------------------------------------------------
	// close the file
	//-------------------------------------------------------------------------
	infile.close();

	//-------------------------------------------------------------------------
	// check for error
	//-------------------------------------------------------------------------
	llassert( p <= (&text[0] + fileSize) );

	if ( error )
	{
		LL_INFOS() << "ERROR: error while reading from " << path << LL_ENDL;
		return FALSE;
	}

	LL_INFOS() << "Loading parametric keyframe data for: " << getName() << LL_ENDL;

	//-------------------------------------------------------------------------
	// parse the text and build keyframe data structures
	//-------------------------------------------------------------------------
	p = &text[0];
	S32 num;
	char strA[80]; /* Flawfinder: ignore */
	char strB[80]; /* Flawfinder: ignore */
	F32 floatA = 0.0f;


	//-------------------------------------------------------------------------
	// get priority
	//-------------------------------------------------------------------------
	BOOL isFirstMotion = TRUE;
	num = sscanf(p, "%79s %79s %f", strA, strB, &floatA);	/* Flawfinder: ignore */

	while(1)
	{
		if (num == 0 || num == EOF) break;
		if ((num != 3))
		{
			LL_INFOS() << "WARNING: can't read parametric motion" << LL_ENDL;
			return FALSE;
		}

		addKeyframeMotion(strA, gAnimLibrary.stringToAnimState(std::string(strA)), strB, floatA);
		if (isFirstMotion)
		{
			isFirstMotion = FALSE;
			setDefaultKeyframeMotion(strA);
		}
		
		p = strstr(p, "\n");
		if (!p)
		{
			break;
		}
			
		p++;
		num = sscanf(p, "%79s %79s %f", strA, strB, &floatA);	/* Flawfinder: ignore */
	}

	return TRUE;
}
//-----------------------------------------------------------------------------
// postBuild()
//-----------------------------------------------------------------------------
BOOL LLFloaterAnimPreview::postBuild()
{
	LLRect r;
	LLKeyframeMotion* motionp = NULL;
	LLBVHLoader* loaderp = NULL;

	if (!LLFloaterNameDesc::postBuild())
	{
		return FALSE;
	}

	childSetCommitCallback("name_form", onCommitName, this);

	childSetLabelArg("ok_btn", "[AMOUNT]", llformat("%d",sUploadAmount));
	childSetAction("ok_btn", onBtnOK, this);
	setDefaultBtn();

	mPreviewRect.set(PREVIEW_HPAD, 
		PREVIEW_TEXTURE_HEIGHT,
		getRect().getWidth() - PREVIEW_HPAD, 
		PREVIEW_HPAD + PREF_BUTTON_HEIGHT + PREVIEW_HPAD);
	mPreviewImageRect.set(0.f, 1.f, 1.f, 0.f);

	S32 y = mPreviewRect.mTop + BTN_HEIGHT;
	S32 btn_left = PREVIEW_HPAD;

	r.set( btn_left, y, btn_left + 32, y - BTN_HEIGHT );
	mPlayButton = getChild<LLButton>( "play_btn");
	if (!mPlayButton)
	{
		mPlayButton = new LLButton(std::string("play_btn"), LLRect(0,0,0,0));
	}
	mPlayButton->setClickedCallback(onBtnPlay);
	mPlayButton->setCallbackUserData(this);

	mPlayButton->setImages(std::string("button_anim_play.tga"),
						   std::string("button_anim_play_selected.tga"));
	mPlayButton->setDisabledImages(LLStringUtil::null,LLStringUtil::null);

	mPlayButton->setScaleImage(TRUE);

	mStopButton = getChild<LLButton>( "stop_btn");
	if (!mStopButton)
	{
		mStopButton = new LLButton(std::string("stop_btn"), LLRect(0,0,0,0));
	}
	mStopButton->setClickedCallback(onBtnStop);
	mStopButton->setCallbackUserData(this);

	mStopButton->setImages(std::string("button_anim_stop.tga"),
						   std::string("button_anim_stop_selected.tga"));
	mStopButton->setDisabledImages(LLStringUtil::null,LLStringUtil::null);

	mStopButton->setScaleImage(TRUE);

	r.set(r.mRight + PREVIEW_HPAD, y, getRect().getWidth() - PREVIEW_HPAD, y - BTN_HEIGHT);
	//childSetCommitCallback("playback_slider", onSliderMove, this);

	childHide("bad_animation_text");

	//childSetCommitCallback("preview_base_anim", onCommitBaseAnim, this);
	//childSetValue("preview_base_anim", "Standing");

	//childSetCommitCallback("priority", onCommitPriority, this);
	//childSetCommitCallback("loop_check", onCommitLoop, this);
	//childSetCommitCallback("loop_in_point", onCommitLoopIn, this);
	//childSetValidate("loop_in_point", validateLoopIn);
	//childSetCommitCallback("loop_out_point", onCommitLoopOut, this);
	//childSetValidate("loop_out_point", validateLoopOut);

	//childSetCommitCallback("hand_pose_combo", onCommitHandPose, this);
	
	//childSetCommitCallback("emote_combo", onCommitEmote, this);
	//childSetValue("emote_combo", "[None]");

	//childSetCommitCallback("ease_in_time", onCommitEaseIn, this);
	//childSetValidate("ease_in_time", validateEaseIn);
	//childSetCommitCallback("ease_out_time", onCommitEaseOut, this);
	//childSetValidate("ease_out_time", validateEaseOut);

	std::string exten = gDirUtilp->getExtension(mFilename);
	if (exten == "bvh")
	{
		// loading a bvh file

		// now load bvh file
		S32 file_size;
		
		LLAPRFile infile ;
		infile.open(mFilenameAndPath, LL_APR_RB, LLAPRFile::global, &file_size);
		
		if (!infile.getFileHandle())
		{
			llwarns << "Can't open BVH file:" << mFilename << llendl;	
		}
		else
		{
			char*	file_buffer;

			file_buffer = new char[file_size + 1];

			if (file_size == infile.read(file_buffer, file_size))
			{
				file_buffer[file_size] = '\0';
				llinfos << "Loading BVH file " << mFilename << llendl;
				loaderp = new LLBVHLoader(file_buffer);
			}

			infile.close() ;
			delete[] file_buffer;
		}
	}

	if (loaderp && loaderp->isInitialized() && loaderp->getDuration() <= MAX_ANIM_DURATION)
	{
		// generate unique id for this motion
		mTransactionID.generate();
		mMotionID = mTransactionID.makeAssetID(gAgent.getSecureSessionID());

		mAnimPreview = new LLPreviewAnimation(256, 256);

		// motion will be returned, but it will be in a load-pending state, as this is a new motion
		// this motion will not request an asset transfer until next update, so we have a chance to 
		// load the keyframe data locally
		motionp = (LLKeyframeMotion*)mAnimPreview->getDummyAvatar()->createMotion(mMotionID);

		// create data buffer for keyframe initialization
		S32 buffer_size = loaderp->getOutputSize();
		U8* buffer = new U8[buffer_size];

		LLDataPackerBinaryBuffer dp(buffer, buffer_size);

		// pass animation data through memory buffer
		loaderp->serialize(dp);
		dp.reset();
		BOOL success = motionp && motionp->deserialize(dp);

		delete []buffer;

		if (success)
		{
			setAnimCallbacks() ;
			
			const LLBBoxLocal &pelvis_bbox = motionp->getPelvisBBox();

			LLVector3 temp = pelvis_bbox.getCenter();
			// only consider XY?
			//temp.mV[VZ] = 0.f;
			F32 pelvis_offset = temp.magVec();

			temp = pelvis_bbox.getExtent();
			//temp.mV[VZ] = 0.f;
			F32 pelvis_max_displacement = pelvis_offset + (temp.magVec() * 0.5f) + 1.f;
			
			F32 camera_zoom = LLViewerCamera::getInstance()->getDefaultFOV() / (2.f * atan(pelvis_max_displacement / PREVIEW_CAMERA_DISTANCE));
		
			mAnimPreview->setZoom(camera_zoom);

			motionp->setName(childGetValue("name_form").asString());
			mAnimPreview->getDummyAvatar()->startMotion(mMotionID);
			childSetMinValue("playback_slider", 0.0);
			childSetMaxValue("playback_slider", 1.0);

			childSetValue("loop_check", LLSD(motionp->getLoop()));
			childSetValue("loop_in_point", LLSD(motionp->getLoopIn() / motionp->getDuration() * 100.f));
			childSetValue("loop_out_point", LLSD(motionp->getLoopOut() / motionp->getDuration() * 100.f));
			childSetValue("priority", LLSD((F32)motionp->getPriority()));
			childSetValue("hand_pose_combo", LLHandMotion::getHandPoseName(motionp->getHandPose()));
			childSetValue("ease_in_time", LLSD(motionp->getEaseInDuration()));
			childSetValue("ease_out_time", LLSD(motionp->getEaseOutDuration()));
			setEnabled(TRUE);
			std::string seconds_string;
			seconds_string = llformat(" - %.2f seconds", motionp->getDuration());

			setTitle(mFilename + std::string(seconds_string));
		}
		else
		{
			delete mAnimPreview;
			mAnimPreview = NULL;
			mMotionID.setNull();
			childSetValue("bad_animation_text", getString("failed_to_initialize"));
		}
	}
	else
	{
		if ( loaderp )
		{
			if (loaderp->getDuration() > MAX_ANIM_DURATION)
			{
				LLUIString out_str = getString("anim_too_long");
				out_str.setArg("[LENGTH]", llformat("%.1f", loaderp->getDuration()));
				out_str.setArg("[MAX_LENGTH]", llformat("%.1f", MAX_ANIM_DURATION));
				childSetValue("bad_animation_text", out_str.getString());
			}
			else
			{
				LLUIString out_str = getString("failed_file_read");
				out_str.setArg("[STATUS]", loaderp->getStatus()); // *TODO:Translate
				childSetValue("bad_animation_text", out_str.getString());
			}
		}

		//setEnabled(FALSE);
		mMotionID.setNull();
		mAnimPreview = NULL;
	}

	refresh();

	delete loaderp;

	return TRUE;
}
Example #20
0
S32 LLTextureCache::openAndReadEntry(const LLUUID& id, Entry& entry, bool create)
{
	S32 idx = -1;
	
	id_map_t::iterator iter1 = mHeaderIDMap.find(id);
	if (iter1 != mHeaderIDMap.end())
	{
		idx = iter1->second;
	}

	if (idx < 0)
	{
		if (create && !mReadOnly)
		{
			if (mHeaderEntriesInfo.mEntries < sCacheMaxEntries)
			{
				// Add an entry to the end of the list
				idx = mHeaderEntriesInfo.mEntries++;

			}
			else if (!mFreeList.empty())
			{
				idx = *(mFreeList.begin());
				mFreeList.erase(mFreeList.begin());
			}
			else
			{
				// Look for a still valid entry in the LRU
				for (std::set<LLUUID>::iterator iter2 = mLRU.begin(); iter2 != mLRU.end();)
				{
					std::set<LLUUID>::iterator curiter2 = iter2++;
					LLUUID oldid = *curiter2;
					// Erase entry from LRU regardless
					mLRU.erase(curiter2);
					// Look up entry and use it if it is valid
					id_map_t::iterator iter3 = mHeaderIDMap.find(oldid);
					if (iter3 != mHeaderIDMap.end() && iter3->second >= 0)
					{
						idx = iter3->second;
						mHeaderIDMap.erase(oldid);
						mTexturesSizeMap.erase(oldid);
						break;
					}
				}
				// if (idx < 0) at this point, we will rebuild the LRU 
				//  and retry if called from setHeaderCacheEntry(),
				//  otherwise this shouldn't happen and will trigger an error
			}
			if (idx >= 0)
			{
				// Set the header index
				mHeaderIDMap[id] = idx;
				llassert_always(mTexturesSizeMap.erase(id) == 0);
				// Initialize the entry (will get written later)
				entry.init(id, time(NULL));
				// Update Header
				writeEntriesHeader();
				// Write Entry
				S32 offset = sizeof(EntriesInfo) + idx * sizeof(Entry);
				LLAPRFile* aprfile = openHeaderEntriesFile(false, offset);
				S32 bytes_written = aprfile->write((void*)&entry, (S32)sizeof(Entry));
				llassert_always(bytes_written == sizeof(Entry));
				mHeaderEntriesMaxWriteIdx = llmax(mHeaderEntriesMaxWriteIdx, idx);
				closeHeaderEntriesFile();
			}
		}
	}
	else
	{
		// Remove this entry from the LRU if it exists
		mLRU.erase(id);
		// Read the entry
		S32 offset = sizeof(EntriesInfo) + idx * sizeof(Entry);
		LLAPRFile* aprfile = openHeaderEntriesFile(true, offset);
		S32 bytes_read = aprfile->read((void*)&entry, (S32)sizeof(Entry));
		llassert_always(bytes_read == sizeof(Entry));
		llassert_always(entry.mImageSize == 0 || entry.mImageSize == -1 || entry.mImageSize > entry.mBodySize);
		closeHeaderEntriesFile();
	}
	return idx;
}
void primbackup::upload_next_asset()
{
	if(textures.empty())
	{
		llinfos<<" Texture list is empty, moving to rez statge"<< llendl;
		current_asset=LLUUID::null;
		import_object1a();
		return;
	}

	this->updateimportnumbers();

	std::list<LLUUID>::iterator iter;
	iter=textures.begin();
	LLUUID id=(*iter);
	textures.pop_front();

	llinfos<<"Got texture ID "<<id<< "trying to upload"<<llendl;

	current_asset=id;
	std::string struid;
	id.toString(struid);
	std::string filename=folder+"//"+struid;
	

	LLAssetID uuid;
	LLTransactionID tid;

	// gen a new transaction ID for this asset
	tid.generate();
	uuid = tid.makeAssetID(gAgent.getSecureSessionID());

	S32 file_size;
	apr_file_t* fp;
    LLAPRFile aFile;
    aFile.open(filename, LL_APR_RB, LLAPRFile::global, &file_size);
    fp = aFile.getFileHandle();
	if (fp)
	{
		const S32 buf_size = 65536;	
		U8 copy_buf[buf_size];
		LLVFile file(gVFS, uuid,  LLAssetType::AT_TEXTURE, LLVFile::WRITE);
		file.setMaxSize(file_size);
		
		while ((file_size =aFile.read(copy_buf, buf_size)))
		{
			file.write(copy_buf, file_size);
		}
		aFile.close();
	}
	else
	{
		llwarns<<"Unable to access output file "<<filename<<llendl;
		upload_next_asset();
		return;
	}

	 myupload_new_resource(
	 tid, LLAssetType::AT_TEXTURE, struid,
		struid, 0,
		LLAssetType::AT_TEXTURE, 
		 LLInventoryType::defaultForAssetType(LLAssetType::AT_TEXTURE),
		 0x0,
		 "Uploaded texture",
		 NULL,
		 NULL);


}
Example #22
0
// static
LLAssetType::EType LLAssetConverter::convert(std::string src_filename, std::string filename)
{
	std::string exten = gDirUtilp->getExtension(src_filename);
	LLAssetType::EType asset_type = LLAssetType::AT_NONE;
	if (exten.empty())
		return LLAssetType::AT_NONE;
	else if(exten == "bmp")
	{
		asset_type = LLAssetType::AT_TEXTURE;
		if (!LLViewerImageList::createUploadFile(src_filename,
												 filename,
												 IMG_CODEC_BMP ))
		{
			return LLAssetType::AT_NONE;
		}
	}
	else if( exten == "tga")
	{
		asset_type = LLAssetType::AT_TEXTURE;
		if (!LLViewerImageList::createUploadFile(src_filename,
												 filename,
												 IMG_CODEC_TGA ))
		{
			return LLAssetType::AT_NONE;
		}
	}
	else if( exten == "jpg" || exten == "jpeg")
	{
		asset_type = LLAssetType::AT_TEXTURE;
		if (!LLViewerImageList::createUploadFile(src_filename,
												 filename,
												 IMG_CODEC_JPEG ))
		{
			return LLAssetType::AT_NONE;
		}
	}
 	else if( exten == "png")
 	{
 		asset_type = LLAssetType::AT_TEXTURE;
 		if (!LLViewerImageList::createUploadFile(src_filename,
 												 filename,
 												 IMG_CODEC_PNG ))
 		{
 			return LLAssetType::AT_NONE;
 		}
 	}
	else if(exten == "wav")
	{
		asset_type = LLAssetType::AT_SOUND;
		if(encode_vorbis_file(src_filename, filename) != LLVORBISENC_NOERR)
		{
			return LLAssetType::AT_NONE;
		}
	}
	else if(exten == "ogg")
	{
		asset_type = LLAssetType::AT_SOUND;
		if(!copyFile(src_filename, filename))
		{
			return LLAssetType::AT_NONE;
		}
	}
	//else if(exten == "tmp") FIXME
	else if (exten == "bvh")
	{
		asset_type = LLAssetType::AT_ANIMATION;
		S32 file_size;
		LLAPRFile fp;
		fp.open(src_filename, LL_APR_RB, LLAPRFile::global, &file_size);
		if(!fp.getFileHandle()) return LLAssetType::AT_NONE;
		char* file_buffer = new char[file_size + 1];
		if(fp.read(file_buffer, file_size) == 0) //not sure if this is right, gotta check this one
		{
			fp.close();
			delete[] file_buffer;
			return LLAssetType::AT_NONE;
		}
		LLBVHLoader* loaderp = new LLBVHLoader(file_buffer);
		if(!loaderp->isInitialized())
		{
			fp.close();
			delete[] file_buffer;
			return LLAssetType::AT_NONE;
		}
		S32 buffer_size = loaderp->getOutputSize();
		U8* buffer = new U8[buffer_size];
		LLDataPackerBinaryBuffer dp(buffer, buffer_size);
		loaderp->serialize(dp);
		LLAPRFile apr_file(filename, LL_APR_WB, LLAPRFile::global);
		apr_file.write(buffer, buffer_size);
		delete[] file_buffer;
		delete[] buffer;
		fp.close();
		apr_file.close();
	}
	else if (exten == "animatn")
	{
		asset_type = LLAssetType::AT_ANIMATION;
		if(!copyFile(src_filename, filename))
		{
			return LLAssetType::AT_NONE;
		}
	}
	else if(exten == "jp2" || exten == "j2k" || exten == "j2c")
	{
		asset_type = LLAssetType::AT_TEXTURE;
		if(!copyFile(src_filename, filename))
		{
			return LLAssetType::AT_NONE;
		}
	}
	else if(exten == "gesture")
	{
		asset_type = LLAssetType::AT_GESTURE;
		if(!copyFile(src_filename, filename))
		{
			return LLAssetType::AT_NONE;
		}
	}
	else if(exten == "notecard")
	{
		asset_type = LLAssetType::AT_NOTECARD;
		if(!copyFile(src_filename, filename))
		{
			return LLAssetType::AT_NONE;
		}
	}
	else if(exten == "lsl")
	{
		asset_type = LLAssetType::AT_LSL_TEXT;
		if(!copyFile(src_filename, filename))
		{
			return LLAssetType::AT_NONE;
		}
	}
	else if(exten == "eyes" || exten == "gloves" || exten == "hair" || exten == "jacket" || exten == "pants" || exten == "shape" || exten == "shirt" || exten == "shoes" || exten == "skin" || exten == "skirt" || exten == "socks" || exten == "underpants" || exten == "undershirt" || exten == "bodypart" || exten == "clothing")
	{
		asset_type = LLAssetType::AT_CLOTHING;
		if(!copyFile(src_filename, filename))
		{
			return LLAssetType::AT_NONE;
		}
	}
	else
	{
		llwarns << "Unhandled extension" << llendl;
		return LLAssetType::AT_NONE;
	}
	return asset_type;
}
Example #23
0
//-----------------------------------------------------------------------------
// loadBVH()
//-----------------------------------------------------------------------------
BOOL LLFloaterAnimPreview::loadBVH()
{
	LLKeyframeMotion* motionp = NULL;
	LLBVHLoader* loaderp = NULL;

	mPlayButton->setVisible(true);
	mPauseButton->setVisible(false);
	
	getChildView("bad_animation_text")->setVisible(FALSE);

	std::string exten = gDirUtilp->getExtension(mFilename);
	if (exten == "bvh")
	{
		// loading a bvh file

		// now load bvh file
		S32 file_size;
		
		LLAPRFile infile ;
		infile.open(mFilenameAndPath, LL_APR_RB, NULL, &file_size);
		
		if (!infile.getFileHandle())
		{
			llwarns << "Can't open BVH file:" << mFilename << llendl;	
		}
		else
		{
			char*	file_buffer;

			file_buffer = new char[file_size + 1];

			if (file_size == infile.read(file_buffer, file_size))
			{
				file_buffer[file_size] = '\0';
				llinfos << "Loading BVH file " << mFilename << llendl;
				ELoadStatus load_status = E_ST_OK;
				S32 line_number = 0; 
				loaderp = new LLBVHLoader(file_buffer, load_status, line_number);
				std::string status = getString(STATUS[load_status]);
				
				if(load_status == E_ST_NO_XLT_FILE)
				{
					llwarns << "NOTE: No translation table found." << llendl;
				}
				else
				{
					llwarns << "ERROR: [line: " << line_number << "] " << status << llendl;
				}
			}

			infile.close() ;
			delete[] file_buffer;
		}
	}

	if (loaderp && loaderp->isInitialized() && loaderp->getDuration() <= MAX_ANIM_DURATION)
	{
		// generate unique id for this motion
		mTransactionID.generate();
		mMotionID = mTransactionID.makeAssetID(gAgent.getSecureSessionID());

		mAnimPreview = new LLPreviewAnimation(256, 256);

		// motion will be returned, but it will be in a load-pending state, as this is a new motion
		// this motion will not request an asset transfer until next update, so we have a chance to 
		// load the keyframe data locally
		motionp = (LLKeyframeMotion*)mAnimPreview->getPreviewAvatar()->createMotion(mMotionID);

		// create data buffer for keyframe initialization
		S32 buffer_size = loaderp->getOutputSize();
		U8* buffer = new U8[buffer_size];

		LLDataPackerBinaryBuffer dp(buffer, buffer_size);

		// pass animation data through memory buffer
		loaderp->serialize(dp);
		dp.reset();
		BOOL success = motionp && motionp->deserialize(dp);

		delete []buffer;

		if (success)
		{
			setAnimCallbacks() ;
			
			const LLBBoxLocal &pelvis_bbox = motionp->getPelvisBBox();

			LLVector3 temp = pelvis_bbox.getCenter();
			// only consider XY?
			//temp.mV[VZ] = 0.f;
			F32 pelvis_offset = temp.magVec();

			temp = pelvis_bbox.getExtent();
			//temp.mV[VZ] = 0.f;
			F32 pelvis_max_displacement = pelvis_offset + (temp.magVec() * 0.5f) + 1.f;
			
			F32 camera_zoom = LLViewerCamera::getInstance()->getDefaultFOV() / (2.f * atan(pelvis_max_displacement / PREVIEW_CAMERA_DISTANCE));
		
			mAnimPreview->setZoom(camera_zoom);

			motionp->setName(getChild<LLUICtrl>("name_form")->getValue().asString());
			mAnimPreview->getPreviewAvatar()->startMotion(mMotionID);
			
			getChild<LLSlider>("playback_slider")->setMinValue(0.0);
			getChild<LLSlider>("playback_slider")->setMaxValue(1.0);

			getChild<LLUICtrl>("loop_check")->setValue(LLSD(motionp->getLoop()));
			getChild<LLUICtrl>("loop_in_point")->setValue(LLSD(motionp->getLoopIn() / motionp->getDuration() * 100.f));
			getChild<LLUICtrl>("loop_out_point")->setValue(LLSD(motionp->getLoopOut() / motionp->getDuration() * 100.f));
			getChild<LLUICtrl>("priority")->setValue(LLSD((F32)motionp->getPriority()));
			getChild<LLUICtrl>("hand_pose_combo")->setValue(LLHandMotion::getHandPoseName(motionp->getHandPose()));
			getChild<LLUICtrl>("ease_in_time")->setValue(LLSD(motionp->getEaseInDuration()));
			getChild<LLUICtrl>("ease_out_time")->setValue(LLSD(motionp->getEaseOutDuration()));
			setEnabled(TRUE);
			std::string seconds_string;
			seconds_string = llformat(" - %.2f seconds", motionp->getDuration());

			setTitle(mFilename + std::string(seconds_string));
		}
		else
		{
			mAnimPreview = NULL;
			mMotionID.setNull();
			getChild<LLUICtrl>("bad_animation_text")->setValue(getString("failed_to_initialize"));
		}
	}
	else
	{
		if ( loaderp )
		{
			if (loaderp->getDuration() > MAX_ANIM_DURATION)
			{
				LLUIString out_str = getString("anim_too_long");
				out_str.setArg("[LENGTH]", llformat("%.1f", loaderp->getDuration()));
				out_str.setArg("[MAX_LENGTH]", llformat("%.1f", MAX_ANIM_DURATION));
				getChild<LLUICtrl>("bad_animation_text")->setValue(out_str.getString());
			}
			else
			{
				LLUIString out_str = getString("failed_file_read");
				out_str.setArg("[STATUS]", getString(STATUS[loaderp->getStatus()])); 
				getChild<LLUICtrl>("bad_animation_text")->setValue(out_str.getString());
			}
		}

		//setEnabled(FALSE);
		mMotionID.setNull();
		mAnimPreview = NULL;
	}

	refresh();

	delete loaderp;

	return TRUE;
}
void upload_new_resource(const std::string& src_filename, std::string name,
			 std::string desc, S32 compression_info,
			 LLAssetType::EType destination_folder_type,
			 LLInventoryType::EType inv_type,
			 U32 next_owner_perms,
			 U32 group_perms,
			 U32 everyone_perms,
			 const std::string& display_name,
			 LLAssetStorage::LLStoreAssetCallback callback,
			 S32 expected_upload_cost,
			 void *userdata)
{	
	// Generate the temporary UUID.
	std::string filename = gDirUtilp->getTempFilename();
	LLTransactionID tid;
	LLAssetID uuid;
	
	LLSD args;

	std::string exten = gDirUtilp->getExtension(src_filename);
	LLAssetType::EType asset_type = LLAssetType::AT_NONE;
	std::string error_message;

	BOOL error = FALSE;
	
	if (exten.empty())
	{
		std::string short_name = gDirUtilp->getBaseFileName(filename);
		
		// No extension
		error_message = llformat(
				"No file extension for the file: '%s'\nPlease make sure the file has a correct file extension",
				short_name.c_str());
		args["FILE"] = short_name;
 		upload_error(error_message, "NofileExtension", filename, args);
		return;
	}
	else if( exten == "bmp")
	{
		asset_type = LLAssetType::AT_TEXTURE;
		if (!LLViewerImageList::createUploadFile(src_filename,
												 filename,
												 IMG_CODEC_BMP ))
		{
			error_message = llformat( "Problem with file %s:\n\n%s\n",
					src_filename.c_str(), LLImage::getLastError().c_str());
			args["FILE"] = src_filename;
			args["ERROR"] = LLImage::getLastError();
			upload_error(error_message, "ProblemWithFile", filename, args);
			return;
		}
	}
	else if( exten == "tga")
	{
		asset_type = LLAssetType::AT_TEXTURE;
		if (!LLViewerImageList::createUploadFile(src_filename,
												 filename,
												 IMG_CODEC_TGA ))
		{
			error_message = llformat("Problem with file %s:\n\n%s\n",
					src_filename.c_str(), LLImage::getLastError().c_str());
			args["FILE"] = src_filename;
			args["ERROR"] = LLImage::getLastError();
			upload_error(error_message, "ProblemWithFile", filename, args);
			return;
		}
	}
	else if( exten == "jpg" || exten == "jpeg")
	{
		asset_type = LLAssetType::AT_TEXTURE;
		if (!LLViewerImageList::createUploadFile(src_filename,
												 filename,
												 IMG_CODEC_JPEG ))
		{
			error_message = llformat("Problem with file %s:\n\n%s\n",
					src_filename.c_str(), LLImage::getLastError().c_str());
			args["FILE"] = src_filename;
			args["ERROR"] = LLImage::getLastError();
			upload_error(error_message, "ProblemWithFile", filename, args);
			return;
		}
	}
 	else if( exten == "png")
 	{
 		asset_type = LLAssetType::AT_TEXTURE;
 		if (!LLViewerImageList::createUploadFile(src_filename,
 												 filename,
 												 IMG_CODEC_PNG ))
 		{
 			error_message = llformat("Problem with file %s:\n\n%s\n",
 					src_filename.c_str(), LLImage::getLastError().c_str());
 			args["FILE"] = src_filename;
 			args["ERROR"] = LLImage::getLastError();
 			upload_error(error_message, "ProblemWithFile", filename, args);
 			return;
 		}
 	}
	else if(exten == "wav")
	{
		asset_type = LLAssetType::AT_SOUND;  // tag it as audio
		S32 encode_result = 0;

		llinfos << "Attempting to encode wav as an ogg file" << llendl;

		encode_result = encode_vorbis_file(src_filename, filename);
		
		if (LLVORBISENC_NOERR != encode_result)
		{
			switch(encode_result)
			{
				case LLVORBISENC_DEST_OPEN_ERR:
				    error_message = llformat( "Couldn't open temporary compressed sound file for writing: %s\n", filename.c_str());
					args["FILE"] = filename;
					upload_error(error_message, "CannotOpenTemporarySoundFile", filename, args);
					break;

				default:	
				  error_message = llformat("Unknown vorbis encode failure on: %s\n", src_filename.c_str());
					args["FILE"] = src_filename;
					upload_error(error_message, "UnknownVorbisEncodeFailure", filename, args);
					break;	
			}	
			return;
		}
	}
	else if(exten == "tmp")	 	
	{	 	
		// This is a generic .lin resource file	 	
         asset_type = LLAssetType::AT_OBJECT;	 	
         LLFILE* in = LLFile::fopen(src_filename, "rb");		/* Flawfinder: ignore */	 	
         if (in)	 	
         {	 	
                 // read in the file header	 	
                 char buf[16384];		/* Flawfinder: ignore */ 	
                 S32 read;		/* Flawfinder: ignore */	 	
                 S32  version;	 	
                 if (fscanf(in, "LindenResource\nversion %d\n", &version))	 	
                 {	 	
                         if (2 == version)	 	
                         {
								// *NOTE: This buffer size is hard coded into scanf() below.
                                 char label[MAX_STRING];		/* Flawfinder: ignore */	 	
                                 char value[MAX_STRING];		/* Flawfinder: ignore */	 	
                                 S32  tokens_read;	 	
                                 while (fgets(buf, 1024, in))	 	
                                 {	 	
                                         label[0] = '\0';	 	
                                         value[0] = '\0';	 	
                                         tokens_read = sscanf(	/* Flawfinder: ignore */
											 buf,
											 "%254s %254s\n",
											 label, value);	 	

                                         llinfos << "got: " << label << " = " << value	 	
                                                         << llendl;	 	

                                         if (EOF == tokens_read)	 	
                                         {	 	
                                                 fclose(in);	 	
                                                 error_message = llformat("corrupt resource file: %s", src_filename.c_str());
												 args["FILE"] = src_filename;
												 upload_error(error_message, "CorruptResourceFile", filename, args);
                                                 return;
                                         }	 	

                                         if (2 == tokens_read)	 	
                                         {	 	
                                                 if (! strcmp("type", label))	 	
                                                 {	 	
                                                         asset_type = (LLAssetType::EType)(atoi(value));	 	
                                                 }	 	
                                         }	 	
                                         else	 	
                                         {	 	
                                                 if (! strcmp("_DATA_", label))	 	
                                                 {	 	
                                                         // below is the data section	 	
                                                         break;	 	
                                                 }	 	
                                         }	 	
                                         // other values are currently discarded	 	
                                 }	 	

                         }	 	
                         else	 	
                         {	 	
                                 fclose(in);	 	
                                 error_message = llformat("unknown linden resource file version in file: %s", src_filename.c_str());
								 args["FILE"] = src_filename;
								 upload_error(error_message, "UnknownResourceFileVersion", filename, args);
                                 return;
                         }	 	
                 }	 	
                 else	 	
                 {	 	
                         // this is an original binary formatted .lin file	 	
                         // start over at the beginning of the file	 	
                         fseek(in, 0, SEEK_SET);	 	

                         const S32 MAX_ASSET_DESCRIPTION_LENGTH = 256;	 	
                         const S32 MAX_ASSET_NAME_LENGTH = 64;	 	
                         S32 header_size = 34 + MAX_ASSET_DESCRIPTION_LENGTH + MAX_ASSET_NAME_LENGTH;	 	
                         S16     type_num;	 	

                         // read in and throw out most of the header except for the type	 	
                         if (fread(buf, header_size, 1, in) != 1)
						 {
							 llwarns << "Short read" << llendl;
						 }
                         memcpy(&type_num, buf + 16, sizeof(S16));		/* Flawfinder: ignore */	 	
                         asset_type = (LLAssetType::EType)type_num;	 	
                 }	 	

                 // copy the file's data segment into another file for uploading	 	
                 LLFILE* out = LLFile::fopen(filename, "wb");		/* Flawfinder: ignore */	
                 if (out)	 	
                 {	 	
                         while((read = fread(buf, 1, 16384, in)))		/* Flawfinder: ignore */	 	
                         {	 	
							 if (fwrite(buf, 1, read, out) != read)
							 {
								 llwarns << "Short write" << llendl;
							 }
                         }	 	
                         fclose(out);	 	
                 }	 	
                 else	 	
                 {	 	
                         fclose(in);	 	
                         error_message = llformat( "Unable to create output file: %s", filename.c_str());
						 args["FILE"] = filename;
						 upload_error(error_message, "UnableToCreateOutputFile", filename, args);
                         return;
                 }	 	

                 fclose(in);	 	
         }	 	
         else	 	
         {	 	
                 llinfos << "Couldn't open .lin file " << src_filename << llendl;	 	
         }	 	
	}
	else if (exten == "bvh")
	{
		error_message = llformat("We do not currently support bulk upload of animation files\n");
		upload_error(error_message, "DoNotSupportBulkAnimationUpload", filename, args);
		return;
	}
	else
	{
		// Unknown extension
		// *TODO: Translate?
		error_message = llformat("Unknown file extension .%s\nExpected .wav, .tga, .bmp, .jpg, .jpeg, or .bvh", exten.c_str());
		error = TRUE;;
	}

	// gen a new transaction ID for this asset
	tid.generate();

	if (!error)
	{
		uuid = tid.makeAssetID(gAgent.getSecureSessionID());
		// copy this file into the vfs for upload
		S32 file_size;
		LLAPRFile infile ;
		infile.open(filename, LL_APR_RB, LLAPRFile::local, &file_size);
		if (infile.getFileHandle())
		{
			LLVFile file(gVFS, uuid, asset_type, LLVFile::WRITE);

			file.setMaxSize(file_size);

			const S32 buf_size = 65536;
			U8 copy_buf[buf_size];
			while ((file_size = infile.read(copy_buf, buf_size)))
			{
				file.write(copy_buf, file_size);
			}
		}
		else
		{
			error_message = llformat( "Unable to access output file: %s", filename.c_str());
			error = TRUE;
		}
	}

	if (!error)
	{
		std::string t_disp_name = display_name;
		if (t_disp_name.empty())
		{
			t_disp_name = src_filename;
		}
		upload_new_resource(tid, asset_type, name, desc, compression_info, // tid
				    destination_folder_type, inv_type, next_owner_perms, group_perms, everyone_perms,
				    display_name, callback, expected_upload_cost, userdata);
	}
	else
	{
		llwarns << error_message << llendl;
		LLSD args;
		args["ERROR_MESSAGE"] = error_message;
		LLNotifications::instance().add("ErrorMessage", args);
		if(LLFile::remove(filename) == -1)
		{
			lldebugs << "unable to remove temp file" << llendl;
		}
		LLFilePicker::instance().reset();
	}
}
//-----------------------------------------------------------------------------
// loadMotions()
//-----------------------------------------------------------------------------
BOOL LLKeyframeMotionParam::loadMotions()
{
	//-------------------------------------------------------------------------
	// Load named file by concatenating the character prefix with the motion name.
	// Load data into a buffer to be parsed.
	//-------------------------------------------------------------------------
	std::string path = gDirUtilp->getExpandedFilename(LL_PATH_MOTIONS,mCharacter->getAnimationPrefix())
		+ "_" + getName() + ".llp";

	//-------------------------------------------------------------------------
	// open the file
	//-------------------------------------------------------------------------
	S32 fileSize = 0;
	LLAPRFile infile ;
	infile.open(path, LL_APR_R, NULL, &fileSize);
	apr_file_t* fp = infile.getFileHandle() ;
	if (!fp || fileSize == 0)
	{
		llinfos << "ERROR: can't open: " << path << llendl;
		return FALSE;
	}

	// allocate a text buffer
	char *text = new char[ fileSize+1 ];
	if ( !text )
	{
		llinfos << "ERROR: can't allocated keyframe text buffer." << llendl;
		return FALSE;
	}

	//-------------------------------------------------------------------------
	// load data from file into buffer
	//-------------------------------------------------------------------------
	bool error = false;
	char *p = text;
	while ( 1 )
	{
		if (apr_file_eof(fp) == APR_EOF)
		{
			break;
		}
		if (apr_file_gets(p, 1024, fp) != APR_SUCCESS)
		{
			error = true;
			break;
		}
		while ( *(++p) )
			;
	}

	//-------------------------------------------------------------------------
	// close the file
	//-------------------------------------------------------------------------
	infile.close();

	//-------------------------------------------------------------------------
	// check for error
	//-------------------------------------------------------------------------
	llassert( p <= (text+fileSize) );

	if ( error )
	{
		llinfos << "ERROR: error while reading from " << path << llendl;
		delete [] text;
		return FALSE;
	}

	llinfos << "Loading parametric keyframe data for: " << getName() << llendl;

	//-------------------------------------------------------------------------
	// parse the text and build keyframe data structures
	//-------------------------------------------------------------------------
	p = text;
	S32 num;
	char strA[80]; /* Flawfinder: ignore */
	char strB[80]; /* Flawfinder: ignore */
	F32 floatA = 0.0f;


	//-------------------------------------------------------------------------
	// get priority
	//-------------------------------------------------------------------------
	BOOL isFirstMotion = TRUE;
	num = sscanf(p, "%79s %79s %f", strA, strB, &floatA);	/* Flawfinder: ignore */

	while(1)
	{
		if (num == 0 || num == EOF) break;
		if ((num != 3))
		{
			llinfos << "WARNING: can't read parametric motion" << llendl;
			delete [] text;
			return FALSE;
		}

		addKeyframeMotion(strA, gAnimLibrary.stringToAnimState(std::string(strA)), strB, floatA);
		if (isFirstMotion)
		{
			isFirstMotion = FALSE;
			setDefaultKeyframeMotion(strA);
		}
		
		p = strstr(p, "\n");
		if (!p)
		{
			break;
		}
			
		p++;
		num = sscanf(p, "%79s %79s %f", strA, strB, &floatA);	/* Flawfinder: ignore */
	}

	delete [] text;
	return TRUE;
}
Example #26
0
// static
void LLXmlImport::import(LLXmlImportOptions* import_options)
{
	sXmlImportOptions = import_options;
	if(sXmlImportOptions->mSupplier == NULL)
	{
		LLViewerObject* cube = new LLViewerObject(LLUUID::null, 9, NULL, TRUE);
		cube->setScale(LLVector3(.31337f, .31337f, .31337f), FALSE);
		sSupplyParams = cube;
	}
	else sSupplyParams = sXmlImportOptions->mSupplier;

	if(!(sXmlImportOptions->mKeepPosition) && sXmlImportOptions->mRootObjects.size())
	{ // Reposition all roots so that the first root is somewhere near the avatar
		// Find the root closest to the ground
		int num_roots = (int)sXmlImportOptions->mRootObjects.size();
		int lowest_root = 0;
		F32 lowest_z(65536.f);
		for(int i = 0; i < num_roots; i++)
		{
			F32 z = sXmlImportOptions->mRootObjects[i]->getPosition().mV[2];
			if(z < lowest_z)
			{
				lowest_root = i;
				lowest_z = z;
			}
		}
		// Move all roots
		LLVector3 old_pos = sXmlImportOptions->mRootObjects[lowest_root]->getPosition();
		LLVector3 new_pos = gAgent.getPositionAgent() + (gAgent.getAtAxis() * 2.0f);
		LLVector3 difference = new_pos - old_pos;
		for(int i = 0; i < num_roots; i++)
		{
			sXmlImportOptions->mRootObjects[i]->setPosition(sXmlImportOptions->mRootObjects[i]->getPosition() + difference, FALSE);
		}
	}
	// Make the actual importable list
	sPrims.clear();
	// Clear these attachment-related maps
	sPt2watch.clear();
	sId2attachpt.clear();
	sPt2attachpos.clear();
	sPt2attachrot.clear();
	sDescriptions.clear();
	// Go ahead and add roots first
	std::vector<LLImportObject*>::iterator root_iter = sXmlImportOptions->mRootObjects.begin();
	std::vector<LLImportObject*>::iterator root_end = sXmlImportOptions->mRootObjects.end();
	for( ; root_iter != root_end; ++root_iter)
	{
		sPrims.push_back(*root_iter);
		// Remember some attachment info
		if((*root_iter)->importIsAttachment)
		{
			sId2attachpt[(*root_iter)->mId] = (*root_iter)->importAttachPoint;
			sPt2watch[(*root_iter)->importAttachPoint] = true;
			sPt2attachpos[(*root_iter)->importAttachPoint] = (*root_iter)->importAttachPos;
			sPt2attachrot[(*root_iter)->importAttachPoint] = (*root_iter)->importAttachRot;
			sDescriptions[(*root_iter)->importAttachPoint] = (*root_iter)->mPrimDescription;
		}
	}
	// Then add children, nearest first
	std::vector<LLImportObject*> children(sXmlImportOptions->mChildObjects);
	for(root_iter = sXmlImportOptions->mRootObjects.begin() ; root_iter != root_end; ++root_iter)
	{
		while(children.size() > 0)
		{
			std::string rootid = (*root_iter)->mId;
			F32 lowest_mag = 65536.0f;
			std::vector<LLImportObject*>::iterator lowest_child_iter = children.begin();
			LLImportObject* lowest_child = (*lowest_child_iter);
			
			std::vector<LLImportObject*>::iterator child_end = children.end();
			for(std::vector<LLImportObject*>::iterator child_iter = children.begin() ; child_iter != child_end; ++child_iter)
			{
				if((*child_iter)->mParentId == rootid)
				{
					F32 mag = (*child_iter)->getPosition().magVec();
					if(mag < lowest_mag)
					{
						lowest_child_iter = child_iter;
						lowest_child = (*lowest_child_iter);
						lowest_mag = mag;
					}
				}
			}
			sPrims.push_back(lowest_child);
			children.erase(lowest_child_iter);
		}
	}
	
	sImportInProgress = true;
	sImportHasAttachments = (sId2attachpt.size() > 0);
	sPrimsNeeded = (int)sPrims.size();
	sTotalAssets = sXmlImportOptions->mAssets.size();
	sPrimIndex = 0;
	sUploadedAssets = 0;
	sId2localid.clear();
	sRootpositions.clear();
	sRootrotations.clear();
	sLinkSets.clear();

	LLFloaterImportProgress::show();
	LLFloaterImportProgress::update();

	// Create folder
	if((sXmlImportOptions->mWearables.size() > 0) || (sId2attachpt.size() > 0) || (sTotalAssets > 0))
	{
		sFolderID = gInventory.createNewCategory( gInventory.getRootFolderID(), LLFolderType::FT_NONE, sXmlImportOptions->mName);
	}
	if(sXmlImportOptions->mReplaceTexture && sTotalAssets > 0 && !sXmlImportOptions->mAssetDir.empty())
	{
		LLUUID folder_id = gInventory.createNewCategory( sFolderID, LLFolderType::FT_NONE, "Textures");
		//starting up the texture uploading
		LLImportAssetData* data = sXmlImportOptions->mAssets[0];
                data->folderid = folder_id;
		sTextureReplace[data->oldassetid] = data->assetid;
		std::string url = gAgent.getRegion()->getCapability("NewFileAgentInventory");
		if(!url.empty())
		{
			LLPointer<LLImageJ2C> integrity_test = new LLImageJ2C;
			if( !integrity_test->loadAndValidate( data->filename ) )
			{
				llinfos << "Image: " << data->filename << " is corrupt." << llendl;
			}
			S32 file_size;
			LLAPRFile infile ;
			infile.open(data->filename, LL_APR_RB, LLAPRFile::short_lived, &file_size);
			if (infile.getFileHandle())
			{
				LLVFile file(gVFS, data->assetid, data->type, LLVFile::WRITE);
				file.setMaxSize(file_size);
				const S32 buf_size = 65536;
				U8 copy_buf[buf_size];
				while ((file_size = infile.read(copy_buf, buf_size)))
				{
					file.write(copy_buf, file_size);
				}

				LLSD body;
				body["folder_id"] = folder_id;
				body["asset_type"] = LLAssetType::lookup(data->type);
				body["inventory_type"] = LLInventoryType::lookup(data->inv_type);
				body["name"] = data->name;
				body["description"] = data->description;
				body["next_owner_mask"] = LLSD::Integer(U32_MAX);
				body["group_mask"] = LLSD::Integer(U32_MAX);
				body["everyone_mask"] = LLSD::Integer(U32_MAX);
				body["expected_upload_cost"] = LLSD::Integer(LLGlobalEconomy::Singleton::getInstance()->getPriceUpload());
				LLHTTPClient::post(url, body, new LLImportInventoryResponder(body, data->assetid, data->type,data));
			}
		}
		else
		{
			//maybe do legacy upload here?????
			llinfos << "NewFileAgentInventory does not exist!!!!" << llendl;
			LLXmlImport::finish_init();
		}
	}
	else
		LLXmlImport::finish_init();
}
	void fire(const LLUUID &inv_item)
	{
		S32 file_size;
		LLAPRFile infile;
		infile.open(data->filename, LL_APR_RB, LLAPRFile::access_t(), &file_size);
		if (infile.getFileHandle())
		{
			//cmdline_printchat("got file handle @ postinv");
			LLVFile file(gVFS, data->assetid, data->type, LLVFile::WRITE);
			file.setMaxSize(file_size);
			const S32 buf_size = 65536;
			U8 copy_buf[buf_size];
			while ((file_size = infile.read(copy_buf, buf_size)))
			{
				file.write(copy_buf, file_size);
			}
			switch(data->type)
			{
			case LLAssetType::AT_NOTECARD:
				//cmdline_printchat("case notecard @ postinv");
				{
					*//*LLViewerTextEditor* edit = new LLViewerTextEditor("",LLRect(0,0,0,0),S32_MAX,"");
					S32 size = gVFS->getSize(data->assetid, data->type);
					U8* buffer = new U8[size];
					gVFS->getData(data->assetid, data->type, buffer, 0, size);
					edit->setText(LLStringExplicit((char*)buffer));
					std::string card;
					edit->exportBuffer(card);
					cmdline_printchat("Encoded notecard");;
					edit->die();
					delete buffer;
					//buffer = new U8[card.size()];
					//size = card.size();
					//strcpy((char*)buffer,card.c_str());
					file.remove();
					LLVFile newfile(gVFS, data->assetid, data->type, LLVFile::APPEND);
					newfile.setMaxSize(size);
					newfile.write((const U8*)card.c_str(),size);*//*
					//FAIL.



					std::string agent_url = gAgent.getRegion()->getCapability("UpdateNotecardAgentInventory");
					LLSD body;
					body["item_id"] = inv_item;
					//cmdline_printchat("posting content as " + data->assetid.asString());
					LLHTTPClient::post(agent_url, body,
								new JCPostInvUploadResponder(body, data->assetid, data->type,inv_item,data));
				}
				break;
			case LLAssetType::AT_LSL_TEXT:
				//cmdline_printchat("case lsltext @ postinv");
				{
					std::string url = gAgent.getRegion()->getCapability("UpdateScriptAgent");
					LLSD body;
					body["item_id"] = inv_item;
					S32 size = gVFS->getSize(data->assetid, data->type);
					U8* buffer = new U8[size];
					gVFS->getData(data->assetid, data->type, buffer, 0, size);
					std::string script((char*)buffer);
					BOOL domono = FALSE;//Phox- this needs to be fixed when the preproc is added = JCLSLPreprocessor::mono_directive(script);
					*//*if(script.find("//mono\n") != -1)
					{
						domono = TRUE;
					}else if(script.find("//lsl2\n") != -1)
					{
						domono = FALSE;
					}*//*
					delete buffer;
					buffer = 0;
					body["target"] = (domono == TRUE) ? "mono" : "lsl2";
					//cmdline_printchat("posting content as " + data->assetid.asString());
					LLHTTPClient::post(url, body, new JCPostInvUploadResponder(body, data->assetid, data->type,inv_item,data));
				}
				break;
			default:
				break;
			}