void TestViterbiDecodingSamples() { { std::vector<int> polynomials; polynomials.push_back(7); polynomials.push_back(5); ViterbiCodec codec(3, polynomials); TestViterbiDecoding(codec, "0011100001100111111000101100111011", "010111001010001"); // Inject 1 error bit. TestViterbiDecoding(codec, "0011100001100111110000101100111011", "010111001010001"); } { std::vector<int> polynomials; polynomials.push_back(7); polynomials.push_back(6); ViterbiCodec codec(3, polynomials); TestViterbiDecoding(codec, "1011010100110000", "101100"); } { std::vector<int> polynomials; polynomials.push_back(6); polynomials.push_back(5); ViterbiCodec codec(3, polynomials); TestViterbiDecoding(codec, "011011011101101011", "1001101"); // Inject 2 error bits. TestViterbiDecoding(codec, "111011011100101011", "1001101"); } { std::vector<int> polynomials; polynomials.push_back(91); polynomials.push_back(117); polynomials.push_back(121); ViterbiCodec codec(7, polynomials); TestViterbiDecoding(codec, "111100101110001011110101111111001011100111", "10110111"); // Inject 4 error bits. TestViterbiDecoding(codec, "100100101110001011110101110111001011100110", "10110111"); } }
/*! Serialize the account information to the current group of the given QSettings file \a conf. \sa readSettings() */ void AccountConfiguration::saveSettings(QSettings *conf) const { conf->setValue("name", _userName ); conf->setValue("email", _emailAddress ); conf->setValue("mailuser", _mailUserName ); { QMailBase64Codec codec(QMailBase64Codec::Text); QByteArray encoded = codec.encode(_mailPassword, "ISO-8859-1"); QString plain; plain = QString::fromLatin1(encoded.constData(), encoded.length()); conf->setValue("mailpasswordobs", plain); } conf->setValue("mailserver", _mailServer ); conf->setValue("mailport", _mailPort); conf->setValue("basefolder", _baseFolder); conf->setValue("smtpserver", _smtpServer ); conf->setValue("smtpport", _smtpPort); #ifndef QT_NO_OPENSSL conf->setValue("smtpUsername",_smtpUsername); { QMailBase64Codec codec(QMailBase64Codec::Text); QByteArray encoded = codec.encode(_smtpPassword, "ISO-8859-1"); QString plain; plain = QString::fromLatin1(encoded.constData(), encoded.length()); conf->setValue("smtpPasswordObs", plain); } conf->setValue("smtpAuthentication",_smtpAuthentication); conf->setValue("smtpEncryption",_smtpEncryption); conf->setValue("mailEncryption",_mailEncryption); #endif conf->setValue("usesig", _useSig); conf->setValue("maxmailsize", _maxMailSize); conf->setValue("checkinterval", _checkInterval); conf->setValue("intervalCheckRoamingEnabled", _intervalCheckRoamingEnabled); conf->setValue("pushEnabled", _pushEnabled); conf->remove("defaultmailserver"); if (_useSig) { QString path = Qtopia::applicationFileName("qtopiamail", "") + "sig_" + QString::number(_id.toULongLong()); QFile file(path); if ( file.open(QIODevice::WriteOnly) ) { // file opened successfully QTextStream t( &file ); // use a text stream t << _sig; file.close(); } } conf->setValue("synchronize", _synchronize); conf->setValue("deletemail", _deleteMail); conf->setValue("networkConfig", _networkCfg); conf->setValue("autoDownload", _autoDL); }
static QByteArray encode(const QByteArray& input, QMailMessageBody::TransferEncoding encoding) { if (encoding == QMailMessageBody::Base64) { QMailBase64Codec codec(QMailBase64Codec::Text); return codec.encode(input); } else if (encoding == QMailMessageBody::QuotedPrintable) { QMailQuotedPrintableCodec codec(QMailQuotedPrintableCodec::Text, QMailQuotedPrintableCodec::Rfc2045); return codec.encode(input); } return input; }
SkAndroidCodec* SkAndroidCodec::NewFromStream(SkStream* stream, SkPngChunkReader* chunkReader) { SkAutoTDelete<SkCodec> codec(SkCodec::NewFromStream(stream, chunkReader)); if (nullptr == codec) { return nullptr; } switch (codec->getEncodedFormat()) { #ifdef SK_CODEC_DECODES_PNG case kPNG_SkEncodedFormat: case kICO_SkEncodedFormat: #endif #ifdef SK_CODEC_DECODES_JPEG case kJPEG_SkEncodedFormat: #endif #ifdef SK_CODEC_DECODES_GIF case kGIF_SkEncodedFormat: #endif case kBMP_SkEncodedFormat: case kWBMP_SkEncodedFormat: return new SkSampledCodec(codec.detach()); #ifdef SK_CODEC_DECODES_WEBP case kWEBP_SkEncodedFormat: return new SkWebpAdapterCodec((SkWebpCodec*) codec.detach()); #endif #ifdef SK_CODEC_DECODES_RAW case kRAW_SkEncodedFormat: return new SkRawAdapterCodec((SkRawCodec*)codec.detach()); #endif default: return nullptr; } }
static void test_dimensions(skiatest::Reporter* r, const char path[]) { // Create the codec from the resource file SkAutoTDelete<SkStream> stream(resource(path)); if (!stream) { SkDebugf("Missing resource '%s'\n", path); return; } SkAutoTDelete<SkAndroidCodec> codec(SkAndroidCodec::NewFromStream(stream.detach())); if (!codec) { ERRORF(r, "Unable to create codec '%s'", path); return; } // Check that the decode is successful for a variety of scales for (int sampleSize = 1; sampleSize < 32; sampleSize++) { // Scale the output dimensions SkISize scaledDims = codec->getSampledDimensions(sampleSize); SkImageInfo scaledInfo = codec->getInfo() .makeWH(scaledDims.width(), scaledDims.height()) .makeColorType(kN32_SkColorType); // Set up for the decode size_t rowBytes = scaledDims.width() * sizeof(SkPMColor); size_t totalBytes = scaledInfo.getSafeSize(rowBytes); SkAutoTMalloc<SkPMColor> pixels(totalBytes); SkAndroidCodec::AndroidOptions options; options.fSampleSize = sampleSize; SkCodec::Result result = codec->getAndroidPixels(scaledInfo, pixels.get(), rowBytes, &options); REPORTER_ASSERT(r, SkCodec::kSuccess == result); } }
void LLFloaterBuyCurrencyHTML::navigateToFinalURL() { // URL for actual currency buy contents is in XUI file std::string buy_currency_url = getString( "buy_currency_url" ); // replace [LANGUAGE] meta-tag with view language LLStringUtil::format_map_t replace; // viewer language replace[ "[LANGUAGE]" ] = LLUI::getLanguage(); // flag that specific amount requested replace[ "[SPECIFIC_AMOUNT]" ] = ( mSpecificSumRequested ? "y":"n" ); // amount requested std::ostringstream codec( "" ); codec << mSum; replace[ "[SUM]" ] = codec.str(); // users' current balance codec.clear(); codec.str( "" ); codec << gStatusBar->getBalance(); replace[ "[BAL]" ] = codec.str(); // message - "This cost L$x,xxx for example replace[ "[MSG]" ] = LLURI::escape( mMessage ); LLStringUtil::format( buy_currency_url, replace ); // write final URL to debug console llinfos << "Buy currency HTML prased URL is " << buy_currency_url << llendl; // kick off the navigation mBrowser->navigateTo( buy_currency_url, "text/html" ); }
bool get_bitmap(sk_sp<SkData> fileBits, DiffResource& resource, bool sizeOnly) { SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(fileBits)); if (!codec) { SkDebugf("ERROR: could not create codec for <%s>\n", resource.fFullPath.c_str()); resource.fStatus = DiffResource::kCouldNotDecode_Status; return false; } if (!resource.fBitmap.setInfo(codec->getInfo().makeColorType(kN32_SkColorType))) { SkDebugf("ERROR: could not set bitmap info for <%s>\n", resource.fFullPath.c_str()); resource.fStatus = DiffResource::kCouldNotDecode_Status; return false; } if (sizeOnly) { return true; } if (!resource.fBitmap.tryAllocPixels()) { SkDebugf("ERROR: could not allocate pixels for <%s>\n", resource.fFullPath.c_str()); resource.fStatus = DiffResource::kCouldNotDecode_Status; return false; } if (SkCodec::kSuccess != codec->getPixels(resource.fBitmap.info(), resource.fBitmap.getPixels(), resource.fBitmap.rowBytes())) { SkDebugf("ERROR: codec failed for basePath <%s>\n", resource.fFullPath.c_str()); resource.fStatus = DiffResource::kCouldNotDecode_Status; return false; } resource.fStatus = DiffResource::kDecoded_Status; return true; }
void PlayerSubtitle::onPlayerStart() { if (!m_enabled) return; if (!autoLoad()) { if (m_file == m_sub->fileName()) return; m_sub->setFileName(m_file); m_sub->setFuzzyMatch(false); if (m_file.isEmpty()) { const int n = m_player->currentSubtitleStream(); if (n >= 0 && !m_tracks.isEmpty() && m_tracks.size() <= n) { m_sub->processHeader(QByteArray(), QByteArray()); // reset return; } QVariantMap track = m_tracks[n].toMap(); QByteArray codec(track.value("codec").toByteArray()); QByteArray data(track.value("extra").toByteArray()); m_sub->processHeader(codec, data); } else { m_sub->loadAsync(); } return; } if (m_file != m_sub->fileName()) return; if (!m_player) return; // autoLoad was false then reload then true then reload // previous loaded is user selected subtitle m_sub->setFileName(getSubtitleBasePath(m_player->file())); m_sub->setFuzzyMatch(true); m_sub->loadAsync(); return; }
void EntityEditor::submitChanges() { if (mRootAdapter->hasChanges()) { Atlas::Message::Element rootElement = mRootAdapter->getSelectedChangedElements(); if (rootElement.isMap()) { std::map<std::string, ::Atlas::Message::Element> attributes(rootElement.asMap()); if (attributes.size()) { std::stringstream ss; Atlas::Message::QueuedDecoder decoder; Atlas::Codecs::XML codec(ss, decoder); Atlas::Formatter formatter(ss, codec); Atlas::Message::Encoder encoder(formatter); formatter.streamBegin(); encoder.streamMessageElement(attributes); formatter.streamEnd(); S_LOG_VERBOSE("Sending attribute update to server:\n" << ss.str()); EmberServices::getSingleton().getServerService().setAttributes(&mEntity, attributes); } } } }
int main( int argc, char* argv[] ) { //! [Creating a Convolutional code] //! [Creating a Convolutional code structure] //! [Creating a trellis] /* We are creating a trellis structure with 1 input bit. The constraint length is 4, which means there are 3 registers associated with the input bit. There are two output bits, the first one with generator 4 (in octal) associated with the input bit. */ fec::Trellis trellis({4}, {{013, 017}}, {015}); //! [Creating a trellis] /* The trellis is used to create a code structure. We specify that one bloc will conatins 1024 branches before being terminated. */ auto options = fec::Convolutional::Options(trellis, 1024); options.termination(fec::Convolutional::Tail); options.algorithm(fec::Approximate); //! [Creating a Convolutional code structure] /* A code is created and ready to operate */ std::unique_ptr<fec::Codec> codec(new fec::Convolutional(options)); //! [Creating a Convolutional code] std::cout << per(codec, 3.0) << std::endl; return 0; }
/*! Returns the string \a value encoded into base-64 encoded form. */ QString QMailServiceConfiguration::encodeValue(const QString &value) { // TODO: Shouldn't this be UTF-8? QMailBase64Codec codec(QMailBase64Codec::Text); QByteArray encoded(codec.encode(value, "ISO-8859-1")); return QString::fromLatin1(encoded.constData(), encoded.length()); }
void ColorCodecBench::decodeAndXformQCMS() { SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(fEncoded)); #ifdef SK_DEBUG const SkCodec::Result result = #endif codec->startScanlineDecode(fSrcInfo); SkASSERT(SkCodec::kSuccess == result); SkAutoTCallVProc<qcms_profile, qcms_profile_release> srcSpace(qcms_profile_from_memory(fSrcData->data(), fSrcData->size())); SkASSERT(srcSpace); SkAutoTCallVProc<qcms_transform, qcms_transform_release> transform (qcms_transform_create(srcSpace, QCMS_DATA_RGBA_8, fDstSpaceQCMS.get(), QCMS_DATA_RGBA_8, QCMS_INTENT_PERCEPTUAL)); SkASSERT(transform); #ifdef SK_PMCOLOR_IS_RGBA qcms_output_type outType = QCMS_OUTPUT_RGBX; #else qcms_output_type outType = QCMS_OUTPUT_BGRX; #endif void* dst = fDst.get(); for (int y = 0; y < fSrcInfo.height(); y++) { #ifdef SK_DEBUG const int rows = #endif codec->getScanlines(fSrc.get(), 1, 0); SkASSERT(1 == rows); qcms_transform_data_type(transform, fSrc.get(), dst, fSrcInfo.width(), outType); dst = SkTAddOffset<void>(dst, fDstInfo.minRowBytes()); } }
void ColorCodecBench::onDelayedSetup() { SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(fEncoded)); fSrcData = codec->getICCData(); sk_sp<SkData> dstData = SkData::MakeFromFileName( GetResourcePath("icc_profiles/HP_ZR30w.icc").c_str()); SkASSERT(dstData); fDstSpace = nullptr; #if defined(SK_TEST_QCMS) if (FLAGS_qcms) { fDstSpaceQCMS.reset(FLAGS_srgb ? qcms_profile_sRGB() : qcms_profile_from_memory(dstData->data(), dstData->size())); SkASSERT(fDstSpaceQCMS); // This call takes a non-trivial amount of time, but I think it's the most fair to // treat it as overhead. It only needs to happen once. qcms_profile_precache_output_transform(fDstSpaceQCMS); } else #endif { fDstSpace = FLAGS_srgb ? SkColorSpace::MakeNamed(SkColorSpace::kSRGB_Named) : SkColorSpace::MakeICC(dstData->data(), dstData->size()); SkASSERT(fDstSpace); } fSrcInfo = codec->getInfo().makeColorType(kRGBA_8888_SkColorType); fDstInfo = fSrcInfo; if (FLAGS_half) { fDstInfo = fDstInfo.makeColorType(kRGBA_F16_SkColorType); SkASSERT(SkColorSpace_Base::Type::kXYZ == as_CSB(fDstSpace)->type()); fDstSpace = static_cast<SkColorSpace_XYZ*>(fDstSpace.get())->makeLinearGamma(); } if (FLAGS_nonstd) { SkColorSpaceTransferFn gamma; gamma.fA = 1.0f; gamma.fB = gamma.fC = gamma.fD = gamma.fE = gamma.fF = 0.0f; gamma.fG = 4.0f; SkMatrix44 matrix = SkMatrix44(SkMatrix44::kUninitialized_Constructor); matrix.set3x3(0.30f, 0.31f, 0.28f, 0.32f, 0.33f, 0.29f, 0.27f, 0.30f, 0.30f); fDstSpace = SkColorSpace::MakeRGB(gamma, matrix); } fDstInfo = fDstInfo.makeColorSpace(fDstSpace); fDst.reset(fDstInfo.getSafeSize(fDstInfo.minRowBytes())); if (FLAGS_xform_only) { fSrc.reset(fSrcInfo.getSafeSize(fSrcInfo.minRowBytes())); codec->getPixels(fSrcInfo, fSrc.get(), fSrcInfo.minRowBytes()); } #if defined(SK_TEST_QCMS) else if (FLAGS_qcms) { // Set-up a row buffer to decode into before transforming to dst. fSrc.reset(fSrcInfo.minRowBytes()); } #endif }
SkCodec* SkCodec::NewFromStream(SkStream* stream) { if (!stream) { return NULL; } SkAutoTDelete<SkStream> streamDeleter(stream); SkAutoTDelete<SkCodec> codec(NULL); for (uint32_t i = 0; i < SK_ARRAY_COUNT(gDecoderProcs); i++) { DecoderProc proc = gDecoderProcs[i]; const bool correctFormat = proc.IsFormat(stream); if (!stream->rewind()) { return NULL; } if (correctFormat) { codec.reset(proc.NewFromStream(streamDeleter.detach())); break; } } // Set the max size at 128 megapixels (512 MB for kN32). // This is about 4x smaller than a test image that takes a few minutes for // dm to decode and draw. const int32_t maxSize = 1 << 27; if (codec && codec->getInfo().width() * codec->getInfo().height() > maxSize) { SkCodecPrintf("Error: Image size too large, cannot decode.\n"); return NULL; } else { return codec.detach(); } }
int main(int argc, char **argv) { struct stat sbuf; const char *fname = "test.jpg"; FlowImage image("image"); if (stat(fname, &sbuf)) toast("stat error"); printf("file has %d bytes.\n", sbuf.st_size); if (sbuf.st_size <= 0) toast("file has zero size.\n"); image.set_data_size(sbuf.st_size); FILE *f = fopen(fname, "rb"); int num_read = fread(image.data, 1, sbuf.st_size, f); if (num_read != sbuf.st_size) toast("couldn't read entire file\n"); printf("read %d bytes\n", num_read); image.compression = "jpeg"; image.colorspace = "rgb24"; image.width = 200; image.height = 153; ImageCodec<FlowImage> codec(&image); uint8_t *raster; if (!(raster = codec.get_raster())) printf("couldn't get raster\n"); else { printf("got raster of %d bytes\n", codec.get_raster_size()); codec.write_file("out.ppm"); codec.write_file("out.jpg", 5); } return 0; }
TEST(TextCodecLatin1Test, QuestionMarksAndSurrogates) { WTF::TextEncoding encoding("windows-1252"); std::unique_ptr<WTF::TextCodec> codec(newTextCodec(encoding)); { const LChar testCase[] = {0xd1, 0x16, 0x86}; size_t testCaseSize = WTF_ARRAY_LENGTH(testCase); CString result = codec->encode(testCase, testCaseSize, WTF::QuestionMarksForUnencodables); EXPECT_STREQ("\xd1\x16?", result.data()); } { const UChar testCase[] = {0xd9f0, 0xdcd9}; size_t testCaseSize = WTF_ARRAY_LENGTH(testCase); CString result = codec->encode(testCase, testCaseSize, WTF::QuestionMarksForUnencodables); EXPECT_STREQ("?", result.data()); } { const UChar testCase[] = {0xd9f0, 0xdcd9, 0xd9f0, 0xdcd9}; size_t testCaseSize = WTF_ARRAY_LENGTH(testCase); CString result = codec->encode(testCase, testCaseSize, WTF::QuestionMarksForUnencodables); EXPECT_STREQ("??", result.data()); } }
bool SciDoc::save(QString& error) { // LOGGER; if ( isNoname() ) { error = "This is a Noname file and shouldn't be saved directly"; return false; } if ( MainSettings::get(MainSettings::StripTrailingSpaces) ) stripTrailingSpaces(); bool result; stopWatcher(); QFile file(fileName()); if ( file.open(QIODevice::WriteOnly) ) { QString text(""); text = int_->edit1_->text(); file.write(codec()->fromUnicode(text)); file.close(); // Document::save(error); int_->edit1_->setModified(false); result = true; } else { error = tr("Can't open file for writing"); result = false; } startWatcher(); return result; }
DEF_TEST(BadImage, reporter) { const char* const badImages [] = { "sigabort_favicon.ico", "sigsegv_favicon.ico", "sigsegv_favicon_2.ico", "ico_leak01.ico", "ico_fuzz0.ico", "ico_fuzz1.ico", "skbug3442.webp", "skbug3429.webp", }; const char* badImagesFolder = "invalid_images"; for (size_t i = 0; i < SK_ARRAY_COUNT(badImages); ++i) { SkString resourcePath = SkOSPath::Join(badImagesFolder, badImages[i]); SkAutoTDelete<SkStream> stream(GetResourceAsStream(resourcePath.c_str())); SkAutoTDelete<SkCodec> codec(SkCodec::NewFromStream(stream.release())); // These images are corrupt. It's not important whether we succeed/fail in codec // creation or decoding. We just want to make sure that we don't crash. if (codec) { SkBitmap bm; bm.allocPixels(codec->getInfo()); codec->getPixels(codec->getInfo(), bm.getPixels(), bm.rowBytes()); } } }
TextFile::ReadResult TextFile::read(const QString &fileName, QString *plainText, QString *errorString) { d->m_readResult = Utils::TextFileFormat::readFile(fileName, codec(), plainText, &d->m_format, errorString, &d->m_decodingErrorSample); return d->m_readResult; }
// SkCodec's wbmp decoder was initially more restrictive than SkImageDecoder. // It required the second byte to be zero. But SkImageDecoder allowed a couple // of bits to be 1 (so long as they do not overlap with 0x9F). Test that // SkCodec now supports an image with these bits set. DEF_TEST(Codec_wbmp, r) { const char* path = "mandrill.wbmp"; SkAutoTDelete<SkStream> stream(resource(path)); if (!stream) { SkDebugf("Missing resource '%s'\n", path); return; } // Modify the stream to contain a second byte with some bits set. SkAutoTUnref<SkData> data(SkCopyStreamToData(stream)); uint8_t* writeableData = static_cast<uint8_t*>(data->writable_data()); writeableData[1] = static_cast<uint8_t>(~0x9F); // SkImageDecoder supports this. SkBitmap bitmap; REPORTER_ASSERT(r, SkImageDecoder::DecodeMemory(data->data(), data->size(), &bitmap)); // So SkCodec should, too. SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(data)); REPORTER_ASSERT(r, codec); if (!codec) { return; } test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr); }
static inline void emulateSingleFrameBroadcastTransfer(CanDriver& can, uavcan::NodeID node_id, const MessageType& message, uavcan::TransferID tid) { uavcan::StaticTransferBuffer<100> buffer; uavcan::BitStream bitstream(buffer); uavcan::ScalarCodec codec(bitstream); // Manual message publication ASSERT_LT(0, MessageType::encode(message, codec)); ASSERT_GE(8, buffer.getMaxWritePos()); // DataTypeID data_type_id, TransferType transfer_type, NodeID src_node_id, NodeID dst_node_id, // uint_fast8_t frame_index, TransferID transfer_id, bool last_frame uavcan::Frame frame(MessageType::DefaultDataTypeID, uavcan::TransferTypeMessageBroadcast, node_id, uavcan::NodeID::Broadcast, tid); frame.setStartOfTransfer(true); frame.setEndOfTransfer(true); ASSERT_EQ(buffer.getMaxWritePos(), frame.setPayload(buffer.getRawPtr(), buffer.getMaxWritePos())); uavcan::CanFrame can_frame; ASSERT_TRUE(frame.compile(can_frame)); can.pushRxToAllIfaces(can_frame); }
EncodeView() { fBitmapCount = SK_ARRAY_COUNT(gColorTypes); fBitmaps = new SkBitmap[fBitmapCount]; fEncodedPNGs = new SkAutoDataUnref[fBitmapCount]; fEncodedJPEGs = new SkAutoDataUnref[fBitmapCount]; for (int i = 0; i < fBitmapCount; i++) { make_image(&fBitmaps[i], gColorTypes[i], i); for (size_t j = 0; j < SK_ARRAY_COUNT(gTypes); j++) { SkAutoTDelete<SkImageEncoder> codec( SkImageEncoder::Create(gTypes[j])); if (NULL == codec.get()) { SkDebugf("[%s:%d] failed to encode %s%s\n", __FILE__, __LINE__,gConfigLabels[i], gExt[j]); continue; } SkAutoDataUnref data(codec->encodeData(fBitmaps[i], 100)); if (NULL == data.get()) { SkDebugf("[%s:%d] failed to encode %s%s\n", __FILE__, __LINE__,gConfigLabels[i], gExt[j]); continue; } if (SkImageEncoder::kJPEG_Type == gTypes[j]) { fEncodedJPEGs[i].reset(data.detach()); } else if (SkImageEncoder::kPNG_Type == gTypes[j]) { fEncodedPNGs[i].reset(data.detach()); } } } this->setBGColor(0xFFDDDDDD); }
static void test_dimensions(skiatest::Reporter* r, const char path[]) { // Create the codec from the resource file SkAutoTDelete<SkStream> stream(resource(path)); if (!stream) { SkDebugf("Missing resource '%s'\n", path); return; } SkAutoTDelete<SkCodec> codec(SkCodec::NewFromStream(stream.detach())); if (!codec) { ERRORF(r, "Unable to create codec '%s'", path); return; } // Check that the decode is successful for a variety of scales for (float scale = -0.05f; scale < 2.0f; scale += 0.05f) { // Scale the output dimensions SkISize scaledDims = codec->getScaledDimensions(scale); SkImageInfo scaledInfo = codec->getInfo().makeWH(scaledDims.width(), scaledDims.height()); // Set up for the decode size_t rowBytes = scaledDims.width() * sizeof(SkPMColor); size_t totalBytes = scaledInfo.getSafeSize(rowBytes); SkAutoTMalloc<SkPMColor> pixels(totalBytes); SkImageGenerator::Result result = codec->getPixels(scaledInfo, pixels.get(), rowBytes, NULL, NULL, NULL); REPORTER_ASSERT(r, SkImageGenerator::kSuccess == result); } }
void KDocumentTextBuffer::checkConsistency() { QString bufferContents = codec()->toUnicode( slice(0, length())->text() ); QString documentContents = kDocument()->text(); if ( bufferContents != documentContents ) { KUrl url = kDocument()->url(); kDocument()->setModified(false); kDocument()->setReadWrite(false); m_aboutToClose = true; QTemporaryFile f; f.setAutoRemove(false); f.open(); f.close(); kDocument()->saveAs(f.fileName()); KDialog* dialog = new KDialog; dialog->setButtons(KDialog::Ok | KDialog::Cancel); QLabel* label = new QLabel(i18n("Sorry, an internal error occurred in the text synchronization component.<br>" "You can try to reload the document or disconnect.")); label->setWordWrap(true); dialog->setMainWidget(label); dialog->button(KDialog::Ok)->setText(i18n("Reload document")); dialog->button(KDialog::Cancel)->setText(i18n("Disconnect")); DocumentReopenHelper* helper = new DocumentReopenHelper(url, kDocument()); connect(dialog, SIGNAL(accepted()), helper, SLOT(reopen())); // We must not use exec() here, since that will create a nested event loop, // which might handle incoming network events. This can easily get very messy. dialog->show(); } }
DEF_TEST(Codec_jpeg_rewind, r) { const char* path = "mandrill_512_q075.jpg"; SkAutoTDelete<SkStream> stream(resource(path)); if (!stream) { SkDebugf("Missing resource '%s'\n", path); return; } SkAutoTDelete<SkAndroidCodec> codec(SkAndroidCodec::NewFromStream(stream.release())); if (!codec) { ERRORF(r, "Unable to create codec '%s'.", path); return; } const int width = codec->getInfo().width(); const int height = codec->getInfo().height(); size_t rowBytes = sizeof(SkPMColor) * width; SkAutoMalloc pixelStorage(height * rowBytes); // Perform a sampled decode. SkAndroidCodec::AndroidOptions opts; opts.fSampleSize = 12; codec->getAndroidPixels(codec->getInfo().makeWH(width / 12, height / 12), pixelStorage.get(), rowBytes, &opts); // Rewind the codec and perform a full image decode. SkCodec::Result result = codec->getPixels(codec->getInfo(), pixelStorage.get(), rowBytes); REPORTER_ASSERT(r, SkCodec::kSuccess == result); }
void sniff(const void* ptr, size_t len) { SkMD5 md5; md5.write(ptr, len); SkMD5::Digest digest; md5.finish(digest); if (gSeen.contains(digest)) { return; } gSeen.add(digest); SkAutoTUnref<SkData> data(SkData::NewWithoutCopy(ptr, len)); SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(data)); if (!codec) { // FIXME: This code is currently unreachable because we create an empty generator when // we fail to create a codec. SkDebugf("Codec could not be created for %s\n", skpName.c_str()); gSkpToUnknownCount[skpName]++; return; } SkString ext; switch (codec->getEncodedFormat()) { case SkEncodedFormat::kBMP_SkEncodedFormat: ext = "bmp"; break; case SkEncodedFormat::kGIF_SkEncodedFormat: ext = "gif"; break; case SkEncodedFormat::kICO_SkEncodedFormat: ext = "ico"; break; case SkEncodedFormat::kJPEG_SkEncodedFormat: ext = "jpg"; break; case SkEncodedFormat::kPNG_SkEncodedFormat: ext = "png"; break; case SkEncodedFormat::kDNG_SkEncodedFormat: ext = "dng"; break; case SkEncodedFormat::kWBMP_SkEncodedFormat: ext = "wbmp"; break; case SkEncodedFormat::kWEBP_SkEncodedFormat: ext = "webp"; break; default: // This should be unreachable because we cannot create a codec if we do not know // the image type. SkASSERT(false); } if (FLAGS_testDecode) { SkBitmap bitmap; SkImageInfo info = codec->getInfo().makeColorType(kN32_SkColorType); bitmap.allocPixels(info); if (SkCodec::kSuccess != codec->getPixels(info, bitmap.getPixels(), bitmap.rowBytes())) { SkDebugf("Decoding failed for %s\n", skpName.c_str()); gSkpToUnknownCount[skpName]++; return; } } if (FLAGS_writeImages) { SkString path; path.appendf("%s/%d.%s", gOutputDir, gKnown, ext.c_str()); SkFILEWStream file(path.c_str()); file.write(ptr, len); SkDebugf("%s\n", path.c_str()); } gKnown++; }
SkCodec* SkCodec::NewFromStream(SkStream* stream, SkPngChunkReader* chunkReader) { if (!stream) { return nullptr; } SkAutoTDelete<SkStream> streamDeleter(stream); // 14 is enough to read all of the supported types. const size_t bytesToRead = 14; SkASSERT(bytesToRead <= MinBufferedBytesNeeded()); char buffer[bytesToRead]; size_t bytesRead = stream->peek(buffer, bytesToRead); // It is also possible to have a complete image less than bytesToRead bytes // (e.g. a 1 x 1 wbmp), meaning peek() would return less than bytesToRead. // Assume that if bytesRead < bytesToRead, but > 0, the stream is shorter // than bytesToRead, so pass that directly to the decoder. // It also is possible the stream uses too small a buffer for peeking, but // we trust the caller to use a large enough buffer. if (0 == bytesRead) { SkCodecPrintf("Could not peek!\n"); // It is possible the stream does not support peeking, but does support // rewinding. // Attempt to read() and pass the actual amount read to the decoder. bytesRead = stream->read(buffer, bytesToRead); if (!stream->rewind()) { SkCodecPrintf("Could not rewind!\n"); return nullptr; } } SkAutoTDelete<SkCodec> codec(nullptr); // PNG is special, since we want to be able to supply an SkPngChunkReader. // But this code follows the same pattern as the loop. if (SkPngCodec::IsPng(buffer, bytesRead)) { codec.reset(SkPngCodec::NewFromStream(streamDeleter.detach(), chunkReader)); } else { for (DecoderProc proc : gDecoderProcs) { if (proc.IsFormat(buffer, bytesRead)) { codec.reset(proc.NewFromStream(streamDeleter.detach())); break; } } } // Set the max size at 128 megapixels (512 MB for kN32). // This is about 4x smaller than a test image that takes a few minutes for // dm to decode and draw. const int32_t maxSize = 1 << 27; if (codec && codec->getInfo().width() * codec->getInfo().height() > maxSize) { SkCodecPrintf("Error: Image size too large, cannot decode.\n"); return nullptr; } else { return codec.detach(); } }
SkScanlineDecoder* SkBmpCodec::NewSDFromStream(SkStream* stream) { SkAutoTDelete<SkBmpCodec> codec(static_cast<SkBmpCodec*>(SkBmpCodec::NewFromStream(stream))); if (!codec) { return NULL; } return SkNEW_ARGS(SkBmpScanlineDecoder, (codec.detach())); }
IVDAudioCodec *VDCreateAudioDecompressorW32(const VDWaveFormat *srcFormat, const VDWaveFormat *dstFormat, const char *pShortNameDriverHint, bool throwIfNotFound) { vdautoptr<VDAudioCodecW32> codec(new VDAudioCodecW32); if (!codec->Init((const WAVEFORMATEX *)srcFormat, (const WAVEFORMATEX *)dstFormat, false, pShortNameDriverHint, throwIfNotFound)) return NULL; return codec.release(); }
DEF_TEST(ShortFrontBufferedStream, reporter) { FailingStream* failingStream = new FailingStream; std::unique_ptr<SkStreamRewindable> stream(SkFrontBufferedStream::Create(failingStream, 64)); // This will fail to create a codec. However, what we really want to test is that we // won't read past the end of the stream. std::unique_ptr<SkCodec> codec(SkCodec::NewFromStream(stream.release())); }