streamreader_basic_tutorial.py 18.3 KB
Newer Older
1
"""
2
3
StreamReader Basic Usages
=========================
4

5
6
**Author**: `Moto Hira <moto@meta.com>`__

7
This tutorial shows how to use :py:class:`torchaudio.io.StreamReader` to
8
9
10
11
12
fetch and decode audio/video data and apply preprocessings that
libavfilter provides.

"""

13
14
15
16
######################################################################
#
# .. note::
#
moto's avatar
moto committed
17
#    This tutorial requires FFmpeg libraries (>=5.0, <6).
18
19
20
#
#    There are multiple ways to install FFmpeg libraries.
#    If you are using Anaconda Python distribution,
moto's avatar
moto committed
21
#    ``conda install -c conda-forge 'ffmpeg<6'`` will install
22
23
24
#    the required libraries.
#

25
######################################################################
26
27
# Overview
# --------
28
29
30
31
32
33
#
# Streaming API leverages the powerful I/O features of ffmpeg.
#
# It can
#  - Load audio/video in variety of formats
#  - Load audio/video from local/remote source
34
#  - Load audio/video from file-like object
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#  - Load audio/video from microphone, camera and screen
#  - Generate synthetic audio/video signals.
#  - Load audio/video chunk by chunk
#  - Change the sample rate / frame rate, image size, on-the-fly
#  - Apply filters and preprocessings
#
# The streaming API works in three steps.
#
# 1. Open media source (file, device, synthetic pattern generator)
# 2. Configure output stream
# 3. Stream the media
#
# At this moment, the features that the ffmpeg integration provides
# are limited to the form of
#
# `<some media source> -> <optional processing> -> <tensor>`
#
# If you have other forms that can be useful to your usecases,
53
# (such as integration with `torch.Tensor` type)
54
55
56
57
# please file a feature request.
#

######################################################################
58
59
# Preparation
# -----------
60
61
62
63
#

import torch
import torchaudio
64

65
66
67
68
69
70
print(torch.__version__)
print(torchaudio.__version__)

######################################################################
#

71
try:
72
    from torchaudio.io import StreamReader
73
74
75
76
77
78
except ModuleNotFoundError:
    try:
        import google.colab

        print(
            """
79
80
            To enable running this notebook in Google Colab, install the requisite
            third party libraries by running the following code:
81
82
83
84
85
86
87
88

            !add-apt-repository -y ppa:savoury1/ffmpeg4
            !apt-get -qq install -y ffmpeg
            """
        )
    except ModuleNotFoundError:
        pass
    raise
89

90
import matplotlib.pyplot as plt
91
92
93
94
95
96

base_url = "https://download.pytorch.org/torchaudio/tutorial-assets"
AUDIO_URL = f"{base_url}/Lab41-SRI-VOiCES-src-sp0307-ch127535-sg0042.wav"
VIDEO_URL = f"{base_url}/stream-api/NASAs_Most_Scientifically_Complex_Space_Observatory_Requires_Precision-MP4.mp4"

######################################################################
97
98
# Opening the source
# ------------------
99
100
101
102
103
#
# There are mainly three different sources that streaming API can
# handle. Whichever source is used, the remaining processes
# (configuring the output, applying preprocessing) are same.
#
104
# 1. Common media formats (resource indicator of string type or file-like object)
105
106
107
108
109
# 2. Audio / Video devices
# 3. Synthetic audio / video sources
#
# The following section covers how to open common media formats.
# For the other streams, please refer to the
moto's avatar
moto committed
110
# `StreamReader Advanced Usage <./streamreader_advanced_tutorial.html>`__.
111
#
112
113
114
115
116
117
118
119
# .. note::
#
#    The coverage of the supported media (such as containers, codecs and protocols)
#    depend on the FFmpeg libraries found in the system.
#
#    If `StreamReader` raises an error opening a source, please check
#    that `ffmpeg` command can handle it.
#
120
121

######################################################################
122
123
# Local files
# ~~~~~~~~~~~
124
125
#
# To open a media file, you can simply pass the path of the file to
126
# the constructor of `StreamReader`.
127
128
129
#
# .. code::
#
130
#    StreamReader(src="audio.wav")
131
#
132
#    StreamReader(src="audio.mp3")
133
134
135
136
137
138
#
# This works for image file, video file and video streams.
#
# .. code::
#
#    # Still image
139
#    StreamReader(src="image.jpeg")
140
141
#
#    # Video file
142
#    StreamReader(src="video.mpeg")
143
#
144
145
146
147
148
149
150
151
152

######################################################################
# Network protocols
# ~~~~~~~~~~~~~~~~~
#
# You can directly pass a URL as well.
#
# .. code::
#
153
#    # Video on remote server
154
#    StreamReader(src="https://example.com/video.mp4")
155
156
#
#    # Playlist format
157
#    StreamReader(src="https://example.com/playlist.m3u")
158
#
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#    # RTMP
#    StreamReader(src="rtmp://example.com:1935/live/app")
#

######################################################################
# File-like objects
# ~~~~~~~~~~~~~~~~~
#
# You can also pass a file-like object. A file-like object must implement
# ``read`` method conforming to :py:attr:`io.RawIOBase.read`.
#
# If the given file-like object has ``seek`` method, StreamReader uses it
# as well. In this case the ``seek`` method is expected to conform to
# :py:attr:`io.IOBase.seek`.
#
# .. code::
#
#    # Open as fileobj with seek support
#    with open("input.mp4", "rb") as src:
#        StreamReader(src=src)
#
# In case where third-party libraries implement ``seek`` so that it raises
# an error, you can write a wrapper class to mask the ``seek`` method.
#
# .. code::
#
185
#    class UnseekableWrapper:
186
187
188
189
190
191
192
193
194
195
196
#        def __init__(self, obj):
#            self.obj = obj
#
#        def read(self, n):
#            return self.obj.read(n)
#
# .. code::
#
#    import requests
#
#    response = requests.get("https://example.com/video.mp4", stream=True)
197
#    s = StreamReader(UnseekableWrapper(response.raw))
198
199
200
201
202
203
#
# .. code::
#
#    import boto3
#
#    response = boto3.client("s3").get_object(Bucket="my_bucket", Key="key")
204
205
206
207
208
209
210
211
212
213
214
#    s = StreamReader(UnseekableWrapper(response["Body"]))
#
# .. note::
#
#    When using an unseekable file-like object, the source media has to be
#    streamable.
#    For example, a valid MP4-formatted object can have its metadata either
#    at the beginning or at the end of the media data.
#    Those with metadata at the beginning can be opened without method
#    `seek`, but those with metadata at the end cannot be opened
#    without `seek`.
215
216
217
#

######################################################################
218
219
# Headerless media
# ~~~~~~~~~~~~~~~~
220
#
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# If attempting to load headerless raw data, you can use ``format`` and
# ``option`` to specify the format of the data.
#
# Say, you converted an audio file into faw format with ``sox`` command
# as follow;
#
# .. code::
#
#    # Headerless, 16-bit signed integer PCM, resampled at 16k Hz.
#    $ sox original.wav -r 16000 raw.s2
#
# Such audio can be opened like following.
#
# .. code::
#
236
#    StreamReader(src="raw.s2", format="s16le", option={"sample_rate": "16000"})
237
238
239
#

######################################################################
240
241
# Checking the source streams
# ---------------------------
242
243
244
245
246
#
# Once the media is opened, we can inspect the streams and configure
# the output streams.
#
# You can check the number of source streams with
247
# :py:attr:`~torchaudio.io.StreamReader.num_src_streams`.
248
249
250
251
252
253
#
# .. note::
#    The number of streams is NOT the number of channels.
#    Each audio stream can contain an arbitrary number of channels.
#
# To check the metadata of source stream you can use
254
# :py:meth:`~torchaudio.io.StreamReader.get_src_stream_info`
255
256
257
# method and provide the index of the source stream.
#
# This method returns
258
# :py:class:`~torchaudio.io.StreamReader.SourceStream`. If a source
259
# stream is audio type, then the return type is
260
# :py:class:`~torchaudio.io.StreamReader.SourceAudioStream`, which is
261
262
# a subclass of `SourceStream`, with additional audio-specific attributes.
# Similarly, if a source stream is video type, then the return type is
263
# :py:class:`~torchaudio.io.StreamReader.SourceVideoStream`.
264
265
266
267
268
269

######################################################################
# For regular audio formats and still image formats, such as `WAV`
# and `JPEG`, the number of souorce streams is 1.
#

270
streamer = StreamReader(AUDIO_URL)
271
272
273
274
275
276
277
278
279
print("The number of source streams:", streamer.num_src_streams)
print(streamer.get_src_stream_info(0))

######################################################################
# Container formats and playlist formats may contain multiple streams
# of different media type.
#

src = "https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8"
280
streamer = StreamReader(src)
281
282
283
284
285
print("The number of source streams:", streamer.num_src_streams)
for i in range(streamer.num_src_streams):
    print(streamer.get_src_stream_info(i))

######################################################################
286
287
# Configuring output streams
# --------------------------
288
289
290
291
292
293
294
295
#
# The stream API lets you stream data from an arbitrary combination of
# the input streams. If your application does not need audio or video,
# you can omit them. Or if you want to apply different preprocessing
# to the same source stream, you can duplicate the source stream.
#

######################################################################
296
297
# Default streams
# ~~~~~~~~~~~~~~~
298
299
300
301
302
303
304
#
# When there are multiple streams in the source, it is not immediately
# clear which stream should be used.
#
# FFmpeg implements some heuristics to determine the default stream.
# The resulting stream index is exposed via
#
305
306
# :py:attr:`~torchaudio.io.StreamReader.default_audio_stream` and
# :py:attr:`~torchaudio.io.StreamReader.default_video_stream`.
307
308
309
#

######################################################################
310
311
# Configuring output streams
# ~~~~~~~~~~~~~~~~~~~~~~~~~~
312
313
314
#
# Once you know which source stream you want to use, then you can
# configure output streams with
315
316
# :py:meth:`~torchaudio.io.StreamReader.add_basic_audio_stream` and
# :py:meth:`~torchaudio.io.StreamReader.add_basic_video_stream`.
317
318
319
320
321
322
323
324
325
326
327
328
329
#
# These methods provide a simple way to change the basic property of
# media to match the application's requirements.
#
# The arguments common to both methods are;
#
# - ``frames_per_chunk``: How many frames at maximum should be
#   returned at each iteration.
#   For audio, the resulting tensor will be the shape of
#   `(frames_per_chunk, num_channels)`.
#   For video, it will be
#   `(frames_per_chunk, num_channels, height, width)`.
# - ``buffer_chunk_size``: The maximum number of chunks to be buffered internally.
330
331
#   When the StreamReader buffered this number of chunks and is asked to pull
#   more frames, StreamReader drops the old frames/chunks.
332
# - ``stream_index``: The index of the source stream.
333
334
335
# - ``decoder``: If provided, override the decoder. Useful if it fails to detect
#   the codec.
# - ``decoder_option``: The option for the decoder.
336
337
338
339
#
# For audio output stream, you can provide the following additional
# parameters to change the audio properties.
#
340
341
# - ``format``: By default the StreamReader returns tensor of `float32` dtype,
#   with sample values ranging `[-1, 1]`. By providing ``format`` argument
342
#   the resulting dtype and value range is changed.
343
# - ``sample_rate``: When provided, StreamReader resamples the audio on-the-fly.
344
345
346
#
# For video output stream, the following parameters are available.
#
347
348
# - ``format``: Image frame format. By default StreamReader returns
#   frames in 8-bit 3 channel, in RGB order.
349
350
351
352
353
354
355
356
357
# - ``frame_rate``: Change the frame rate by dropping or duplicating
#   frames. No interpolation is performed.
# - ``width``, ``height``: Change the image size.
#

######################################################################
#
# .. code::
#
358
#    streamer = StreamReader(...)
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
#
#    # Stream audio from default audio source stream
#    # 256 frames at a time, keeping the original sampling rate.
#    streamer.add_basic_audio_stream(
#        frames_per_chunk=256,
#    )
#
#    # Stream audio from source stream `i`.
#    # Resample audio to 8k Hz, stream 256 frames at each
#    streamer.add_basic_audio_stream(
#        frames_per_chunk=256,
#        stream_index=i,
#        sample_rate=8000,
#    )
#

######################################################################
#
# .. code::
#
#    # Stream video from default video source stream.
#    # 10 frames at a time, at 30 FPS
#    # RGB color channels.
#    streamer.add_basic_video_stream(
#        frames_per_chunk=10,
#        frame_rate=30,
385
#        format="rgb24"
386
387
388
389
390
391
392
393
394
395
396
#    )
#
#    # Stream video from source stream `j`,
#    # 10 frames at a time, at 30 FPS
#    # BGR color channels with rescaling to 128x128
#    streamer.add_basic_video_stream(
#        frames_per_chunk=10,
#        stream_index=j,
#        frame_rate=30,
#        width=128,
#        height=128,
397
#        format="bgr24"
398
399
400
401
402
403
404
#    )
#

######################################################################
#
# You can check the resulting output streams in a similar manner as
# checking the source streams.
405
# :py:attr:`~torchaudio.io.StreamReader.num_out_streams` reports
406
# the number of configured output streams, and
407
# :py:meth:`~torchaudio.io.StreamReader.get_out_stream_info`
408
409
410
411
412
413
414
415
416
417
418
# fetches the information about the output streams.
#
# .. code::
#
#    for i in range(streamer.num_out_streams):
#        print(streamer.get_out_stream_info(i))
#

######################################################################
#
# If you want to remove an output stream, you can do so with
419
# :py:meth:`~torchaudio.io.StreamReader.remove_stream` method.
420
421
422
423
424
425
426
427
#
# .. code::
#
#    # Removes the first output stream.
#    streamer.remove_stream(0)
#

######################################################################
428
429
# Streaming
# ---------
430
431
432
433
434
435
#
# To stream media data, the streamer alternates the process of
# fetching and decoding the source data, and passing the resulting
# audio / video data to client code.
#
# There are low-level methods that performs these operations.
436
437
438
# :py:meth:`~torchaudio.io.StreamReader.is_buffer_ready`,
# :py:meth:`~torchaudio.io.StreamReader.process_packet` and
# :py:meth:`~torchaudio.io.StreamReader.pop_chunks`.
439
440
441
442
443
444
#
# In this tutorial, we will use the high-level API, iterator protocol.
# It is as simple as a ``for`` loop.
#
# .. code::
#
445
#    streamer = StreamReader(...)
446
447
448
449
450
451
452
453
454
#    streamer.add_basic_audio_stream(...)
#    streamer.add_basic_video_stream(...)
#
#    for chunks in streamer.stream():
#        audio_chunk, video_chunk = chunks
#        ...
#

######################################################################
455
456
# Example
# -------
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
#
# Let's take an example video to configure the output streams.
# We will use the following video.
#
# .. raw:: html
#
#    <iframe width="560" height="315"
#     src="https://www.youtube.com/embed/6zNsc0e3Zns"
#     title="YouTube video player"
#     frameborder="0"
#     allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
#     allowfullscreen></iframe>
#
# Source: https://svs.gsfc.nasa.gov/13013 (This video is in public domain)
#
# Credit: NASA's Goddard Space Flight Center.
#
# NASA's Media Usage Guidelines: https://www.nasa.gov/multimedia/guidelines/index.html
#
#

######################################################################
479
480
# Opening the source media
# ~~~~~~~~~~~~~~~~~~~~~~~~
481
482
483
484
#
# Firstly, let's list the available streams and its properties.
#

485
streamer = StreamReader(VIDEO_URL)
486
487
488
489
490
491
492
for i in range(streamer.num_src_streams):
    print(streamer.get_src_stream_info(i))

######################################################################
#
# Now we configure the output stream.
#
493
494
# Configuring ouptut streams
# ~~~~~~~~~~~~~~~~~~~~~~~~~~
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514

# fmt: off
# Audio stream with 8k Hz
streamer.add_basic_audio_stream(
    frames_per_chunk=8000,
    sample_rate=8000,
)

# Audio stream with 16k Hz
streamer.add_basic_audio_stream(
    frames_per_chunk=16000,
    sample_rate=16000,
)

# Video stream with 960x540 at 1 FPS.
streamer.add_basic_video_stream(
    frames_per_chunk=1,
    frame_rate=1,
    width=960,
    height=540,
515
    format="rgb24",
516
517
518
519
520
521
522
523
)

# Video stream with 320x320 (stretched) at 3 FPS, grayscale
streamer.add_basic_video_stream(
    frames_per_chunk=3,
    frame_rate=3,
    width=320,
    height=320,
524
    format="gray",
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
)
# fmt: on

######################################################################
# .. note::
#
#    When configuring multiple output streams, in order to keep all
#    streams synced, set parameters so that the ratio between
#    ``frames_per_chunk`` and ``sample_rate`` or ``frame_rate`` is
#    consistent across output streams.
#

######################################################################
# Checking the output streams.
#

for i in range(streamer.num_out_streams):
    print(streamer.get_out_stream_info(i))

######################################################################
# Remove the second audio stream.
#

streamer.remove_stream(1)
for i in range(streamer.num_out_streams):
    print(streamer.get_out_stream_info(i))

######################################################################
553
554
# Streaming
# ~~~~~~~~~
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
#

######################################################################
# Jump to the 10 second point.
#
streamer.seek(10.0)

######################################################################
#
# Now, let's finally iterate over the output streams.
#

n_ite = 3
waveforms, vids1, vids2 = [], [], []
for i, (waveform, vid1, vid2) in enumerate(streamer.stream()):
    waveforms.append(waveform)
    vids1.append(vid1)
    vids2.append(vid2)
    if i + 1 == n_ite:
        break

######################################################################
# For audio stream, the chunk Tensor will be the shape of
# `(frames_per_chunk, num_channels)`, and for video stream,
# it is `(frames_per_chunk, num_color_channels, height, width)`.
#

print(waveforms[0].shape)
print(vids1[0].shape)
print(vids2[0].shape)

######################################################################
# Let's visualize what we received.

k = 3
fig = plt.figure()
gs = fig.add_gridspec(3, k * n_ite)
for i, waveform in enumerate(waveforms):
    ax = fig.add_subplot(gs[0, k * i : k * (i + 1)])
    ax.specgram(waveform[:, 0], Fs=8000)
    ax.set_yticks([])
    ax.set_xticks([])
    ax.set_title(f"Iteration {i}")
    if i == 0:
        ax.set_ylabel("Stream 0")
for i, vid in enumerate(vids1):
    ax = fig.add_subplot(gs[1, k * i : k * (i + 1)])
    ax.imshow(vid[0].permute(1, 2, 0))  # NCHW->HWC
    ax.set_yticks([])
    ax.set_xticks([])
    if i == 0:
        ax.set_ylabel("Stream 1")
for i, vid in enumerate(vids2):
    for j in range(3):
        ax = fig.add_subplot(gs[2, k * i + j : k * i + j + 1])
        ax.imshow(vid[j].permute(1, 2, 0), cmap="gray")
        ax.set_yticks([])
        ax.set_xticks([])
        if i == 0 and j == 0:
            ax.set_ylabel("Stream 2")
plt.tight_layout()
plt.show(block=False)
617
618
619
620

######################################################################
#
# Tag: :obj:`torchaudio.io`