Showing posts with label encoding. Show all posts
Showing posts with label encoding. Show all posts

Tuesday, October 31, 2017

How to convert a file to UTF-8 in php?

Leave a Comment

Is it possible to convert a file into UTF-8 on my end?

If I have an access on the file after the submission with

$_FILES['file']['tmp_name'] 

Note: The user can upload a CSV file with any kind of charset, I usually encounter an unknown 8-bit charset.

I try

$row = array(); $datas = file($_FILES['file']['tmp_name']); foreach($datas as $data) {     $data = mb_convert_encoding($data, 'UTF-8');     $row[] = explode(',', $data); } 

But the problem is, this code remove special characters like single quote.

My first question is htmlspecialchars remove the value inside the array?

I put it for additional information. Thanks for those who can help!

4 Answers

Answers 1

Try this out.
The example I have used was something I was doing in a test environment, you might need to change the code slightly.

I had a text file with the following data in:

test café áÁÁÁááá žžœš¥± ÆÆÖÖÖasØØ ß 

Then I had a form which took a file input in and performed the following code:

function neatify_files(&$files) {     $tmp = array();     for ($i = 0; $i < count($_FILES); $i++) {         for ($j = 0; $j < count($_FILES[array_keys($_FILES)[$i]]["name"]); $j++) {             $tmp[array_keys($_FILES)[$i]][$j]["name"] = $_FILES[array_keys($_FILES)[$i]]["name"][$j];             $tmp[array_keys($_FILES)[$i]][$j]["type"] = $_FILES[array_keys($_FILES)[$i]]["type"][$j];             $tmp[array_keys($_FILES)[$i]][$j]["tmp_name"] = $_FILES[array_keys($_FILES)[$i]]["tmp_name"][$j];             $tmp[array_keys($_FILES)[$i]][$j]["error"] = $_FILES[array_keys($_FILES)[$i]]["error"][$j];             $tmp[array_keys($_FILES)[$i]][$j]["size"] = $_FILES[array_keys($_FILES)[$i]]["size"][$j];         }     }     return $files = $tmp; }  if (isset($_POST["submit"])) {     neatify_files($_FILES);     $file = $_FILES["file"][0];      $handle = fopen($file["tmp_name"], "r");     while ($line = fgets($handle)) {         $enc = mb_detect_encoding($line, "UTF-8", true);         if (strtolower($enc) != "utf-8") {             echo "<p>" . (iconv($enc, "UTF-8", $line)) . "</p>";         } else {             echo "<p>$line</p>";         }     } } ?> <form action="<?= $_SERVER["PHP_SELF"]; ?>" method="POST" enctype="multipart/form-data">     <input type="file" name="file[]" />     <input type="submit" name="submit" value="Submit" /> </form> 

The function neatify_files is something I wrote to make the $_FILES array more logical in its layout.

The form is a standard form that simply POSTs the data to the server.
Note: Using $_SERVER["PHP_SELF"] is a security risk, see here for more.

When the data is posted I store the file in a variable. Obviously, if you are using the multiple attribute your code won't look quite like this.

$handle stores the entire contents of the text file, in a read-only format; hence the "r" argument.

$enc uses the mb_detect_encoding function to detect the encoding (duh).
At first I was having trouble with obtaining the correct encoding. Setting the encoding_list to use only UTF-8, and setting strict to be true.

If the encoding is UTF-8 then I simply print the line, if it didn't I converted it to UTF-8 using the iconv function.

Answers 2

before you can convert it to utf-8, you need to know what characterset it is. if you can't figure that out, you can't in any sane way convert it to utf8.. however, an insane way to convert it to utf-8, if the encoding cannot be determined, is to simply strip any bytes that doesn't happen to be valid in utf-8, you might be able to use that as a fallback...

warning, untested code (im suddenly in a hurry), but may look something like this:

foreach ( $datas as $data ) {     $encoding = guess_encoding ( $data );     if (empty ( $encoding )) {         // encoding cannot be determined...         // as a fallback, we simply strip any bytes that isnt valid utf-8...         // obviously this isn't a reliable conversion scheme.         // also this could probably be improved         $data = iconv ( "ASCII", "UTF-8//TRANSLIT//IGNORE", $text );     } else {         $data = mb_convert_encoding ( $data, 'UTF-8', $encoding );     }     $row [] = explode ( ',', $data ); } function guess_encoding(string $str): string {     $blacklist = array (             'pass',             'auto',             'wchar',             'byte2be',             'byte2le',             'byte4be',             'byte4le',             'BASE64',             'UUENCODE',             'HTML-ENTITIES',             '7bit',             '8bit'      );     $encodings = array_flip ( mb_list_encodings () );     foreach ( $blacklist as $tmp ) {         unset ( $encodings [$tmp] );     }     $encodings = array_keys ( $encodings );     $detected = mb_detect_encoding ( $str, $encodings, true );     return ( string ) $detected; } 

Answers 3

you can convert the file text into binary data by using the following

FUNCTION bin2text($bin_str)  {      $text_str = '';      $chars = EXPLODE("\n", CHUNK_SPLIT(STR_REPLACE("\n", '', $bin_str), 8));      $_I = COUNT($chars);      FOR($i = 0; $i < $_I; $text_str .= CHR(BINDEC($chars[$i])), $i  );      RETURN $text_str;  }   FUNCTION text2bin($txt_str)  {      $len = STRLEN($txt_str);      $bin = '';      FOR($i = 0; $i < $len; $i  )      {          $bin .= STRLEN(DECBIN(ORD($txt_str[$i]))) < 8 ? STR_PAD(DECBIN(ORD($txt_str[$i])), 8, 0, STR_PAD_LEFT) : DECBIN(ORD($txt_str[$i]));      }      RETURN $bin;  } 

after converting the data into binary you simply change the text to php method mb_convert_encoding($fileText, "UTF-8");

Answers 4

Let's try this:

function encode_utf8($data) {     if ($data === null || $data === '') {         return $data;     }     if (!mb_check_encoding($data, 'UTF-8')) {         return mb_convert_encoding($data, 'UTF-8');     } else {         return $data;     } } 

Usage:

$content = file_get_contents($_FILES['file']['tmp_name']); $content = encode_utf8($content);  $rows = explode("\n", $content); foreach ($rows as $row) {     print_r($row); } 
Read More

Monday, February 27, 2017

How to avoid “Invalid byte sequence” when looking for link with text using Nokogiri

Leave a Comment

I'm using Rails 5 with Ruby 4.2 and scanning a document that I parsed with Nokogiri, looking in a case insensitive way for a link with text:

a_elt = doc ? doc.xpath('//a').detect { |node| /link[[:space:]]+text/i === node.text } : nil  

After getting the HTML of my web page in content, I parse it into a Nokogiri doc using:

doc = Nokogiri::HTML(content)  

The problem is, I'm getting

ArgumentError invalid byte sequence in UTF-8 

on certain web pages when using the above regular expression.

2.4.0 :002 > doc.encoding  => "UTF-8"  2.4.0 :003 > doc.xpath('//a').detect { |node| /individual[[:space:]]+results/i === node.text } ArgumentError: invalid byte sequence in UTF-8     from (irb):3:in `==='     from (irb):3:in `block in irb_binding'     from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/nokogiri-1.7.0/lib/nokogiri/xml/node_set.rb:187:in `block in each'     from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/nokogiri-1.7.0/lib/nokogiri/xml/node_set.rb:186:in `upto'     from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/nokogiri-1.7.0/lib/nokogiri/xml/node_set.rb:186:in `each'     from (irb):3:in `detect'     from (irb):3     from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands/console.rb:65:in `start'     from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands/console_helper.rb:9:in `start'     from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:78:in `console'     from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!'     from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands.rb:18:in `<top (required)>'     from bin/rails:4:in `require'     from bin/rails:4:in `<main>'  

Is there a way I can rewrite the above to automatically account for the encoding or weird characters and not flip out?

1 Answers

Answers 1

Your question may have already been answered before. Have you tried the methods from "Is there any way to clean a file of "invalid byte sequence in UTF-8" errors in Ruby?"?

Specifically before the detect block, try to remove the invalid bytes and control characters except new line:

doc.scrub!("") doc.gsub!(/[[:cntrl:]&&[^\n\r]]/,"") 

Remember, scrub! is a Ruby 2.1+ method.

Read More

Friday, February 3, 2017

UTF-8 / Unicode Text Encoding with RPostgreSQL

Leave a Comment

I'm running R on a Windows machine which is directly linked to a PostgreSQL database. I'm not using RODBC. My database is encoded in UTF-8 as confirmed by the following R command:

dbGetQuery(con, "SHOW CLIENT_ENCODING") #   client_encoding # 1            UTF8 

However, when some text is read into R, it displays as strange text in R.

For example, the following text is shown in my PostgreSQL database: "Stéphane"

After exporting to R it's shown as: "Stéphane" (the é is encoded as é)

When importing to R I use the dbConnect command to establish a connection and the dbGetQuery command to query data using SQL. I do not specify any text encoding anywhere when connecting to the database or when running a query.

I've searched online and can't find a direct resolution to my issue. I found this link, but their issue is with RODBC, which I'm not using.

This link is helpful in identifying the symbols, but I don't just want to do a find & replace in R... way too much data.

I did try running the following commands below and I arrived at a warning.

Sys.setlocale("LC_ALL", "en_US.UTF-8") # [1] "" # Warning message: # In Sys.setlocale("LC_ALL", "en_US.UTF-8") : #   OS reports request to set locale to "en_US.UTF-8" cannot be honored Sys.setenv(LANG="en_US.UTF-8") Sys.setenv(LC_CTYPE="UTF-8") 

The warning occurs on the Sys.setlocale("LC_ALL", "en_US.UTF-8") command. My intuition is that this is a Windows specific issue and doesn't occur with Mac/Linux/Unix.

EDIT 2014-01-29:
The following execution will fix any Unicode/UTF-8 problems in Windows. It must be executed before querying the database.

postgresqlpqExec(con, "SET client_encoding = 'windows-1252'") 

2 Answers

Answers 1

After exporting to R it's shown as: "Stéphane" (the é is encoded as é)

Your R environment is using a 1-byte non-composed encoding like latin-1 or windows-1252. Witness this test in Python, demonstrating that the utf-8 bytes for é, decoded as if they were latin-1, produce the text you see:

>>> print u"é".encode("utf-8").decode("latin-1") é 

Either SET client_encoding = 'windows-1252' or fix the encoding your R environment uses. If it's running in a cmd.exe console you'll need to mess with the chcp console command; otherwise it's specific to whatever your R runtime is.

Answers 2

As Craig Ringer said, setting client_encoding to windows-1252 is probably not the best thing to do. Indeed, if the data you're retrieving contains a single exotic character, you're in trouble:

Error in postgresqlExecStatement(conn, statement, ...) : RS-DBI driver: (could not Retrieve the result : ERROR: character 0xcca7 of encoding "UTF8" has no equivalent in "WIN1252" )

On the other hand, getting your R environment to use Unicode could be impossible (I have the same problem as you with Sys.setlocale... Same in this question too.).

A (dirty) workaround is to manually declare UTF-8 encoding on all your data, using a function like this one:

set_utf8 = function(x){   # Declare UTF-8 encoding on all character strings:   for (i in 1:ncol(x)){     if (is.character(x[, i])) Encoding(x[, i]) <- 'UTF-8'   }   # Same on column names:   for (name in colnames(x)){     Encoding(name) <- 'UTF-8'   }   return(x) } 

And you have to use this function in all your queries:

set_utf8(dbGetQuery(con, "SELECT myvar FROM mytable")) 
Read More

Sunday, April 10, 2016

AAC encoding using AudioConverter and writing to AVAssetWriter

Leave a Comment

I'm struggling to encode audio buffers received from AVCaptureSession using AudioConverter and then appending them to an AVAssetWriter.

I'm not getting any errors (including OSStatus responses), and the CMSampleBuffers generated seem to have valid data, however the resulting file simply does not have any playable audio. When writing together with video, the video frames stop getting appended a couple of frames in (appendSampleBuffer() returns false, but with no AVAssetWriter.error), probably because the asset writer is waiting for the audio to catch up. I suspect it's related to the way I'm setting up the priming for AAC.

The app uses RxSwift, but I've removed the RxSwift parts so that it's easier to understand for a wider audience.

Please check out comments in the code below for more... comments

Given a settings struct:

import Foundation import AVFoundation import CleanroomLogger  public struct AVSettings {  let orientation: AVCaptureVideoOrientation = .Portrait let sessionPreset                          = AVCaptureSessionPreset1280x720 let videoBitrate: Int                      = 2_000_000 let videoExpectedFrameRate: Int            = 30 let videoMaxKeyFrameInterval: Int          = 60  let audioBitrate: Int                      = 32 * 1024  /// Settings that are `0` means variable rate. /// The `mSampleRate` and `mChennelsPerFrame` is overwritten at run-time /// to values based on the input stream. let audioOutputABSD = AudioStreamBasicDescription(                             mSampleRate: AVAudioSession.sharedInstance().sampleRate,                             mFormatID: kAudioFormatMPEG4AAC,                             mFormatFlags: UInt32(MPEG4ObjectID.AAC_Main.rawValue),                             mBytesPerPacket: 0,                             mFramesPerPacket: 1024,                             mBytesPerFrame: 0,                             mChannelsPerFrame: 1,                             mBitsPerChannel: 0,                             mReserved: 0)  let audioEncoderClassDescriptions = [     AudioClassDescription(         mType: kAudioEncoderComponentType,         mSubType: kAudioFormatMPEG4AAC,         mManufacturer: kAppleSoftwareAudioCodecManufacturer) ]  } 

Some helper functions:

public func getVideoDimensions(fromSettings settings: AVSettings) -> (Int, Int) {   switch (settings.sessionPreset, settings.orientation)  {   case (AVCaptureSessionPreset1920x1080, .Portrait): return (1080, 1920)   case (AVCaptureSessionPreset1280x720, .Portrait): return (720, 1280)   default: fatalError("Unsupported session preset and orientation")   } }  public func createAudioFormatDescription(fromSettings settings: AVSettings) -> CMAudioFormatDescription {   var result = noErr   var absd = settings.audioOutputABSD   var description: CMAudioFormatDescription?   withUnsafePointer(&absd) { absdPtr in       result = CMAudioFormatDescriptionCreate(nil,                                               absdPtr,                                               0, nil,                                               0, nil,                                               nil,                                               &description)   }    if result != noErr {       Log.error?.message("Could not create audio format description")   }    return description! }  public func createVideoFormatDescription(fromSettings settings: AVSettings) -> CMVideoFormatDescription {   var result = noErr   var description: CMVideoFormatDescription?   let (width, height) = getVideoDimensions(fromSettings: settings)   result = CMVideoFormatDescriptionCreate(nil,                                           kCMVideoCodecType_H264,                                           Int32(width),                                           Int32(height),                                           [:],                                           &description)    if result != noErr {       Log.error?.message("Could not create video format description")   }    return description! } 

This is how the asset writer is initialized:

guard let audioDevice = defaultAudioDevice() else { throw RecordError.MissingDeviceFeature("Microphone") }  guard let videoDevice = defaultVideoDevice(.Back) else { throw RecordError.MissingDeviceFeature("Camera") }  let videoInput      = try AVCaptureDeviceInput(device: videoDevice) let audioInput      = try AVCaptureDeviceInput(device: audioDevice) let videoFormatHint = createVideoFormatDescription(fromSettings: settings) let audioFormatHint = createAudioFormatDescription(fromSettings: settings)  let writerVideoInput = AVAssetWriterInput(mediaType: AVMediaTypeVideo,                                         outputSettings: nil,                                         sourceFormatHint: videoFormatHint)  let writerAudioInput = AVAssetWriterInput(mediaType: AVMediaTypeAudio,                                         outputSettings: nil,                                         sourceFormatHint: audioFormatHint)  writerVideoInput.expectsMediaDataInRealTime = true writerAudioInput.expectsMediaDataInRealTime = true  let url = NSURL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)         .URLByAppendingPathComponent(NSProcessInfo.processInfo().globallyUniqueString)         .URLByAppendingPathExtension("mp4")  let assetWriter =  try AVAssetWriter(URL: url, fileType: AVFileTypeMPEG4)  if !assetWriter.canAddInput(writerVideoInput) { throw RecordError.Unknown("Could not add video input") }  if !assetWriter.canAddInput(writerAudioInput) { throw RecordError.Unknown("Could not add audio input") }  assetWriter.addInput(writerVideoInput) assetWriter.addInput(writerAudioInput) 

And this is how audio samples are being encoded, problem area is most likely to be around here. I've re-written this so that it doesn't use any Rx-isms.

var outputABSD = settings.audioOutputABSD var outputFormatDescription: CMAudioFormatDescription! = nil CMAudioFormatDescriptionCreate(nil, &outputABSD, 0, nil, 0, nil, nil, &formatDescription)  var converter: AudioConverter?  // Indicates whether priming information has been attached to the first buffer var primed = false  func encodeAudioBuffer(settings: AVSettings, buffer: CMSampleBuffer) throws -> CMSampleBuffer? {    // Create the audio converter if it's not available   if converter == nil {       var classDescriptions = settings.audioEncoderClassDescriptions       var inputABSD = CMAudioFormatDescriptionGetStreamBasicDescription(CMSampleBufferGetFormatDescription(buffer)!).memory       var outputABSD = settings.audioOutputABSD       outputABSD.mSampleRate = inputABSD.mSampleRate       outputABSD.mChannelsPerFrame = inputABSD.mChannelsPerFrame        var converter: AudioConverterRef = nil       var result = noErr       result = withUnsafePointer(&outputABSD) { outputABSDPtr in           return withUnsafePointer(&inputABSD) { inputABSDPtr in           return AudioConverterNewSpecific(inputABSDPtr,                                           outputABSDPtr,                                           UInt32(classDescriptions.count),                                           &classDescriptions,                                           &converter)           }       }        if result != noErr { throw RecordError.Unknown }        // At this point I made an attempt to retrieve priming info from       // the audio converter assuming that it will give me back default values       // I can use, but ended up with `nil`       var primeInfo: AudioConverterPrimeInfo? = nil       var primeInfoSize = UInt32(sizeof(AudioConverterPrimeInfo))        // The following returns a `noErr` but `primeInfo` is still `nil``       AudioConverterGetProperty(converter,                                kAudioConverterPrimeInfo,                               &primeInfoSize,                                &primeInfo)        // I've also tried to set `kAudioConverterPrimeInfo` so that it knows       // the leading frames that are being primed, but the set didn't seem to work       // (`noErr` but getting the property afterwards still returned `nil`)   }    let converter = converter!    // Need to give a big enough output buffer.   // The assumption is that it will always be <= to the input size   let numSamples = CMSampleBufferGetNumSamples(buffer)   // This becomes 1024 * 2 = 2048   let outputBufferSize = numSamples * Int(inputABSD.mBytesPerPacket)   let outputBufferPtr = UnsafeMutablePointer<Void>.alloc(outputBufferSize)    defer {       outputBufferPtr.destroy()       outputBufferPtr.dealloc(1)   }    var result = noErr    var outputPacketCount = UInt32(1)   var outputData = AudioBufferList(   mNumberBuffers: 1,   mBuffers: AudioBuffer(                   mNumberChannels: outputABSD.mChannelsPerFrame,                   mDataByteSize: UInt32(outputBufferSize),                   mData: outputBufferPtr))    // See below for `EncodeAudioUserData`   var userData = EncodeAudioUserData(inputSampleBuffer: buffer,                                       inputBytesPerPacket: inputABSD.mBytesPerPacket)    withUnsafeMutablePointer(&userData) { userDataPtr in       // See below for `fetchAudioProc`       result = AudioConverterFillComplexBuffer(                       converter,                       fetchAudioProc,                       userDataPtr,                       &outputPacketCount,                       &outputData,                       nil)   }    if result != noErr {       Log.error?.message("Error while trying to encode audio buffer, code: \(result)")       return nil   }    // See below for `CMSampleBufferCreateCopy`   guard let newBuffer = CMSampleBufferCreateCopy(buffer,                                                   fromAudioBufferList: &outputData,                                                   newFromatDescription: outputFormatDescription) else {       Log.error?.message("Could not create sample buffer from audio buffer list")       return nil   }    if !primed {       primed = true       // Simply picked 2112 samples based on convention, is there a better way to determine this?       let samplesToPrime: Int64 = 2112       let samplesPerSecond = Int32(settings.audioOutputABSD.mSampleRate)       let primingDuration = CMTimeMake(samplesToPrime, samplesPerSecond)        // Without setting the attachment the asset writer will complain about the       // first buffer missing the `TrimDurationAtStart` attachment, is there are way       // to infer the value from the given `AudioBufferList`?       CMSetAttachment(newBuffer,                       kCMSampleBufferAttachmentKey_TrimDurationAtStart,                       CMTimeCopyAsDictionary(primingDuration, nil),                       kCMAttachmentMode_ShouldNotPropagate)   }    return newBuffer  } 

Below is the proc that fetches samples for the audio converter, and the data structure that gets passed to it:

private class EncodeAudioUserData {   var inputSampleBuffer: CMSampleBuffer?   var inputBytesPerPacket: UInt32    init(inputSampleBuffer: CMSampleBuffer,       inputBytesPerPacket: UInt32) {       self.inputSampleBuffer   = inputSampleBuffer       self.inputBytesPerPacket = inputBytesPerPacket   } }  private let fetchAudioProc: AudioConverterComplexInputDataProc = {   (inAudioConverter,   ioDataPacketCount,   ioData,   outDataPacketDescriptionPtrPtr,   inUserData) in    var result = noErr    if ioDataPacketCount.memory == 0 { return noErr }    let userData = UnsafeMutablePointer<EncodeAudioUserData>(inUserData).memory    // If its already been processed   guard let buffer = userData.inputSampleBuffer else {       ioDataPacketCount.memory = 0       return -1   }    var inputBlockBuffer: CMBlockBuffer?   var inputBufferList = AudioBufferList()   result = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(               buffer,               nil,               &inputBufferList,               sizeof(AudioBufferList),               nil,               nil,               0,               &inputBlockBuffer)    if result != noErr {       Log.error?.message("Error while trying to retrieve buffer list, code: \(result)")       ioDataPacketCount.memory = 0       return result   }    let packetsCount = inputBufferList.mBuffers.mDataByteSize / userData.inputBytesPerPacket   ioDataPacketCount.memory = packetsCount    ioData.memory.mBuffers.mNumberChannels = inputBufferList.mBuffers.mNumberChannels   ioData.memory.mBuffers.mDataByteSize = inputBufferList.mBuffers.mDataByteSize   ioData.memory.mBuffers.mData = inputBufferList.mBuffers.mData    if outDataPacketDescriptionPtrPtr != nil {       outDataPacketDescriptionPtrPtr.memory = nil   }    return noErr } 

This is how I am converting AudioBufferLists to CMSampleBuffers:

public func CMSampleBufferCreateCopy(     buffer: CMSampleBuffer,     inout fromAudioBufferList bufferList: AudioBufferList,     newFromatDescription formatDescription: CMFormatDescription? = nil)     -> CMSampleBuffer? {    var result = noErr    var sizeArray: [Int] = [Int(bufferList.mBuffers.mDataByteSize)]   // Copy timing info from the previous buffer   var timingInfo = CMSampleTimingInfo()   result = CMSampleBufferGetSampleTimingInfo(buffer, 0, &timingInfo)    if result != noErr { return nil }    var newBuffer: CMSampleBuffer?   result = CMSampleBufferCreateReady(       kCFAllocatorDefault,       nil,       formatDescription ?? CMSampleBufferGetFormatDescription(buffer),       Int(bufferList.mNumberBuffers),       1, &timingInfo,       1, &sizeArray,       &newBuffer)    if result != noErr { return nil }   guard let b = newBuffer else { return nil }    CMSampleBufferSetDataBufferFromAudioBufferList(b, nil, nil, 0, &bufferList)   return newBuffer  } 

Is there anything that I am obviously doing wrong? Is there a proper way to construct CMSampleBuffers from AudioBufferList? How do you transfer priming information from the converter to CMSampleBuffers that you create?

For my use case I need to do the encoding manually as the buffers will be manipulated further down the pipeline (although I've disabled all transformations after the encode in order to make sure that it works.)

Any help would be much appreciated. Sorry that there's so much code to digest, but I wanted to provide as much context as possible.

Thanks in advance :)


Some related questions:

Some references I've used:

0 Answers

Read More

Wednesday, March 16, 2016

What is the point of Tomcat's setting URIEncoding?

Leave a Comment

In Apache Tomcat, parameter URIEncoding tells Tomcat how to interpret incoming URIs:

URIEncoding

This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, ISO-8859-1 will be used.

Apache Tomcat 7 - The HTTP Connector

However, as explained for example in What is the proper way to URL encode Unicode characters? , non-ASCII characters in URIs are always encoded in UTF-8, following current standards (RFC 3986 and 3987).

So:

  • Why is there even a setting for something that is mandated by a standard?
  • Why is the default different from what the standard mandates? (ISO-8859-1 instead of UTF-8)

Is this simply because the Tomcat setting predates the standard, and was retained for backwards compatibility? Or is there some situation where a value different from UTF-8 makes sense?

1 Answers

Answers 1

I see that at least for Tomcat 6 and below URIEncoding was not only important, but necessary, with many people having issues if not explicitly setting it to 'UTF-8'. As for your question, I can only assume that it is for backward compatibility. Developers hate to remove code once they have written it, even if the possibility of ever needing it again is zero :)

Read More