# Buggy code
def write(self, sequence, res, chunk_size=8192):
    if sequence.segment.key and sequence.segment.key.method != "NONE":
        try:
            decryptor = self.create_decryptor(sequence.segment.key, sequence.num)
        except StreamError as err:
            self.logger.error("Failed to create decryptor: {0}", err)
            self.close()
            return

        for chunk in res.iter_content(chunk_size):
            # If the input data is not a multiple of 16, cut off any garbage
            garbage_len = len(chunk) % 16
            if garbage_len:
                self.logger.debug(
                    "Cutting off {0} bytes of garbage before decrypting", garbage_len
                )
                decrypted_chunk = decryptor.decrypt(chunk[:-garbage_len])
            else:
                decrypted_chunk = decryptor.decrypt(chunk)
            self.reader.buffer.write(decrypted_chunk)
    else:
        for chunk in res.iter_content(chunk_size):
            self.reader.buffer.write(chunk)

    self.logger.debug("Download of segment {0} complete", sequence.num)


# Traceback (requests.packages.urllib3.exceptions.ReadTimeoutError)
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py", line 232, in _error_catcher
yield
File "/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py", line 314, in read
data = self._fp.read(amt)
File "/usr/local/lib/python3.5/http/client.py", line 448, in read
n = self.readinto(b)
File "/usr/local/lib/python3.5/http/client.py", line 488, in readinto
n = self.fp.readinto(b)
File "/usr/local/lib/python3.5/socket.py", line 575, in readinto
return self._sock.recv_into(b)
File "/usr/local/lib/python3.5/ssl.py", line 929, in recv_into
return self.read(nbytes, buffer)
File "/usr/local/lib/python3.5/ssl.py", line 791, in read
return self._sslobj.read(len, buffer)
File "/usr/local/lib/python3.5/ssl.py", line 575, in read
v = self._sslobj.read(len, buffer)
socket.timeout: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/requests/models.py", line 676, in generate
for chunk in self.raw.stream(chunk_size, decode_content=True):
File "/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py", line 357, in stream
data = self.read(amt=amt, decode_content=decode_content)
File "/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py", line 324, in read
flush_decoder = True
File "/usr/local/lib/python3.5/contextlib.py", line 77, in __exit__
self.gen.throw(type, value, traceback)
File "/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py", line 237, in _error_catcher
raise ReadTimeoutError(self._pool, None, 'Read timed out.')
requests.packages.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='video-edge-835ef0.ord02.hls.ttvnw.net', port=443): Read timed out.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.5/site-packages/streamlink/stream/segmented.py", line 160, in run
self.write(segment, result)
File "/usr/local/lib/python3.5/site-packages/streamlink/stream/hls.py", line 111, in write
for chunk in res.iter_content(chunk_size):
File "/usr/local/lib/python3.5/site-packages/requests/models.py", line 683, in generate
raise ConnectionError(e)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='video-edge-835ef0.ord02.hls.ttvnw.net', port=443): Read timed out.

# Fixed code
def write(self, sequence, res, chunk_size=8192, retries=None):
    retries = retries or self.retries
    if retries == 0:
        self.logger.error("Failed to open segment {0}", sequence.num)
        return
    try:
        if sequence.segment.key and sequence.segment.key.method != "NONE":
            try:
                decryptor = self.create_decryptor(sequence.segment.key, sequence.num)
            except StreamError as err:
                self.logger.error("Failed to create decryptor: {0}", err)
                self.close()
                return

            for chunk in res.iter_content(chunk_size):
                # If the input data is not a multiple of 16, cut off any garbage
                garbage_len = len(chunk) % 16
                if garbage_len:
                    self.logger.debug(
                        "Cutting off {0} bytes of garbage before decrypting",
                        garbage_len,
                    )
                    decrypted_chunk = decryptor.decrypt(chunk[:-garbage_len])
                else:
                    decrypted_chunk = decryptor.decrypt(chunk)
                self.reader.buffer.write(decrypted_chunk)
        else:
            for chunk in res.iter_content(chunk_size):
                self.reader.buffer.write(chunk)
    except StreamError as err:
        self.logger.error("Failed to open segment {0}: {1}", sequence.num, err)
        return self.write(
            sequence,
            self.fetch(sequence, retries=self.retries),
            chunk_size=chunk_size,
            retries=retries - 1,
        )

    self.logger.debug("Download of segment {0} complete", sequence.num)