arg. Sorry! (original post updated, see code)
I had a return() where a print() must be. See, the function appends these chunks to STDOUT. As I read your provided logic, it writes everything to a (possibly large) $buffer and then outputs it as a whole. Or did I oversee something in your solution?
2nd update: had a mix up in there with $buffer and $bytes, cleared up by renaming to $chunk_size.