Bytes encode(const Unicode& ustring, const Bytes& encoding) { Codec* codec = lookup(encoding); Bytes bstring = codec->encode(bstring); delete codec; return bstring; }
const_byteptr decodeArray(Codec const& codec, Uint *xs, unsigned n, const_byteptr p, const_byteptr end) { if (codec.k_max_bytes * n + p > end) for (unsigned i = 0; i < n; ++i) p = codec.decode(xs[i], p, end); else for (unsigned i = 0; i < n; ++i) p = codec.decode(xs[i], p); return p; }
byteptr encodeArray(Codec const& codec, byteptr p, byteptr end, Uint const* xs, unsigned n) { if (codec.k_max_bytes * n + p > end) for (unsigned i = 0; i < n; ++i) p = codec.encode(p, end, xs[i]); else for (unsigned i = 0; i < n; ++i) p = codec.encode(p, xs[i]); return p; }
int main() { Codec s; vector<int> preorder({1, 2, 4, 3}), inorder({4, 2, 1, 3}); TreeNode *root = buildTree(preorder, inorder); root->print(); cout << s.serialize(root) << endl; TreeNode* node = s.deserialize(s.serialize(root)); node->print(); return 0; }
int main(void) { Codec codec; vector<string> strs = {"", "vn"}; string encoded_string = codec.encode(strs); vector<string> strs2 = codec.decode(encoded_string); assert(strs.size() == strs2.size()); for (size_t i = 0; i < strs.size(); i++) assert(strs[i] == strs2[i]); cout << "\nPassed All\n"; return 0; }
//----------------------------------------------------------------------------- Image & Image::load(DataStreamPtr& stream, const String& type ) { if( m_pBuffer && m_bAutoDelete ) { OGRE_FREE(m_pBuffer, MEMCATEGORY_GENERAL); m_pBuffer = NULL; } Codec * pCodec = 0; if (!type.empty()) { // use named codec pCodec = Codec::getCodec(type); } else { // derive from magic number // read the first 32 bytes or file size, if less size_t magicLen = std::min(stream->size(), (size_t)32); char magicBuf[32]; stream->read(magicBuf, magicLen); // return to start stream->seek(0); pCodec = Codec::getCodec(magicBuf, magicLen); } if( !pCodec ) OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Unable to load image - unable to identify codec. Check file extension " "and file format.", "Image::load" ); Codec::DecodeResult res = pCodec->decode(stream); ImageCodec::ImageData* pData = static_cast<ImageCodec::ImageData*>(res.second.getPointer()); m_uWidth = pData->width; m_uHeight = pData->height; m_uDepth = pData->depth; m_uSize = pData->size; m_uNumMipmaps = pData->num_mipmaps; m_uFlags = pData->flags; // Get the format and compute the pixel size m_eFormat = pData->format; m_ucPixelSize = static_cast<uchar>(PixelUtil::getNumElemBytes( m_eFormat )); // Just use internal buffer of returned memory stream m_pBuffer = res.first->getPtr(); // Make sure stream does not delete res.first->setFreeOnClose(false); return *this; }
int main() { Codec codec; string data = "null"; TreeNode* root = codec.deserialize(data); // print_tree(root); auto ret = codec.serialize(root); cout<<ret<<endl; return 0; }
//----------------------------------------------------------------------------- Image & Image::load(DataStreamPtr& stream, const String& type ) { freeMemory(); Codec * pCodec = 0; if (!type.empty()) { // use named codec pCodec = Codec::getCodec(type); } else { // derive from magic number // read the first 32 bytes or file size, if less size_t magicLen = std::min(stream->size(), (size_t)32); char magicBuf[32]; stream->read(magicBuf, magicLen); // return to start stream->seek(0); pCodec = Codec::getCodec(magicBuf, magicLen); if( !pCodec ) OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Unable to load image: Image format is unknown. Unable to identify codec. " "Check it or specify format explicitly.", "Image::load" ); } Codec::DecodeResult res = pCodec->decode(stream); ImageCodec::ImageData* pData = static_cast<ImageCodec::ImageData*>(res.second.getPointer()); mWidth = pData->width; mHeight = pData->height; mDepth = pData->depth; mBufSize = pData->size; mNumMipmaps = pData->num_mipmaps; mFlags = pData->flags; // Get the format and compute the pixel size mFormat = pData->format; mPixelSize = static_cast<uchar>(PixelUtil::getNumElemBytes( mFormat )); // Just use internal buffer of returned memory stream mBuffer = res.first->getPtr(); // Make sure stream does not delete res.first->setFreeOnClose(false); // make sure we delete mAutoDelete = true; return *this; }
//----------------------------------------------------------------------------- Image & Image::load(const String& strFileName, const String& group) { OgreGuard( "Image::load" ); freeData(); String strExt; size_t pos = strFileName.find_last_of("."); if( pos == String::npos ) OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Unable to load image file '" + strFileName + "' - invalid extension.", "Image::load" ); while( pos != strFileName.length() - 1 ) strExt += strFileName[++pos]; Codec * pCodec = Codec::getCodec(strExt); if( !pCodec ) OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Unable to load image file '" + strFileName + "' - invalid extension.", "Image::load" ); DataStreamPtr encoded = ResourceGroupManager::getSingleton().openResource(strFileName, group); Codec::DecodeResult res = pCodec->decode(encoded); ImageCodec::ImageData* pData = static_cast<ImageCodec::ImageData*>(res.second.getPointer()); // Get the format and compute the pixel size m_uWidth = pData->width; m_uHeight = pData->height; m_uDepth = pData->depth; m_uSize = pData->size; m_eFormat = pData->format; m_uNumMipmaps = pData->num_mipmaps; m_ucPixelSize = PixelUtil::getNumElemBytes( m_eFormat ); m_uFlags = pData->flags; // re-use the decoded buffer m_pBuffer = res.first->getPtr(); // ensure we don't delete when stream is closed res.first->setFreeOnClose(false); OgreUnguardRet( *this ); }
// Your Codec object will be instantiated and called as such: // Codec codec; // codec.decode(codec.encode(strs)); // int main() { Codec codec; vector<string> strs; strs.push_back("hello"); strs.push_back(""); strs.push_back("gaobo"); string coded_str = codec.encode(strs); cout << "coded str: " << coded_str << endl; vector<string> decoded_strs = codec.decode(coded_str); for (int i = 0; i < decoded_strs.size(); i++) { cout << decoded_strs[i] << endl; } return 0; }
void CodecContext::open(const Codec &codec, AVDictionary **options, error_code &ec) { clear_if(ec); if (m_isOpened || !isValid()) { throws_if(ec, m_isOpened ? Errors::CodecAlreadyOpened : Errors::CodecInvalid); return; } int stat = avcodec_open2(m_raw, codec.isNull() ? m_raw->codec : codec.raw(), options); if (stat < 0) throws_if(ec, stat, ffmpeg_category()); else m_isOpened = true; }
AudioStream *ASFStream::createAudioStream() { delete _lastPacket; _lastPacket = readPacket(); // TODO if (_lastPacket->segments.size() != 1) throw Common::Exception("ASFStream::createAudioStream(): Only single segment packets supported"); Packet::Segment &segment = _lastPacket->segments[0]; // We should only have one stream in a ASF audio file if (segment.streamID != _streamID) throw Common::Exception("ASFStream::createAudioStream(): Packet stream ID mismatch"); // TODO if (segment.sequenceNumber != _curSequenceNumber) throw Common::Exception("ASFStream::createAudioStream(): Only one sequence number per packet supported"); // This can overflow and needs to overflow! _curSequenceNumber++; // TODO if (segment.data.size() != 1) throw Common::Exception("ASFStream::createAudioStream(): Packet grouping not supported"); Common::SeekableReadStream *stream = segment.data[0]; if (_codec) return _codec->decodeFrame(*stream); return 0; }
//--------------------------------------------------------------------- String Image::getFileExtFromMagic(DataStreamPtr stream) { // read the first 32 bytes or file size, if less size_t magicLen = std::min(stream->size(), (size_t)32); char magicBuf[32]; stream->read(magicBuf, magicLen); // return to start stream->seek(0); Codec* pCodec = Codec::getCodec(magicBuf, magicLen); if(pCodec) return pCodec->getType(); else return BLANKSTRING; }
void Mixer::remoteStartTransmission(const ::Ice::Current& curr) { stringstream a; stringstream b; LOG4CXX_DEBUG(logger, string("Mixer::remoteStartTransmission()")); IPV4Address *tmpAddr = new IPV4Address(getRemoteAddressFromConnection(curr.con)); a << string("Mixer::remoteStartTransmission() rem hostAddr: ") << tmpAddr->getHostname(); LOG4CXX_DEBUG(logger, a.str()); TerminalInfo *info = remoteHostsM[tmpAddr->getHostname()]; if (remoteHostsM.find(tmpAddr->getHostname()) == remoteHostsM.end() ) { cout << "ERROR info not found\n"; } if (this->currentState != States::PASSIVE_CONNECTED) { LOG4CXX_DEBUG(logger, string("Mixer::remoteStartTransmission() bad state")); } else { changeState(States::PASSIVE_OPERATIONAL); cout << "TRANSCEIVER STARTED\n"; // TODO start RTP.RTCP transmission CodecFactory codecfactory; Codec* codecInc = codecfactory.getCodec(AudioCodec::PCMU); // HACK // Codec* codecInc = codecfactory.getCodec(info->incomingCodec); Codec* codecOut = codecfactory.getCodec(AudioCodec::PCMU); // Codec* codecOut = codecfactory.getCodec(info->outgoingCodec); // HACK info->transport = new TransportCCRTP(); info->transport->setParams(codecInc->getFrameCount(), codecInc->getFrameSize()); info->transport->setLocalEndpoint("0.0.0.0", localRTPPort); info->transport->setRemoteEndpoint(info->address, info->rtpPort); info->buf = new RingBuffer(1024*1024, 1); // b << "Mixer::remoteStartTransmission() creating transport, localRTPPort += 2; stringstream a; a << "rem address: " << info->address << " port: " << info->rtpPort; LOG4CXX_DEBUG(logger, a.str()); info->transport->start(); LOG4CXX_DEBUG(logger, string("Mixer::remoteStartTransmission() transmission started")); } }
bool MainObject::StartCodec() { Codec *codec; if((codec= CodecFactory(sir_config->audioFormat(),sir_ringbuffers[sir_codecs.size()], this))==NULL) { Log(LOG_ERR, QString().sprintf("unsupported codec type \"%s\"", (const char *)Codec::codecTypeText(Codec::TypeMpegL3).toUtf8())); return false; } if(sir_config->audioBitrateQuantity()>0) { codec-> setBitrate(sir_config->audioBitrate(sir_config->audioBitrateQuantity()-1)); } else { codec->setBitrate(0); } codec->setChannels(sir_config->audioChannels()); codec->setQuality(sir_config->audioQuality()); codec->setSourceSamplerate(sir_audio_device->deviceSamplerate()); codec->setStreamSamplerate(sir_config->audioSamplerate()); codec->setCompleteFrames(sir_config->audioAtomicFrames()); sir_codecs.push_back(codec); return sir_codecs.back()->start(); }
int main(int argc, char const *argv[]) { /* code */ TreeNode* n1 = new TreeNode(5); TreeNode* n2 = new TreeNode(4); TreeNode* n3 = new TreeNode(2); n1 -> left = n2; n1 -> right = n3; TreeNode* n4 = new TreeNode(11); n2 ->right = n4; TreeNode* n5 = new TreeNode(7); TreeNode* n6 = new TreeNode(8); n3 -> left = n5; n3 -> right = n6; Codec c; string test = "5,4,#,11,#,#,2,7,#,#,8,#,#,"; //c.dfs(n1); cout << "---------" << endl; c.dfs(c.deserialize(test)); cout << endl; cout << c.serialize(n1)<<endl; cout << test<<endl; c.dfs(c.deserialize(c.serialize(n1))); return 0; }
// Your Codec object will be instantiated and called as such: int main() { Codec codec; TreeNode * root = new TreeNode(1); root->left = new TreeNode(2); root->right = new TreeNode(3); root->right->right = new TreeNode(4); string ss = codec.serialize(root); cout << ss << "\n"; codec.matchedParens("(2,(),())"); TreeNode * p = codec.deserialize(ss); cout << "restored tree: "<< "\n"; InorderIter it(p); while (it.hasNext()) { cout << it.next()->val << " "; } cout << "\n"; }
CodecContext::CodecContext(const Stream2 &st, const Codec &codec) : m_stream(st) { m_raw = st.raw()->codec; Codec c = codec; if (codec.isNull()) { if (st.direction() == Direction::DECODING) c = findDecodingCodec(m_raw->codec_id); else c = findEncodingCodec(m_raw->codec_id); } if (!c.isNull()) setCodec(c); m_direction = st.direction(); }
unique_ptr<folly::IOBuf> getSynStream(Codec& egressCodec, uint32_t streamID, const HTTPMessage& msg, uint32_t assocStreamId = 0, bool eom = false, HTTPHeaderSize* size = nullptr) { folly::IOBufQueue output(folly::IOBufQueue::cacheChainLength()); egressCodec.generateHeader(output, streamID, msg, assocStreamId, eom, size); return output.move(); }
void Multipart::appendTextPart( EString & r, const Bodypart * bp, ContentType * ct ) const { Codec * c = 0; EString::Encoding e = EString::Binary; ContentTransferEncoding * cte = bp->header()->contentTransferEncoding(); if ( cte ) e = cte->encoding(); if ( ct && !ct->parameter( "charset" ).isEmpty() ) c = Codec::byName( ct->parameter( "charset" ) ); if ( !c ) c = Codec::byString( bp->text() ); EString body = c->fromUnicode( bp->text() ); r.append( body.encoded( e, 72 ) ); }
int main(int argc, char const *argv[]) { TreeNode *proot = new TreeNode(-1); proot->left = new TreeNode(0); proot->right = new TreeNode(1); /* proot->left->left = new TreeNode(1); proot->left->right = new TreeNode(4); proot->right->left = new TreeNode(6); proot->right->right = new TreeNode(7); */ Codec s; string xx = s.serialize(proot); cout << xx << endl; cout << s.deserialize(xx) << endl; return 0; }
EString Bodypart::asText( bool avoidUtf8 ) const { EString r; Codec *c = 0; ContentType *ct = header()->contentType(); if ( ct && !ct->parameter( "charset" ).isEmpty() ) c = Codec::byName( ct->parameter( "charset" ) ); if ( !c ) c = new AsciiCodec; if ( !children()->isEmpty() ) appendMultipart( r, avoidUtf8 ); else if ( !header()->contentType() || header()->contentType()->type() == "text" ) r = c->fromUnicode( text() ); else r = d->data.e64( 72 ); return r; }
//----------------------------------------------------------------------------- void Image::save(const String& filename) { if( !mBuffer ) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "No image data loaded", "Image::save"); } String strExt; size_t pos = filename.find_last_of("."); if( pos == String::npos ) OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Unable to save image file '" + filename + "' - invalid extension.", "Image::save" ); while( pos != filename.length() - 1 ) strExt += filename[++pos]; Codec * pCodec = Codec::getCodec(strExt); if( !pCodec ) OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Unable to save image file '" + filename + "' - invalid extension.", "Image::save" ); ImageCodec::ImageData* imgData = OGRE_NEW ImageCodec::ImageData(); imgData->format = mFormat; imgData->height = mHeight; imgData->width = mWidth; imgData->depth = mDepth; imgData->size = mBufSize; imgData->num_mipmaps = mNumMipmaps; // Wrap in CodecDataPtr, this will delete Codec::CodecDataPtr codeDataPtr(imgData); // Wrap memory, be sure not to delete when stream destroyed MemoryDataStreamPtr wrapper(OGRE_NEW MemoryDataStream(mBuffer, mBufSize, false)); pCodec->encodeToFile(wrapper, filename, codeDataPtr); }
CodecContext2::CodecContext2(const Stream &st, const Codec &codec, Direction direction, AVMediaType type) : m_stream(st) { if (st.direction() != direction) throw av::Exception(make_avcpp_error(Errors::CodecInvalidDirection)); if (st.mediaType() != type) throw av::Exception(make_avcpp_error(Errors::CodecInvalidMediaType)); #if !USE_CODECPAR FF_DISABLE_DEPRECATION_WARNINGS auto const codecId = st.raw()->codec->codec_id; FF_ENABLE_DEPRECATION_WARNINGS #else auto const codecId = st.raw()->codecpar->codec_id; #endif Codec c = codec; if (codec.isNull()) { if (st.direction() == Direction::Decoding) c = findDecodingCodec(codecId); else c = findEncodingCodec(codecId); } #if !USE_CODECPAR FF_DISABLE_DEPRECATION_WARNINGS m_raw = st.raw()->codec; if (!c.isNull()) setCodec(c, false, direction, type); FF_ENABLE_DEPRECATION_WARNINGS #else m_raw = avcodec_alloc_context3(c.raw()); if (m_raw) { avcodec_parameters_to_context(m_raw, st.raw()->codecpar); } #endif }
void CodecContext2::open(const Codec &codec, AVDictionary **options, OptionalErrorCode ec) { clear_if(ec); if (isOpened() || !isValid()) { throws_if(ec, isOpened() ? Errors::CodecAlreadyOpened : Errors::CodecInvalid); return; } int stat = avcodec_open2(m_raw, codec.raw(), options); if (stat < 0) throws_if(ec, stat, ffmpeg_category()); }
//---------- Stream::Stream(Codec codec, Direction direction, WriteFunction writeFunction, size_t bufferSize) : codec(codec) , direction(direction) , writeFunction(writeFunction) , buffer(bufferSize) { if (!codec.isValid()) { OFXSQUASH_ERROR << "Please specify a valid codec when initializing a stream"; } else { this->codec = codec; } }
// Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root)); int main() { TreeNode* tl,*tr,*node; TreeNode root(1); tl = root.left = new TreeNode(6); tr = root.right = new TreeNode(2); node = tl->left = new TreeNode(7); tl->right = new TreeNode(5); node->left = new TreeNode(8); node->left->left = new TreeNode(7); node->left->right = new TreeNode(9); //root.right = new TreeNode(1); //root.right->right = new TreeNode(1115); Codec s; TreeNode* tmp = s.deserialize(s.serialize(&root)); deque<TreeNode*> myqueue,tmpq; myqueue.push_back(tmp); while (!myqueue.empty()) { while(!myqueue.empty()) { TreeNode* t = myqueue.front(); cout<<t->val<<" "; myqueue.pop_front(); if (t->left != NULL) { tmpq.push_back(t->left); } if (t->right != NULL) { tmpq.push_back(t->right); } } cout<<endl; swap(myqueue, tmpq); } return 0; }
//----------------------------------------------------------------------------- Image & Image::load(DataStreamPtr& stream, const String& type ) { OgreGuard( "Image::load" ); freeData(); String strType = type; Codec * pCodec = Codec::getCodec(strType); if( !pCodec ) OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Unable to load image - invalid extension.", "Image::load" ); Codec::DecodeResult res = pCodec->decode(stream); ImageCodec::ImageData* pData = static_cast<ImageCodec::ImageData*>(res.second.getPointer()); m_uWidth = pData->width; m_uHeight = pData->height; m_uDepth = pData->depth; m_uSize = pData->size; m_uNumMipmaps = pData->num_mipmaps; m_uFlags = pData->flags; // Get the format and compute the pixel size m_eFormat = pData->format; m_ucPixelSize = PixelUtil::getNumElemBytes( m_eFormat ); // Just use internal buffer of returned memory stream m_pBuffer = res.first->getPtr(); // Make sure stream does not delete res.first->setFreeOnClose(false); OgreUnguardRet( *this ); }
bool compress(Codec& codec) { cout << "Compressing with " << codec.getName() << "..." << endl; compressedBufferSize = codec.getMaxCompressedSize(); compressedBuffer = new char[compressedBufferSize]; Timer timer; bool ok = codec.compress(); double compressionTime = timer.query(); if (!ok) { cout << "ERROR: Could not compress" << endl; return false; } double mbps = static_cast<double>(originalSize) / MEGABYTE / compressionTime; double compressionRatio = static_cast<double>(compressedSize) / static_cast<double>(originalSize) * 100.0; cout << "Compressed in " << compressionTime << " s, " << mbps << " MB/s" << endl; cout << "Compressed size: " << static_cast<double>(compressedSize) / MEGABYTE << " MB (" << compressedSize / KILOBYTE << " KB)" << endl; cout << "Compression ratio: " << compressionRatio << "%" << endl; return true; }
Stream FormatContext::addStream(const Codec &codec, OptionalErrorCode ec) { clear_if(ec); if (!m_raw) { throws_if(ec, Errors::Unallocated); return Stream(); } if (!outputFormat().codecSupported(codec)) { throws_if(ec, Errors::FormatCodecUnsupported); return Stream(); } auto rawcodec = codec.raw(); AVStream *st = nullptr; st = avformat_new_stream(m_raw, rawcodec); if (!st) { throws_if(ec, Errors::FormatCantAddStream); return Stream(); } auto stream = Stream(m_monitor, st, Direction::Encoding); #if !USE_CODECPAR FF_DISABLE_DEPRECATION_WARNINGS if (st->codec) { if (outputFormat().isFlags(AVFMT_GLOBALHEADER)) { st->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; } } FF_ENABLE_DEPRECATION_WARNINGS #endif return stream; }