Debian Codegraph @

ext/adaptivedemux2/hls/gsthlsdemux-stream.c

raw
1 /* GStreamer
2 * Copyright (C) 2010 Marc-Andre Lureau <[email protected]>
3 * Copyright (C) 2010 Andoni Morales Alastruey <[email protected]>
4 * Copyright (C) 2011, Hewlett-Packard Development Company, L.P.
5 * Author: Youness Alaoui <[email protected]>, Collabora Ltd.
6 * Author: Sebastian Dröge <[email protected]>, Collabora Ltd.
7 * Copyright (C) 2014 Sebastian Dröge <[email protected]>
8 * Copyright (C) 2015 Tim-Philipp Müller <[email protected]>
9 *
10 * Copyright (C) 2021-2022 Centricular Ltd
11 * Author: Edward Hervey <[email protected]>
12 * Author: Jan Schmidt <[email protected]>
13 *
14 * gsthlsdemux-stream.c:
15 *
16 * This library is free software; you can redistribute it and/or
17 * modify it under the terms of the GNU Library General Public
18 * License as published by the Free Software Foundation; either
19 * version 2 of the License, or (at your option) any later version.
20 *
21 * This library is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24 * Library General Public License for more details.
25 *
26 * You should have received a copy of the GNU Library General Public
27 * License along with this library; if not, write to the
28 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
29 * Boston, MA 02110-1301, USA.
30 */
31
32 #ifdef HAVE_CONFIG_H
33 # include "config.h"
34 #endif
35
36 #include <string.h>
37 #include <gst/base/gsttypefindhelper.h>
38 #include <gst/tag/tag.h>
39 #include <glib/gi18n-lib.h>
40
41 #include "gsthlsdemux.h"
42 #include "gsthlsdemux-stream.h"
43
44 GST_DEBUG_CATEGORY_EXTERN (gst_hls_demux2_debug);
45 #define GST_CAT_DEFAULT gst_hls_demux2_debug
46
47 /* Maximum values for mpeg-ts DTS values */
48 #define MPEG_TS_MAX_PTS (((((guint64)1) << 33) * (guint64)100000) / 9)
49
50 static GstBuffer *gst_hls_demux_decrypt_fragment (GstHLSDemux * demux,
51 GstHLSDemuxStream * stream, GstBuffer * encrypted_buffer, GError ** err);
52 static gboolean
53 gst_hls_demux_stream_decrypt_start (GstHLSDemuxStream * stream,
54 const guint8 * key_data, const guint8 * iv_data);
55 static void gst_hls_demux_stream_decrypt_end (GstHLSDemuxStream * stream);
56
57 static gboolean
58 gst_hls_demux_stream_start_fragment (GstAdaptiveDemux2Stream * stream);
59 static GstFlowReturn
60 gst_hls_demux_stream_finish_fragment (GstAdaptiveDemux2Stream * stream);
61 static GstFlowReturn gst_hls_demux_stream_data_received (GstAdaptiveDemux2Stream
62 * stream, GstBuffer * buffer);
63
64 static gboolean gst_hls_demux_stream_has_next_fragment (GstAdaptiveDemux2Stream
65 * stream);
66 static GstFlowReturn
67 gst_hls_demux_stream_advance_fragment (GstAdaptiveDemux2Stream * stream);
68 static GstFlowReturn
69 gst_hls_demux_stream_update_fragment_info (GstAdaptiveDemux2Stream * stream);
70 static GstFlowReturn
71 gst_hls_demux_stream_submit_request (GstAdaptiveDemux2Stream * stream,
72 DownloadRequest * download_req);
73 static void gst_hls_demux_stream_start (GstAdaptiveDemux2Stream * stream);
74 static void gst_hls_demux_stream_stop (GstAdaptiveDemux2Stream * stream);
75 static void gst_hls_demux_stream_create_tracks (GstAdaptiveDemux2Stream *
76 stream);
77 static gboolean gst_hls_demux_stream_select_bitrate (GstAdaptiveDemux2Stream *
78 stream, guint64 bitrate);
79 static GstClockTime
80 gst_hls_demux_stream_get_presentation_offset (GstAdaptiveDemux2Stream * stream);
81
82 static void gst_hls_demux_stream_finalize (GObject * object);
83
84 #define gst_hls_demux_stream_parent_class stream_parent_class
85 G_DEFINE_TYPE (GstHLSDemuxStream, gst_hls_demux_stream,
86 GST_TYPE_ADAPTIVE_DEMUX2_STREAM);
87
88 static void
89 gst_hls_demux_stream_class_init (GstHLSDemuxStreamClass * klass)
90 {
91 GObjectClass *gobject_class = (GObjectClass *) klass;
92 GstAdaptiveDemux2StreamClass *adaptivedemux2stream_class =
93 GST_ADAPTIVE_DEMUX2_STREAM_CLASS (klass);
94
95 gobject_class->finalize = gst_hls_demux_stream_finalize;
96
97 adaptivedemux2stream_class->update_fragment_info =
98 gst_hls_demux_stream_update_fragment_info;
99 adaptivedemux2stream_class->submit_request =
100 gst_hls_demux_stream_submit_request;
101 adaptivedemux2stream_class->has_next_fragment =
102 gst_hls_demux_stream_has_next_fragment;
103 adaptivedemux2stream_class->stream_seek = gst_hls_demux_stream_seek;
104 adaptivedemux2stream_class->advance_fragment =
105 gst_hls_demux_stream_advance_fragment;
106 adaptivedemux2stream_class->select_bitrate =
107 gst_hls_demux_stream_select_bitrate;
108 adaptivedemux2stream_class->start = gst_hls_demux_stream_start;
109 adaptivedemux2stream_class->stop = gst_hls_demux_stream_stop;
110 adaptivedemux2stream_class->create_tracks =
111 gst_hls_demux_stream_create_tracks;
112
113 adaptivedemux2stream_class->start_fragment =
114 gst_hls_demux_stream_start_fragment;
115 adaptivedemux2stream_class->finish_fragment =
116 gst_hls_demux_stream_finish_fragment;
117 adaptivedemux2stream_class->data_received =
118 gst_hls_demux_stream_data_received;
119 adaptivedemux2stream_class->get_presentation_offset =
120 gst_hls_demux_stream_get_presentation_offset;
121
122 }
123
124 static void
125 gst_hls_demux_stream_init (GstHLSDemuxStream * stream)
126 {
127 stream->parser_type = GST_HLS_PARSER_NONE;
128 stream->do_typefind = TRUE;
129 stream->reset_pts = TRUE;
130 stream->presentation_offset = 60 * GST_SECOND;
131 stream->pdt_tag_sent = FALSE;
132 }
133
134 void
135 gst_hls_demux_stream_clear_pending_data (GstHLSDemuxStream * hls_stream,
136 gboolean force)
137 {
138 GST_DEBUG_OBJECT (hls_stream, "force : %d", force);
139 if (hls_stream->pending_encrypted_data)
140 gst_adapter_clear (hls_stream->pending_encrypted_data);
141 gst_buffer_replace (&hls_stream->pending_decrypted_buffer, NULL);
142 gst_buffer_replace (&hls_stream->pending_typefind_buffer, NULL);
143 if (force || !hls_stream->pending_data_is_header) {
144 gst_buffer_replace (&hls_stream->pending_segment_data, NULL);
145 hls_stream->pending_data_is_header = FALSE;
146 }
147 hls_stream->current_offset = -1;
148 hls_stream->process_buffer_content = TRUE;
149 gst_hls_demux_stream_decrypt_end (hls_stream);
150 }
151
152 GstFlowReturn
153 gst_hls_demux_stream_seek (GstAdaptiveDemux2Stream * stream, gboolean forward,
154 GstSeekFlags flags, GstClockTimeDiff ts, GstClockTimeDiff * final_ts)
155 {
156 GstFlowReturn ret = GST_FLOW_OK;
157 GstHLSDemuxStream *hls_stream = GST_HLS_DEMUX_STREAM_CAST (stream);
158 GstHLSDemux *hlsdemux = (GstHLSDemux *) stream->demux;
159
160 GST_DEBUG_OBJECT (stream,
161 "is_variant:%d media:%p current_variant:%p forward:%d ts:%"
162 GST_TIME_FORMAT, hls_stream->is_variant, hls_stream->current_rendition,
163 hlsdemux->current_variant, forward, GST_TIME_ARGS (ts));
164
165 /* If this stream doesn't have a playlist yet, we can't seek on it */
166 if (!hls_stream->playlist_fetched) {
167 return GST_ADAPTIVE_DEMUX_FLOW_BUSY;
168 }
169
170 /* Allow jumping to partial segments in the last 2 segments in LL-HLS */
171 if (GST_HLS_MEDIA_PLAYLIST_IS_LIVE (hls_stream->playlist))
172 flags |= GST_HLS_M3U8_SEEK_FLAG_ALLOW_PARTIAL;
173
174 GstM3U8SeekResult seek_result;
175 if (gst_hls_media_playlist_seek (hls_stream->playlist, forward, flags, ts,
176 &seek_result)) {
177 if (hls_stream->current_segment)
178 gst_m3u8_media_segment_unref (hls_stream->current_segment);
179 hls_stream->current_segment = seek_result.segment;
180 hls_stream->in_partial_segments = seek_result.found_partial_segment;
181 hls_stream->part_idx = seek_result.part_idx;
182
183 hls_stream->reset_pts = TRUE;
184 if (final_ts)
185 *final_ts = seek_result.stream_time;
186 } else {
187 GST_WARNING_OBJECT (stream, "Seeking failed");
188 ret = GST_FLOW_ERROR;
189 }
190
191 return ret;
192 }
193
194 static GstCaps *
195 get_caps_of_stream_type (GstCaps * full_caps, GstStreamType streamtype)
196 {
197 GstCaps *ret = NULL;
198
199 guint i;
200 for (i = 0; i < gst_caps_get_size (full_caps); i++) {
201 GstStructure *st = gst_caps_get_structure (full_caps, i);
202
203 if (gst_hls_get_stream_type_from_structure (st) == streamtype) {
204 ret = gst_caps_new_empty ();
205 gst_caps_append_structure (ret, gst_structure_copy (st));
206 break;
207 }
208 }
209
210 return ret;
211 }
212
213 static GstHLSRenditionStream *
214 find_uriless_rendition (GstHLSDemux * demux, GstStreamType stream_type)
215 {
216 GList *tmp;
217
218 for (tmp = demux->master->renditions; tmp; tmp = tmp->next) {
219 GstHLSRenditionStream *media = tmp->data;
220 if (media->uri == NULL &&
221 gst_stream_type_from_hls_type (media->mtype) == stream_type)
222 return media;
223 }
224 return NULL;
225 }
226
227 static void
228 gst_hls_demux_stream_create_tracks (GstAdaptiveDemux2Stream * stream)
229 {
230 GstHLSDemux *hlsdemux = (GstHLSDemux *) stream->demux;
231 GstHLSDemuxStream *hlsdemux_stream = (GstHLSDemuxStream *) stream;
232 guint i;
233 GstStreamType uriless_types = 0;
234 GstCaps *variant_caps = NULL;
235
236 GST_DEBUG_OBJECT (stream, "Update tracks of variant stream");
237
238 if (hlsdemux->master->have_codecs) {
239 variant_caps = gst_hls_master_playlist_get_common_caps (hlsdemux->master);
240 }
241
242 /* Use the stream->stream_collection and manifest to create the appropriate tracks */
243 for (i = 0; i < gst_stream_collection_get_size (stream->stream_collection);
244 i++) {
245 GstStream *gst_stream =
246 gst_stream_collection_get_stream (stream->stream_collection, i);
247 GstStreamType stream_type = gst_stream_get_stream_type (gst_stream);
248 GstAdaptiveDemuxTrack *track;
249 GstHLSRenditionStream *embedded_media = NULL;
250 /* tracks from the variant streams should be prefered over those provided by renditions */
251 GstStreamFlags flags =
252 gst_stream_get_stream_flags (gst_stream) | GST_STREAM_FLAG_SELECT;
253 GstCaps *manifest_caps = NULL;
254
255 if (stream_type == GST_STREAM_TYPE_UNKNOWN)
256 continue;
257
258 if (variant_caps)
259 manifest_caps = get_caps_of_stream_type (variant_caps, stream_type);
260 hlsdemux_stream->rendition_type |= stream_type;
261
262 if ((uriless_types & stream_type) == 0) {
263 /* Do we have a uriless media for this stream type */
264 /* Find if there is a rendition without URI, it will be provided by this variant */
265 embedded_media = find_uriless_rendition (hlsdemux, stream_type);
266 /* Remember we used this type for a embedded media */
267 uriless_types |= stream_type;
268 }
269
270 if (embedded_media) {
271 GstTagList *tags = gst_stream_get_tags (gst_stream);
272 GST_DEBUG_OBJECT (stream, "Adding track '%s' to main variant stream",
273 embedded_media->name);
274 track =
275 gst_hls_demux_new_track_for_rendition (hlsdemux, embedded_media,
276 manifest_caps, flags,
277 tags ? gst_tag_list_make_writable (tags) : tags);
278 } else {
279 gchar *stream_id;
280 stream_id =
281 g_strdup_printf ("main-%s-%d", gst_stream_type_get_name (stream_type),
282 i);
283
284 GST_DEBUG_OBJECT (stream, "Adding track '%s' to main variant stream",
285 stream_id);
286 track =
287 gst_adaptive_demux_track_new (stream->demux, stream_type,
288 flags, stream_id, manifest_caps, NULL);
289 g_free (stream_id);
290 }
291 track->upstream_stream_id =
292 g_strdup (gst_stream_get_stream_id (gst_stream));
293 gst_adaptive_demux2_stream_add_track (stream, track);
294 gst_adaptive_demux_track_unref (track);
295 }
296
297 if (variant_caps)
298 gst_caps_unref (variant_caps);
299
300 /* Update the stream object with rendition types.
301 * FIXME: rendition_type could be removed */
302 stream->stream_type = hlsdemux_stream->rendition_type;
303 }
304
305 static gboolean
306 gst_hls_demux_stream_start_fragment (GstAdaptiveDemux2Stream * stream)
307 {
308 GstHLSDemuxStream *hls_stream = GST_HLS_DEMUX_STREAM_CAST (stream);
309 GstHLSDemux *hlsdemux = GST_HLS_DEMUX_CAST (stream->demux);
310 const GstHLSKey *key;
311 GstHLSMediaPlaylist *m3u8;
312
313 GST_DEBUG_OBJECT (stream, "Fragment starting");
314
315 gst_hls_demux_stream_clear_pending_data (hls_stream, FALSE);
316
317 /* If no decryption is needed, there's nothing to be done here */
318 if (hls_stream->current_key == NULL)
319 return TRUE;
320
321 m3u8 = hls_stream->playlist;
322
323 key = gst_hls_demux_get_key (hlsdemux, hls_stream->current_key,
324 m3u8->uri, m3u8->allowcache);
325
326 if (key == NULL)
327 goto key_failed;
328
329 if (!gst_hls_demux_stream_decrypt_start (hls_stream, key->data,
330 hls_stream->current_iv))
331 goto decrypt_start_failed;
332
333 return TRUE;
334
335 key_failed:
336 {
337 GST_ELEMENT_ERROR (hlsdemux, STREAM, DECRYPT_NOKEY,
338 ("Couldn't retrieve key for decryption"), (NULL));
339 GST_WARNING_OBJECT (hlsdemux, "Failed to decrypt data");
340 return FALSE;
341 }
342 decrypt_start_failed:
343 {
344 GST_ELEMENT_ERROR (hlsdemux, STREAM, DECRYPT, ("Failed to start decrypt"),
345 ("Couldn't set key and IV or plugin was built without crypto library"));
346 return FALSE;
347 }
348 }
349
350 static GstHLSParserType
351 caps_to_parser_type (const GstCaps * caps)
352 {
353 const GstStructure *s = gst_caps_get_structure (caps, 0);
354
355 if (gst_structure_has_name (s, "video/mpegts"))
356 return GST_HLS_PARSER_MPEGTS;
357 if (gst_structure_has_name (s, "application/x-id3"))
358 return GST_HLS_PARSER_ID3;
359 if (gst_structure_has_name (s, "application/x-subtitle-vtt"))
360 return GST_HLS_PARSER_WEBVTT;
361 if (gst_structure_has_name (s, "video/quicktime"))
362 return GST_HLS_PARSER_ISOBMFF;
363
364 return GST_HLS_PARSER_NONE;
365 }
366
367 /* Identify the nature of data for this stream
368 *
369 * Will also setup the appropriate parser (tsreader) if needed
370 *
371 * Consumes the input buffer when it returns FALSE, but
372 * replaces / returns the input buffer in the `buffer` parameter
373 * when it returns TRUE.
374 *
375 * Returns TRUE if we are done with typefinding */
376 static gboolean
377 gst_hls_demux_typefind_stream (GstHLSDemux * hlsdemux,
378 GstAdaptiveDemux2Stream * stream, GstBuffer ** out_buffer, gboolean at_eos,
379 GstFlowReturn * ret)
380 {
381 GstHLSDemuxStream *hls_stream = GST_HLS_DEMUX_STREAM_CAST (stream); // FIXME: pass HlsStream into function
382 GstCaps *caps = NULL;
383 guint buffer_size;
384 GstTypeFindProbability prob = GST_TYPE_FIND_NONE;
385 GstMapInfo info;
386 GstBuffer *buffer = *out_buffer;
387
388 if (hls_stream->pending_typefind_buffer) {
389 /* Append to the existing typefind buffer and create a new one that
390 * we'll return (or consume below) */
391 buffer = *out_buffer =
392 gst_buffer_append (hls_stream->pending_typefind_buffer, buffer);
393 hls_stream->pending_typefind_buffer = NULL;
394 }
395
396 gst_buffer_map (buffer, &info, GST_MAP_READ);
397 buffer_size = info.size;
398
399 /* Typefind could miss if buffer is too small. In this case we
400 * will retry later */
401 if (buffer_size >= (2 * 1024) || at_eos) {
402 caps =
403 gst_type_find_helper_for_data (GST_OBJECT_CAST (hlsdemux), info.data,
404 info.size, &prob);
405 }
406
407 if (G_UNLIKELY (!caps)) {
408 /* Won't need this mapping any more all paths return inside this if() */
409 gst_buffer_unmap (buffer, &info);
410
411 /* Only fail typefinding if we already a good amount of data
412 * and we still don't know the type */
413 if (buffer_size > (2 * 1024 * 1024) || at_eos) {
414 GST_ELEMENT_ERROR (hlsdemux, STREAM, TYPE_NOT_FOUND,
415 ("Could not determine type of stream"), (NULL));
416 gst_buffer_unref (buffer);
417 *ret = GST_FLOW_NOT_NEGOTIATED;
418 } else {
419 GST_LOG_OBJECT (stream, "Not enough data to typefind");
420 hls_stream->pending_typefind_buffer = buffer; /* Transfer the ref */
421 *ret = GST_FLOW_OK;
422 }
423 *out_buffer = NULL;
424 return FALSE;
425 }
426
427 GST_DEBUG_OBJECT (stream,
428 "Typefind result: %" GST_PTR_FORMAT " prob:%d", caps, prob);
429
430 if (hls_stream->parser_type == GST_HLS_PARSER_NONE) {
431 hls_stream->parser_type = caps_to_parser_type (caps);
432 if (hls_stream->parser_type == GST_HLS_PARSER_NONE) {
433 GST_WARNING_OBJECT (stream,
434 "Unsupported stream type %" GST_PTR_FORMAT, caps);
435 GST_MEMDUMP_OBJECT (stream, "unknown data", info.data,
436 MIN (info.size, 128));
437 gst_buffer_unref (buffer);
438 *ret = GST_FLOW_ERROR;
439 return FALSE;
440 }
441 if (hls_stream->parser_type == GST_HLS_PARSER_ISOBMFF)
442 hls_stream->presentation_offset = 0;
443 }
444
445 gst_adaptive_demux2_stream_set_caps (stream, caps);
446
447 hls_stream->do_typefind = FALSE;
448
449 gst_buffer_unmap (buffer, &info);
450
451 /* We are done with typefinding. Doesn't consume the input buffer */
452 *ret = GST_FLOW_OK;
453 return TRUE;
454 }
455
456 /* Compute the stream time for the given internal time, based on the provided
457 * time map.
458 *
459 * Will handle mpeg-ts wraparound. */
460 GstClockTimeDiff
461 gst_hls_internal_to_stream_time (GstHLSTimeMap * map,
462 GstClockTime internal_time)
463 {
464 if (map->internal_time == GST_CLOCK_TIME_NONE)
465 return GST_CLOCK_STIME_NONE;
466
467 /* Handle MPEG-TS Wraparound */
468 if (internal_time < map->internal_time &&
469 map->internal_time - internal_time > (MPEG_TS_MAX_PTS / 2))
470 internal_time += MPEG_TS_MAX_PTS;
471
472 return (map->stream_time + internal_time - map->internal_time);
473 }
474
475 /* Handle the internal time discovered on a segment.
476 *
477 * This function is called by the individual buffer parsers once they have
478 * extracted that internal time (which is most of the time based on mpegts time,
479 * but can also be ISOBMFF pts).
480 *
481 * This will update the time map when appropriate.
482 *
483 * If a synchronization issue is detected, the appropriate steps will be taken
484 * and the RESYNC return value will be returned
485 */
486 GstHLSParserResult
487 gst_hlsdemux_stream_handle_internal_time (GstHLSDemuxStream * hls_stream,
488 GstClockTime internal_time)
489 {
490 GstM3U8MediaSegment *current_segment = hls_stream->current_segment;
491 GstHLSTimeMap *map;
492 GstClockTimeDiff current_stream_time;
493 GstClockTimeDiff real_stream_time, difference;
494
495 g_return_val_if_fail (current_segment != NULL, GST_HLS_PARSER_RESULT_ERROR);
496
497 current_stream_time = current_segment->stream_time;
498 if (hls_stream->in_partial_segments) {
499 /* If the current partial segment is valid, update the stream current position to the partial
500 * segment stream_time, otherwise leave it alone and fix it up later when we resync */
501 if (current_segment->partial_segments
502 && hls_stream->part_idx < current_segment->partial_segments->len) {
503 GstM3U8PartialSegment *part =
504 g_ptr_array_index (current_segment->partial_segments,
505 hls_stream->part_idx);
506 current_stream_time = part->stream_time;
507 }
508 }
509
510 GST_DEBUG_OBJECT (hls_stream,
511 "Got internal time %" GST_TIME_FORMAT " for current segment stream time %"
512 GST_STIME_FORMAT, GST_TIME_ARGS (internal_time),
513 GST_STIME_ARGS (current_stream_time));
514
515 GstHLSDemux *demux =
516 GST_HLS_DEMUX_CAST (GST_ADAPTIVE_DEMUX2_STREAM_CAST (hls_stream)->demux);
517 map = gst_hls_demux_find_time_map (demux, current_segment->discont_sequence);
518
519 /* Time mappings will always be created upon initial parsing and when advancing */
520 g_assert (map);
521
522 /* Handle the first internal time of a discont sequence. We can only store/use
523 * those values for variant streams. */
524 if (!GST_CLOCK_TIME_IS_VALID (map->internal_time)) {
525 if (!hls_stream->is_variant) {
526 GST_WARNING_OBJECT (hls_stream,
527 "Got data from a new discont sequence on a rendition stream, can't validate stream time");
528 return GST_HLS_PARSER_RESULT_DONE;
529 }
530
531 /* The stream time for a mapping should always be positive ! */
532 gboolean stream_time_valid = current_stream_time >= 0;
533
534 GST_CAT_LEVEL_LOG (GST_CAT_DEFAULT,
535 stream_time_valid ? GST_LEVEL_DEBUG : GST_LEVEL_ERROR, hls_stream,
536 "Updating time map dsn:%" G_GINT64_FORMAT " stream_time:%"
537 GST_STIME_FORMAT " internal_time:%" GST_TIME_FORMAT, map->dsn,
538 GST_STIME_ARGS (current_stream_time), GST_TIME_ARGS (internal_time));
539
540 if (!stream_time_valid) {
541 GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
542 (NULL), ("Negative stream time, please file a bug"));
543 return GST_HLS_PARSER_RESULT_ERROR;
544 }
545
546 if (hls_stream->parser_type == GST_HLS_PARSER_ISOBMFF)
547 hls_stream->presentation_offset = internal_time - current_stream_time;
548
549 gst_time_map_set_values (map, current_stream_time, internal_time,
550 current_segment->datetime);
551
552 gst_hls_demux_start_rendition_streams (demux);
553 return GST_HLS_PARSER_RESULT_DONE;
554 }
555
556 /* The information in a discont is always valid */
557 if (current_segment->discont) {
558 GST_DEBUG_OBJECT (hls_stream,
559 "DISCONT segment, Updating time map to stream_time:%" GST_STIME_FORMAT
560 " internal_time:%" GST_TIME_FORMAT,
561 GST_STIME_ARGS (current_stream_time), GST_TIME_ARGS (internal_time));
562 gst_time_map_set_values (map, current_stream_time, internal_time,
563 current_segment->datetime);
564 return GST_HLS_PARSER_RESULT_DONE;
565 }
566
567 /* Check if the segment is the expected one */
568 real_stream_time = gst_hls_internal_to_stream_time (map, internal_time);
569 difference = current_stream_time - real_stream_time;
570 GST_DEBUG_OBJECT (hls_stream,
571 "Segment contains stream time %" GST_STIME_FORMAT
572 " difference against expected : %" GST_STIME_FORMAT,
573 GST_STIME_ARGS (real_stream_time), GST_STIME_ARGS (difference));
574
575 /* We allow a tolerance of 3-4 frames between the estimated and observed
576 * stream time. */
577 if (ABS (difference) > 100 * GST_MSECOND) {
578 GstClockTimeDiff wrong_position_threshold =
579 hls_stream->current_segment->duration / 2;
580
581 /* Update the value */
582 GST_DEBUG_OBJECT (hls_stream,
583 "Updating current stream time to %" GST_STIME_FORMAT,
584 GST_STIME_ARGS (real_stream_time));
585
586 /* For LL-HLS, make sure to update and recalculate stream time from
587 * the right partial segment if playing one */
588 if (hls_stream->in_partial_segments && hls_stream->part_idx != 0) {
589 if (current_segment->partial_segments
590 && hls_stream->part_idx < current_segment->partial_segments->len) {
591 GstM3U8PartialSegment *part =
592 g_ptr_array_index (current_segment->partial_segments,
593 hls_stream->part_idx);
594 part->stream_time = real_stream_time;
595
596 gst_hls_media_playlist_recalculate_stream_time_from_part
597 (hls_stream->playlist, hls_stream->current_segment,
598 hls_stream->part_idx);
599
600 /* When playing partial segments, the "Wrong position" threshold should be
601 * half the part duration */
602 wrong_position_threshold = part->duration / 2;
603 }
604 } else {
605 /* Aligned to the start of the segment, update there */
606 current_segment->stream_time = real_stream_time;
607 gst_hls_media_playlist_recalculate_stream_time (hls_stream->playlist,
608 hls_stream->current_segment);
609 }
610 gst_hls_media_playlist_dump (hls_stream->playlist);
611
612 if (ABS (difference) > wrong_position_threshold) {
613 GstAdaptiveDemux2Stream *stream = (GstAdaptiveDemux2Stream *) hls_stream;
614 GstM3U8SeekResult seek_result;
615
616 /* We are at the wrong segment, try to figure out the *actual* segment */
617 GST_DEBUG_OBJECT (hls_stream,
618 "Trying to find the correct segment in the playlist for %"
619 GST_STIME_FORMAT, GST_STIME_ARGS (current_stream_time));
620 if (gst_hls_media_playlist_find_position (hls_stream->playlist,
621 current_stream_time, hls_stream->in_partial_segments,
622 &seek_result)) {
623
624 GST_DEBUG_OBJECT (hls_stream, "Synced to position %" GST_STIME_FORMAT,
625 GST_STIME_ARGS (seek_result.stream_time));
626
627 gst_m3u8_media_segment_unref (hls_stream->current_segment);
628 hls_stream->current_segment = seek_result.segment;
629 hls_stream->in_partial_segments = seek_result.found_partial_segment;
630 hls_stream->part_idx = seek_result.part_idx;
631
632 /* Ask parent class to restart this fragment */
633 return GST_HLS_PARSER_RESULT_RESYNC;
634 }
635
636 GST_WARNING_OBJECT (hls_stream,
637 "Could not find a replacement stream, carrying on with segment");
638 stream->discont = TRUE;
639 stream->fragment.stream_time = current_stream_time;
640 gst_time_map_set_values (map, current_stream_time, internal_time,
641 hls_stream->current_segment->datetime);
642 }
643 }
644
645 return GST_HLS_PARSER_RESULT_DONE;
646 }
647
648 static GstHLSParserResult
649 gst_hls_demux_handle_buffer_content (GstHLSDemux * demux,
650 GstHLSDemuxStream * hls_stream, gboolean draining, GstBuffer ** buffer)
651 {
652 GstHLSTimeMap *map;
653 GstAdaptiveDemux2Stream *stream = (GstAdaptiveDemux2Stream *) hls_stream;
654 GstClockTimeDiff current_stream_time =
655 hls_stream->current_segment->stream_time;
656 GstClockTime current_duration = hls_stream->current_segment->duration;
657 GstHLSParserResult parser_ret;
658
659 GST_LOG_OBJECT (stream,
660 "stream_time:%" GST_STIME_FORMAT " duration:%" GST_TIME_FORMAT
661 " discont:%d draining:%d header:%d index:%d",
662 GST_STIME_ARGS (current_stream_time), GST_TIME_ARGS (current_duration),
663 hls_stream->current_segment->discont, draining,
664 stream->downloading_header, stream->downloading_index);
665
666 /* FIXME : Replace the boolean parser return value (and this function's return
667 * value) by an enum which clearly specifies whether:
668 *
669 * * The content parsing happened succesfully and it no longer needs to be
670 * called for the remainder of this fragment
671 * * More data is needed in order to parse the data
672 * * There was a fatal error parsing the contents (ex: invalid/incompatible
673 * content)
674 * * The computed fragment stream time is out of sync
675 */
676
677 g_assert (demux->mappings);
678 map =
679 gst_hls_demux_find_time_map (demux,
680 hls_stream->current_segment->discont_sequence);
681 if (!map) {
682 /* For rendition streams, we can't do anything without time mapping */
683 if (!hls_stream->is_variant) {
684 GST_DEBUG_OBJECT (stream,
685 "No available time mapping for dsn:%" G_GINT64_FORMAT
686 " using estimated stream time",
687 hls_stream->current_segment->discont_sequence);
688 goto out_done;
689 }
690
691 /* Variants will be able to fill in the the time mapping, so we can carry on without a time mapping */
692 } else {
693 GST_DEBUG_OBJECT (stream,
694 "Using mapping dsn:%" G_GINT64_FORMAT " stream_time:%" GST_TIME_FORMAT
695 " internal_time:%" GST_TIME_FORMAT, map->dsn,
696 GST_TIME_ARGS (map->stream_time), GST_TIME_ARGS (map->internal_time));
697 }
698
699 switch (hls_stream->parser_type) {
700 case GST_HLS_PARSER_MPEGTS:
701 parser_ret =
702 gst_hlsdemux_handle_content_mpegts (demux, hls_stream, draining,
703 buffer);
704 break;
705 case GST_HLS_PARSER_ID3:
706 parser_ret =
707 gst_hlsdemux_handle_content_id3 (demux, hls_stream, draining, buffer);
708 break;
709 case GST_HLS_PARSER_WEBVTT:
710 {
711 /* Furthermore it will handle timeshifting itself */
712 parser_ret =
713 gst_hlsdemux_handle_content_webvtt (demux, hls_stream, draining,
714 buffer);
715 break;
716 }
717 case GST_HLS_PARSER_ISOBMFF:
718 parser_ret =
719 gst_hlsdemux_handle_content_isobmff (demux, hls_stream, draining,
720 buffer);
721 break;
722 case GST_HLS_PARSER_NONE:
723 default:
724 {
725 GST_ERROR_OBJECT (stream, "Unknown stream type");
726 goto out_error;
727 }
728 }
729
730 if (parser_ret == GST_HLS_PARSER_RESULT_NEED_MORE_DATA) {
731 if (stream->downloading_index || stream->downloading_header)
732 goto out_need_more;
733 if (draining) {
734 /* Else if we're draining, move to next fragment */
735 return gst_hlsdemux_stream_handle_internal_time (hls_stream,
736 hls_stream->current_segment->stream_time);
737 }
738
739 /* Else we just need more data */
740 goto out_need_more;
741 }
742
743 if (parser_ret == GST_HLS_PARSER_RESULT_ERROR)
744 goto out_error;
745
746 if (parser_ret == GST_HLS_PARSER_RESULT_RESYNC)
747 goto out_resync;
748
749 out_done:
750 GST_DEBUG_OBJECT (stream, "Done. Finished parsing");
751 return GST_HLS_PARSER_RESULT_DONE;
752
753 out_error:
754 GST_DEBUG_OBJECT (stream, "Done. Error while parsing");
755 return GST_HLS_PARSER_RESULT_ERROR;
756
757 out_need_more:
758 GST_DEBUG_OBJECT (stream, "Done. Need more data");
759 return GST_HLS_PARSER_RESULT_NEED_MORE_DATA;
760
761 out_resync:
762 GST_DEBUG_OBJECT (stream, "Done. Resync required");
763 return GST_HLS_PARSER_RESULT_RESYNC;
764 }
765
766 static GstFlowReturn
767 gst_hls_demux_stream_handle_buffer (GstAdaptiveDemux2Stream * stream,
768 GstBuffer * buffer, gboolean at_eos)
769 {
770 GstHLSDemuxStream *hls_stream = GST_HLS_DEMUX_STREAM_CAST (stream); // FIXME: pass HlsStream into function
771 GstHLSDemux *hlsdemux = GST_HLS_DEMUX_CAST (stream->demux);
772 GstFlowReturn ret = GST_FLOW_OK;
773 GstBuffer *pending_header_data = NULL;
774
775 /* If current segment is not present, this means that a playlist update
776 * happened between the moment ::update_fragment_info() was called and the
777 * moment we received data. And that playlist update couldn't match the
778 * current position. This will happen in live playback when we are downloading
779 * too slowly, therefore we try to "catch up" back to live
780 */
781 if (hls_stream->current_segment == NULL) {
782 GST_WARNING_OBJECT (stream, "Lost sync");
783 /* Drop the buffer */
784 gst_buffer_unref (buffer);
785 return GST_ADAPTIVE_DEMUX_FLOW_LOST_SYNC;
786 }
787
788 GST_DEBUG_OBJECT (stream,
789 "buffer:%p at_eos:%d do_typefind:%d uri:%s", buffer, at_eos,
790 hls_stream->do_typefind, GST_STR_NULL (stream->fragment.uri));
791
792 if (buffer == NULL)
793 goto out;
794
795 /* If we need to do typefind and we're not done with it (or we errored), return */
796 if (G_UNLIKELY (hls_stream->do_typefind) &&
797 !gst_hls_demux_typefind_stream (hlsdemux, stream, &buffer, at_eos,
798 &ret)) {
799 goto out;
800 }
801 g_assert (hls_stream->pending_typefind_buffer == NULL);
802
803 if (hls_stream->process_buffer_content) {
804 GstHLSParserResult parse_ret;
805
806 if (hls_stream->pending_segment_data) {
807 if (hls_stream->pending_data_is_header) {
808 /* Keep a copy of the header data in case we need to requeue it
809 * due to GST_ADAPTIVE_DEMUX_FLOW_RESTART_FRAGMENT below */
810 pending_header_data = gst_buffer_ref (hls_stream->pending_segment_data);
811 }
812 buffer = gst_buffer_append (hls_stream->pending_segment_data, buffer);
813 hls_stream->pending_segment_data = NULL;
814 }
815
816 /* Try to get the timing information */
817 parse_ret =
818 gst_hls_demux_handle_buffer_content (hlsdemux, hls_stream, at_eos,
819 &buffer);
820
821 switch (parse_ret) {
822 case GST_HLS_PARSER_RESULT_NEED_MORE_DATA:
823 /* If we don't have enough, store and return */
824 hls_stream->pending_segment_data = buffer;
825 hls_stream->pending_data_is_header =
826 (stream->downloading_header == TRUE);
827 if (hls_stream->pending_data_is_header)
828 stream->send_segment = TRUE;
829 goto out;
830 case GST_HLS_PARSER_RESULT_ERROR:
831 /* Error, drop buffer and return */
832 gst_buffer_unref (buffer);
833 ret = GST_FLOW_ERROR;
834 goto out;
835 case GST_HLS_PARSER_RESULT_RESYNC:
836 /* Resync, drop buffer and return */
837 gst_buffer_unref (buffer);
838 ret = GST_ADAPTIVE_DEMUX_FLOW_RESTART_FRAGMENT;
839 /* If we had a pending set of header data, requeue it */
840 if (pending_header_data != NULL) {
841 g_assert (hls_stream->pending_segment_data == NULL);
842
843 GST_DEBUG_OBJECT (hls_stream,
844 "Requeueing header data %" GST_PTR_FORMAT
845 " before returning RESTART_FRAGMENT", pending_header_data);
846 hls_stream->pending_segment_data = pending_header_data;
847 pending_header_data = NULL;
848 }
849 goto out;
850 case GST_HLS_PARSER_RESULT_DONE:
851 /* Done parsing, carry on */
852 hls_stream->process_buffer_content = FALSE;
853 break;
854 }
855 }
856
857 if (!buffer)
858 goto out;
859
860 buffer = gst_buffer_make_writable (buffer);
861
862 GST_BUFFER_OFFSET (buffer) = hls_stream->current_offset;
863 hls_stream->current_offset += gst_buffer_get_size (buffer);
864 GST_BUFFER_OFFSET_END (buffer) = hls_stream->current_offset;
865
866 GST_DEBUG_OBJECT (stream, "We have a buffer, pushing: %" GST_PTR_FORMAT,
867 buffer);
868
869 ret = gst_adaptive_demux2_stream_push_buffer (stream, buffer);
870
871 out:
872 if (pending_header_data != NULL) {
873 /* Throw away the pending header data now. If it wasn't consumed above,
874 * we won't need it */
875 gst_buffer_unref (pending_header_data);
876 }
877
878 GST_DEBUG_OBJECT (stream, "Returning %s", gst_flow_get_name (ret));
879 return ret;
880 }
881
882 static GstFlowReturn
883 gst_hls_demux_stream_finish_fragment (GstAdaptiveDemux2Stream * stream)
884 {
885 GstHLSDemuxStream *hls_stream = GST_HLS_DEMUX_STREAM_CAST (stream); // FIXME: pass HlsStream into function
886 GstFlowReturn ret = GST_FLOW_OK;
887
888 GST_DEBUG_OBJECT (stream, "Finishing %ssegment uri:%s",
889 hls_stream->in_partial_segments ? "partial " : "",
890 GST_STR_NULL (stream->fragment.uri));
891
892 /* Drain all pending data */
893 if (hls_stream->current_key)
894 gst_hls_demux_stream_decrypt_end (hls_stream);
895
896 if (hls_stream->current_segment && stream->last_ret == GST_FLOW_OK) {
897 if (hls_stream->pending_decrypted_buffer) {
898 if (hls_stream->current_key) {
899 GstMapInfo info;
900 gssize unpadded_size;
901
902 /* Handle pkcs7 unpadding here */
903 gst_buffer_map (hls_stream->pending_decrypted_buffer, &info,
904 GST_MAP_READ);
905 unpadded_size = info.size - info.data[info.size - 1];
906 gst_buffer_unmap (hls_stream->pending_decrypted_buffer, &info);
907
908 gst_buffer_resize (hls_stream->pending_decrypted_buffer, 0,
909 unpadded_size);
910 }
911
912 ret =
913 gst_hls_demux_stream_handle_buffer (stream,
914 hls_stream->pending_decrypted_buffer, TRUE);
915 hls_stream->pending_decrypted_buffer = NULL;
916 }
917
918 if (ret == GST_FLOW_OK || ret == GST_FLOW_NOT_LINKED) {
919 if (G_UNLIKELY (hls_stream->pending_typefind_buffer)) {
920 GstBuffer *buf = hls_stream->pending_typefind_buffer;
921 hls_stream->pending_typefind_buffer = NULL;
922
923 gst_hls_demux_stream_handle_buffer (stream, buf, TRUE);
924 }
925
926 if (hls_stream->pending_segment_data) {
927 GstBuffer *buf = hls_stream->pending_segment_data;
928 hls_stream->pending_segment_data = NULL;
929
930 ret = gst_hls_demux_stream_handle_buffer (stream, buf, TRUE);
931 }
932 }
933 }
934
935 gst_hls_demux_stream_clear_pending_data (hls_stream, FALSE);
936
937 if (G_UNLIKELY (stream->downloading_header || stream->downloading_index))
938 return GST_FLOW_OK;
939
940 if (hls_stream->current_segment == NULL) {
941 /* We can't advance, we just return OK for now and let the base class
942 * trigger a new download (or fail and resync itself) */
943 GST_DEBUG_OBJECT (stream, "Can't advance - current_segment is NULL");
944 return GST_FLOW_OK;
945 }
946
947 if (ret == GST_FLOW_OK || ret == GST_FLOW_NOT_LINKED) {
948 GstClockTime duration = hls_stream->current_segment->duration;
949
950 /* We can update the stream current position with a more accurate value
951 * before advancing. Note that we don't have any period so we can set the
952 * stream_time as-is on the stream current position */
953 if (hls_stream->in_partial_segments) {
954 GstM3U8MediaSegment *cur_segment = hls_stream->current_segment;
955
956 /* If the current partial segment is valid, update the stream current position, otherwise
957 * leave it alone and fix it up later when we resync */
958 if (cur_segment->partial_segments
959 && hls_stream->part_idx < cur_segment->partial_segments->len) {
960 GstM3U8PartialSegment *part =
961 g_ptr_array_index (cur_segment->partial_segments,
962 hls_stream->part_idx);
963 stream->current_position = part->stream_time;
964 duration = part->duration;
965 }
966 } else {
967 stream->current_position = hls_stream->current_segment->stream_time;
968 }
969
970 return gst_adaptive_demux2_stream_advance_fragment (stream, duration);
971 }
972 return ret;
973 }
974
975 static GstFlowReturn
976 gst_hls_demux_stream_data_received (GstAdaptiveDemux2Stream * stream,
977 GstBuffer * buffer)
978 {
979 GstHLSDemuxStream *hls_stream = GST_HLS_DEMUX_STREAM_CAST (stream);
980 GstHLSDemux *hlsdemux = GST_HLS_DEMUX_CAST (stream->demux);
981 GstM3U8MediaSegment *file = hls_stream->current_segment;
982
983 if (hls_stream->current_segment == NULL)
984 return GST_ADAPTIVE_DEMUX_FLOW_LOST_SYNC;
985
986 if (hls_stream->current_offset == -1)
987 hls_stream->current_offset = 0;
988
989 /* Is it encrypted? */
990 if (hls_stream->current_key) {
991 GError *err = NULL;
992 gsize size;
993 GstBuffer *decrypted_buffer;
994 GstBuffer *tmp_buffer;
995
996 if (hls_stream->pending_encrypted_data == NULL)
997 hls_stream->pending_encrypted_data = gst_adapter_new ();
998
999 gst_adapter_push (hls_stream->pending_encrypted_data, buffer);
1000 size = gst_adapter_available (hls_stream->pending_encrypted_data);
1001
1002 /* must be a multiple of 16 */
1003 size &= (~0xF);
1004
1005 if (size == 0) {
1006 return GST_FLOW_OK;
1007 }
1008
1009 buffer = gst_adapter_take_buffer (hls_stream->pending_encrypted_data, size);
1010 decrypted_buffer =
1011 gst_hls_demux_decrypt_fragment (hlsdemux, hls_stream, buffer, &err);
1012 if (err) {
1013 GST_ELEMENT_ERROR (hlsdemux, STREAM, DECODE, ("Failed to decrypt buffer"),
1014 ("decryption failed %s", err->message));
1015 g_error_free (err);
1016 return GST_FLOW_ERROR;
1017 }
1018
1019 tmp_buffer = hls_stream->pending_decrypted_buffer;
1020 hls_stream->pending_decrypted_buffer = decrypted_buffer;
1021 buffer = tmp_buffer;
1022 if (!buffer)
1023 return GST_FLOW_OK;
1024 }
1025
1026 if (!hls_stream->pdt_tag_sent && file != NULL && file->datetime != NULL) {
1027 GstDateTime *pdt_time = gst_date_time_new_from_g_date_time (g_date_time_ref
1028 (file->datetime));
1029 gst_adaptive_demux2_stream_set_tags (stream,
1030 gst_tag_list_new (GST_TAG_DATE_TIME, pdt_time, NULL));
1031 gst_date_time_unref (pdt_time);
1032 hls_stream->pdt_tag_sent = TRUE;
1033 }
1034
1035
1036 return gst_hls_demux_stream_handle_buffer (stream, buffer, FALSE);
1037 }
1038
1039 static void
1040 gst_hls_demux_stream_finalize (GObject * object)
1041 {
1042 GstAdaptiveDemux2Stream *stream = (GstAdaptiveDemux2Stream *) object;
1043 GstHLSDemuxStream *hls_stream = GST_HLS_DEMUX_STREAM_CAST (object);
1044 GstHLSDemux *hlsdemux = (GstHLSDemux *) stream->demux;
1045
1046 if (hls_stream == hlsdemux->main_stream)
1047 hlsdemux->main_stream = NULL;
1048
1049 g_free (hls_stream->lang);
1050 g_free (hls_stream->name);
1051
1052 if (hls_stream->playlist) {
1053 gst_hls_media_playlist_unref (hls_stream->playlist);
1054 hls_stream->playlist = NULL;
1055 }
1056
1057 if (hls_stream->init_file) {
1058 gst_m3u8_init_file_unref (hls_stream->init_file);
1059 hls_stream->init_file = NULL;
1060 }
1061
1062 if (hls_stream->pending_encrypted_data)
1063 g_object_unref (hls_stream->pending_encrypted_data);
1064
1065 gst_buffer_replace (&hls_stream->pending_decrypted_buffer, NULL);
1066 gst_buffer_replace (&hls_stream->pending_typefind_buffer, NULL);
1067 gst_buffer_replace (&hls_stream->pending_segment_data, NULL);
1068
1069 if (hls_stream->playlistloader) {
1070 gst_hls_demux_playlist_loader_stop (hls_stream->playlistloader);
1071 gst_object_unparent (GST_OBJECT (hls_stream->playlistloader));
1072 gst_object_unref (hls_stream->playlistloader);
1073 }
1074
1075 if (hls_stream->preloader) {
1076 gst_hls_demux_preloader_free (hls_stream->preloader);
1077 hls_stream->preloader = NULL;
1078 }
1079
1080 if (hls_stream->moov)
1081 gst_isoff_moov_box_free (hls_stream->moov);
1082
1083 if (hls_stream->current_key) {
1084 g_free (hls_stream->current_key);
1085 hls_stream->current_key = NULL;
1086 }
1087 if (hls_stream->current_iv) {
1088 g_free (hls_stream->current_iv);
1089 hls_stream->current_iv = NULL;
1090 }
1091 if (hls_stream->current_rendition) {
1092 gst_hls_rendition_stream_unref (hls_stream->current_rendition);
1093 hls_stream->current_rendition = NULL;
1094 }
1095 if (hls_stream->pending_rendition) {
1096 gst_hls_rendition_stream_unref (hls_stream->pending_rendition);
1097 hls_stream->pending_rendition = NULL;
1098 }
1099
1100 if (hls_stream->current_segment) {
1101 gst_m3u8_media_segment_unref (hls_stream->current_segment);
1102 hls_stream->current_segment = NULL;
1103 }
1104 gst_hls_demux_stream_decrypt_end (hls_stream);
1105
1106 G_OBJECT_CLASS (stream_parent_class)->finalize (object);
1107 }
1108
1109 static gboolean
1110 gst_hls_demux_stream_has_next_fragment (GstAdaptiveDemux2Stream * stream)
1111 {
1112 GstHLSDemuxStream *hls_stream = (GstHLSDemuxStream *) stream;
1113
1114 GST_DEBUG_OBJECT (stream, "has next ?");
1115
1116 if (hls_stream->current_segment == NULL)
1117 return FALSE;
1118
1119 return gst_hls_media_playlist_has_next_fragment (hls_stream->playlist,
1120 hls_stream->current_segment, stream->demux->segment.rate > 0);
1121 }
1122
1123 static GstFlowReturn
1124 gst_hls_demux_stream_advance_fragment (GstAdaptiveDemux2Stream * stream)
1125 {
1126 GstHLSDemuxStream *hlsdemux_stream = GST_HLS_DEMUX_STREAM_CAST (stream);
1127 GstHLSDemux *hlsdemux = (GstHLSDemux *) stream->demux;
1128 GstM3U8MediaSegment *new_segment = NULL;
1129
1130 /* If we're playing partial segments, we need to continue
1131 * doing that. We can only swap back to a full segment on a
1132 * segment boundary */
1133 if (hlsdemux_stream->in_partial_segments) {
1134 /* Check if there's another partial segment in this fragment */
1135 GstM3U8MediaSegment *cur_segment = hlsdemux_stream->current_segment;
1136 guint avail_segments =
1137 cur_segment->partial_segments !=
1138 NULL ? cur_segment->partial_segments->len : 0;
1139
1140 if (hlsdemux_stream->part_idx + 1 < avail_segments) {
1141 /* Advance to the next partial segment */
1142 hlsdemux_stream->part_idx += 1;
1143
1144 GstM3U8PartialSegment *part =
1145 g_ptr_array_index (cur_segment->partial_segments,
1146 hlsdemux_stream->part_idx);
1147
1148 GST_DEBUG_OBJECT (stream,
1149 "Advanced to partial segment sn:%" G_GINT64_FORMAT
1150 " part %d stream_time:%" GST_STIME_FORMAT " uri:%s",
1151 hlsdemux_stream->current_segment->sequence, hlsdemux_stream->part_idx,
1152 GST_STIME_ARGS (part->stream_time), GST_STR_NULL (part->uri));
1153
1154 return GST_FLOW_OK;
1155 } else if (cur_segment->partial_only) {
1156 /* There's no partial segment available, because we're at the live edge */
1157 GST_DEBUG_OBJECT (stream,
1158 "Hit live edge playing partial segments. Will wait for playlist update.");
1159 hlsdemux_stream->part_idx += 1;
1160 return GST_FLOW_OK;
1161 } else {
1162 /* At the end of the partial segments for this full segment. Advance to the next full segment */
1163 hlsdemux_stream->in_partial_segments = FALSE;
1164 GST_DEBUG_OBJECT (stream,
1165 "No more partial segments in current segment. Advancing");
1166 }
1167 }
1168
1169 GST_DEBUG_OBJECT (stream,
1170 "Current segment sn:%" G_GINT64_FORMAT " stream_time:%" GST_STIME_FORMAT
1171 " uri:%s", hlsdemux_stream->current_segment->sequence,
1172 GST_STIME_ARGS (hlsdemux_stream->current_segment->stream_time),
1173 GST_STR_NULL (hlsdemux_stream->current_segment->uri));
1174
1175 new_segment =
1176 gst_hls_media_playlist_advance_fragment (hlsdemux_stream->playlist,
1177 hlsdemux_stream->current_segment, stream->demux->segment.rate > 0);
1178
1179 if (new_segment) {
1180 hlsdemux_stream->reset_pts = FALSE;
1181 if (new_segment->discont_sequence !=
1182 hlsdemux_stream->current_segment->discont_sequence)
1183 gst_hls_demux_add_time_mapping (hlsdemux, new_segment->discont_sequence,
1184 new_segment->stream_time, new_segment->datetime);
1185 gst_m3u8_media_segment_unref (hlsdemux_stream->current_segment);
1186 hlsdemux_stream->current_segment = new_segment;
1187
1188 /* In LL-HLS, handle advancing into the partial-only segment */
1189 if (GST_HLS_MEDIA_PLAYLIST_IS_LIVE (hlsdemux_stream->playlist)
1190 && new_segment->partial_only) {
1191 hlsdemux_stream->in_partial_segments = TRUE;
1192 hlsdemux_stream->part_idx = 0;
1193
1194 GstM3U8PartialSegment *new_part =
1195 g_ptr_array_index (new_segment->partial_segments,
1196 hlsdemux_stream->part_idx);
1197
1198 GST_DEBUG_OBJECT (stream,
1199 "Advanced to partial segment sn:%" G_GINT64_FORMAT
1200 " part %u stream_time:%" GST_STIME_FORMAT " uri:%s",
1201 new_segment->sequence, hlsdemux_stream->part_idx,
1202 GST_STIME_ARGS (new_part->stream_time), GST_STR_NULL (new_part->uri));
1203 return GST_FLOW_OK;
1204 }
1205
1206 GST_DEBUG_OBJECT (stream,
1207 "Advanced to segment sn:%" G_GINT64_FORMAT " stream_time:%"
1208 GST_STIME_FORMAT " uri:%s", hlsdemux_stream->current_segment->sequence,
1209 GST_STIME_ARGS (hlsdemux_stream->current_segment->stream_time),
1210 GST_STR_NULL (hlsdemux_stream->current_segment->uri));
1211 return GST_FLOW_OK;
1212 }
1213
1214 GST_LOG_OBJECT (stream, "Could not advance to next fragment");
1215 if (GST_HLS_MEDIA_PLAYLIST_IS_LIVE (hlsdemux_stream->playlist)) {
1216 gst_m3u8_media_segment_unref (hlsdemux_stream->current_segment);
1217 hlsdemux_stream->current_segment = NULL;
1218 hlsdemux_stream->in_partial_segments = FALSE;
1219 return GST_FLOW_OK;
1220 }
1221
1222 return GST_FLOW_EOS;
1223 }
1224
1225 static void
1226 gst_hls_demux_stream_update_preloads (GstHLSDemuxStream * hlsdemux_stream)
1227 {
1228 GstHLSMediaPlaylist *playlist = hlsdemux_stream->playlist;
1229 gboolean preloads_allowed = GST_HLS_MEDIA_PLAYLIST_IS_LIVE (playlist);
1230
1231 if (playlist->preload_hints == NULL || !preloads_allowed) {
1232 if (hlsdemux_stream->preloader != NULL) {
1233 /* Cancel any preloads, the new playlist doesn't have them */
1234 gst_hls_demux_preloader_cancel (hlsdemux_stream->preloader,
1235 M3U8_PRELOAD_HINT_ALL);
1236 }
1237 /* Nothing to preload */
1238 return;
1239 }
1240
1241 if (hlsdemux_stream->preloader == NULL) {
1242 GstAdaptiveDemux *demux =
1243 GST_ADAPTIVE_DEMUX2_STREAM (hlsdemux_stream)->demux;
1244 hlsdemux_stream->preloader =
1245 gst_hls_demux_preloader_new (demux->download_helper);
1246 if (hlsdemux_stream->preloader == NULL) {
1247 GST_WARNING_OBJECT (hlsdemux_stream, "Failed to create preload handler");
1248 return;
1249 }
1250 }
1251
1252 /* The HLS spec says any extra preload hint of each type should be ignored */
1253 GstM3U8PreloadHintType seen_types = 0;
1254 guint idx;
1255 for (idx = 0; idx < playlist->preload_hints->len; idx++) {
1256 GstM3U8PreloadHint *hint = g_ptr_array_index (playlist->preload_hints, idx);
1257 switch (hint->hint_type) {
1258 case M3U8_PRELOAD_HINT_MAP:
1259 case M3U8_PRELOAD_HINT_PART:
1260 if (seen_types & hint->hint_type) {
1261 continue; /* Ignore preload hint type we've already seen */
1262 }
1263 seen_types |= hint->hint_type;
1264 break;
1265 default:
1266 GST_FIXME_OBJECT (hlsdemux_stream, "Ignoring unknown preload type %d",
1267 hint->hint_type);
1268 continue; /* Unknown hint type, ignore it */
1269 }
1270 gst_hls_demux_preloader_load (hlsdemux_stream->preloader, hint,
1271 playlist->uri);
1272 }
1273 }
1274
1275 static GstFlowReturn
1276 gst_hls_demux_stream_submit_request (GstAdaptiveDemux2Stream * stream,
1277 DownloadRequest * download_req)
1278 {
1279 GstHLSDemuxStream *hlsdemux_stream = GST_HLS_DEMUX_STREAM_CAST (stream);
1280
1281 /* See if the request can be satisfied from a preload */
1282 if (hlsdemux_stream->preloader != NULL) {
1283 if (gst_hls_demux_preloader_provide_request (hlsdemux_stream->preloader,
1284 download_req))
1285 return GST_FLOW_OK;
1286
1287 /* We're about to request something, but it wasn't the active preload,
1288 * so make sure that's been stopped / cancelled so we're not downloading
1289 * two things in parallel. This usually means the playlist refresh
1290 * took too long and the preload became obsolete */
1291 if (stream->downloading_header) {
1292 gst_hls_demux_preloader_cancel (hlsdemux_stream->preloader,
1293 M3U8_PRELOAD_HINT_MAP);
1294 } else {
1295 gst_hls_demux_preloader_cancel (hlsdemux_stream->preloader,
1296 M3U8_PRELOAD_HINT_PART);
1297 }
1298 }
1299
1300 return
1301 GST_ADAPTIVE_DEMUX2_STREAM_CLASS (stream_parent_class)->submit_request
1302 (stream, download_req);
1303 }
1304
1305 static void
1306 gst_hls_demux_stream_handle_playlist_update (GstHLSDemuxStream * stream,
1307 const gchar * new_playlist_uri, GstHLSMediaPlaylist * new_playlist)
1308 {
1309 GstHLSDemux *demux = GST_HLS_DEMUX_STREAM_GET_DEMUX (stream);
1310 gboolean found_segment_discont = FALSE;
1311
1312 /* Synchronize playlist with previous one. If we can't update the playlist
1313 * timing and inform the base class that we lost sync */
1314 if (stream->playlist) {
1315 if (!gst_hls_media_playlist_sync_to_playlist (new_playlist,
1316 stream->playlist, &found_segment_discont)) {
1317 /* Failure to synchronize with the previous media playlist is only fatal for
1318 * variant streams. */
1319 if (stream->is_variant) {
1320 GST_DEBUG_OBJECT (stream,
1321 "Could not synchronize new variant playlist with previous one !");
1322 goto lost_sync;
1323 }
1324
1325 /* For rendition streams, we can attempt synchronization against the
1326 * variant playlist which is constantly updated */
1327 if (demux->main_stream->playlist
1328 && !gst_hls_media_playlist_sync_to_playlist (new_playlist,
1329 demux->main_stream->playlist, &found_segment_discont)) {
1330 GST_DEBUG_OBJECT (stream,
1331 "Could not do fallback synchronization of rendition stream to variant stream");
1332 goto lost_sync;
1333 }
1334 }
1335 } else {
1336 found_segment_discont = TRUE;
1337 if (!stream->is_variant && demux->main_stream->playlist) {
1338 /* For initial rendition media playlist, attempt to synchronize the playlist
1339 * against the variant stream. This is non-fatal if it fails. */
1340 GST_DEBUG_OBJECT (stream,
1341 "Attempting to synchronize initial rendition stream with variant stream");
1342 gst_hls_media_playlist_sync_to_playlist (new_playlist,
1343 demux->main_stream->playlist, NULL);
1344 }
1345 }
1346
1347 GST_DEBUG_OBJECT (stream, "Synchronized playlist. Update is discont : %d",
1348 found_segment_discont);
1349 if (found_segment_discont) {
1350 stream->pending_discont = TRUE;
1351 }
1352
1353 if (stream->current_segment) {
1354 GstM3U8MediaSegment *new_segment;
1355 GST_DEBUG_OBJECT (stream,
1356 "Current segment sn:%" G_GINT64_FORMAT " stream_time:%" GST_STIME_FORMAT
1357 " uri:%s", stream->current_segment->sequence,
1358 GST_STIME_ARGS (stream->current_segment->stream_time),
1359 GST_STR_NULL (stream->current_segment->uri));
1360
1361 /* Use best-effort techniques to find the corresponding current media segment
1362 * in the new playlist. This might be off in some cases, but it doesn't matter
1363 * since we will be checking the embedded timestamp later */
1364 new_segment =
1365 gst_hls_media_playlist_sync_to_segment (new_playlist,
1366 stream->current_segment);
1367
1368 /* Handle LL-HLS partial segment sync by checking our partial segment
1369 * still makes sense */
1370 if (stream->in_partial_segments && new_segment) {
1371 /* We must be either playing the trailing open-ended partial segment,
1372 * or if we're playing partials from a complete segment, check that we
1373 * still have a) partial segments attached (didn't get too old and
1374 * the server removed them from the playlist) and b) we didn't advance
1375 * beyond the end of that partial segment (when we advance past the live
1376 * edge and increment part_idx, then the segment completes without
1377 * adding any more partial segments) */
1378 if (!new_segment->partial_only) {
1379 if (new_segment->partial_segments == NULL) {
1380 GST_DEBUG_OBJECT (stream,
1381 "Partial segments we were playing became unavailable. Will try and resync");
1382 stream->in_partial_segments = FALSE;
1383 gst_m3u8_media_segment_unref (new_segment);
1384 new_segment = NULL;
1385 } else if (stream->part_idx >= new_segment->partial_segments->len) {
1386 GST_DEBUG_OBJECT (stream,
1387 "After playlist reload, there are no more partial segments to play in the current segment. Resyncing");
1388 stream->in_partial_segments = FALSE;
1389 gst_m3u8_media_segment_unref (new_segment);
1390 new_segment = NULL;
1391 }
1392 }
1393 }
1394
1395 if (new_segment) {
1396 if (new_segment->discont_sequence !=
1397 stream->current_segment->discont_sequence)
1398 gst_hls_demux_add_time_mapping (demux, new_segment->discont_sequence,
1399 new_segment->stream_time, new_segment->datetime);
1400 /* This can happen in case of misaligned variants/renditions. Only warn about it */
1401 if (new_segment->stream_time != stream->current_segment->stream_time)
1402 GST_WARNING_OBJECT (stream,
1403 "Returned segment stream time %" GST_STIME_FORMAT
1404 " differs from current stream time %" GST_STIME_FORMAT,
1405 GST_STIME_ARGS (new_segment->stream_time),
1406 GST_STIME_ARGS (stream->current_segment->stream_time));
1407 } else {
1408 /* Not finding a matching segment only happens in live (otherwise we would
1409 * have found a match by stream time) when we are at the live edge. This is normal*/
1410 GST_DEBUG_OBJECT (stream, "Could not find a matching segment");
1411 }
1412 gst_m3u8_media_segment_unref (stream->current_segment);
1413 stream->current_segment = new_segment;
1414 } else {
1415 GST_DEBUG_OBJECT (stream, "No current segment");
1416 }
1417
1418 if (stream->is_variant) {
1419 /* Updates on the variant playlist have some special requirements to
1420 * set up the time mapping and initial stream config */
1421 gst_hls_demux_handle_variant_playlist_update (demux, new_playlist_uri,
1422 new_playlist);
1423 } else if (stream->pending_rendition) {
1424 /* Switching rendition configures a new playlist on the loader,
1425 * and we should never get a callback for a stale download URI */
1426 g_assert (!g_strcmp0 (stream->pending_rendition->uri, new_playlist_uri));
1427
1428 gst_hls_rendition_stream_unref (stream->current_rendition);
1429 /* Stealing ref */
1430 stream->current_rendition = stream->pending_rendition;
1431 stream->pending_rendition = NULL;
1432 }
1433
1434 if (stream->playlist)
1435 gst_hls_media_playlist_unref (stream->playlist);
1436 stream->playlist = gst_hls_media_playlist_ref (new_playlist);
1437 stream->playlist_fetched = TRUE;
1438
1439 if (!GST_HLS_MEDIA_PLAYLIST_IS_LIVE (stream->playlist)) {
1440 /* Make sure to cancel any preloads if a playlist isn't live after reload */
1441 gst_hls_demux_stream_update_preloads (stream);
1442 }
1443
1444 if (stream->current_segment) {
1445 GST_DEBUG_OBJECT (stream,
1446 "After update, current segment now sn:%" G_GINT64_FORMAT
1447 " stream_time:%" GST_STIME_FORMAT " uri:%s",
1448 stream->current_segment->sequence,
1449 GST_STIME_ARGS (stream->current_segment->stream_time),
1450 GST_STR_NULL (stream->current_segment->uri));
1451 } else {
1452 GST_DEBUG_OBJECT (stream, "No current segment selected");
1453 }
1454
1455 GST_DEBUG_OBJECT (stream, "done");
1456 return;
1457
1458 /* ERRORS */
1459 lost_sync:
1460 {
1461 /* Set new playlist, lost sync handler will know what to do with it */
1462 if (stream->playlist)
1463 gst_hls_media_playlist_unref (stream->playlist);
1464 stream->playlist = new_playlist;
1465 stream->playlist = gst_hls_media_playlist_ref (new_playlist);
1466 stream->playlist_fetched = TRUE;
1467 stream->pending_discont = TRUE;
1468
1469 if (!gst_hls_demux_reset_for_lost_sync (demux)) {
1470 GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
1471 ("Failed to resynchronise streams after a discontinuity"), (NULL));
1472 }
1473 }
1474 }
1475
1476 static void
1477 on_playlist_update_success (GstHLSDemuxPlaylistLoader * pl,
1478 const gchar * new_playlist_uri, GstHLSMediaPlaylist * new_playlist,
1479 gpointer userdata)
1480 {
1481 GstHLSDemuxStream *hls_stream = GST_HLS_DEMUX_STREAM_CAST (userdata);
1482
1483 gst_hls_demux_stream_handle_playlist_update (hls_stream,
1484 new_playlist_uri, new_playlist);
1485 gst_adaptive_demux2_stream_mark_prepared (GST_ADAPTIVE_DEMUX2_STREAM_CAST
1486 (hls_stream));
1487 }
1488
1489 static void
1490 on_playlist_update_error (GstHLSDemuxPlaylistLoader * pl,
1491 const gchar * playlist_uri, gpointer userdata)
1492 {
1493 GstHLSDemuxStream *hls_stream = GST_HLS_DEMUX_STREAM_CAST (userdata);
1494
1495 /* FIXME: How to handle rendition playlist update errors? There's
1496 * not much we can do about it except throw an error */
1497 if (hls_stream->is_variant) {
1498 GstHLSDemux *demux = GST_HLS_DEMUX_STREAM_GET_DEMUX (hls_stream);
1499 gst_hls_demux_handle_variant_playlist_update_error (demux, playlist_uri);
1500 } else {
1501 GstHLSDemux *demux = GST_HLS_DEMUX_STREAM_GET_DEMUX (hls_stream);
1502 GST_ELEMENT_ERROR (demux, STREAM, FAILED,
1503 (_("Internal data stream error.")),
1504 ("Could not update rendition playlist"));
1505 }
1506 }
1507
1508 static GstHLSDemuxPlaylistLoader *
1509 gst_hls_demux_stream_get_playlist_loader (GstHLSDemuxStream * hls_stream)
1510 {
1511 GstAdaptiveDemux *demux = GST_ADAPTIVE_DEMUX2_STREAM_CAST (hls_stream)->demux;
1512 if (hls_stream->playlistloader == NULL) {
1513 hls_stream->playlistloader =
1514 gst_hls_demux_playlist_loader_new (demux, demux->download_helper);
1515 gst_hls_demux_playlist_loader_set_callbacks (hls_stream->playlistloader,
1516 on_playlist_update_success, on_playlist_update_error, hls_stream);
1517 }
1518
1519 return hls_stream->playlistloader;
1520 }
1521
1522 void
1523 gst_hls_demux_stream_set_playlist_uri (GstHLSDemuxStream * hls_stream,
1524 gchar * uri)
1525 {
1526 GstAdaptiveDemux *demux = GST_ADAPTIVE_DEMUX2_STREAM_CAST (hls_stream)->demux;
1527 GstHLSDemuxPlaylistLoader *pl =
1528 gst_hls_demux_stream_get_playlist_loader (hls_stream);
1529
1530 const gchar *main_uri = gst_adaptive_demux_get_manifest_ref_uri (demux);
1531 gst_hls_demux_playlist_loader_set_playlist_uri (pl, main_uri, uri);
1532 }
1533
1534 void
1535 gst_hls_demux_stream_start_playlist_loading (GstHLSDemuxStream * hls_stream)
1536 {
1537 GstHLSDemuxPlaylistLoader *pl =
1538 gst_hls_demux_stream_get_playlist_loader (hls_stream);
1539 gst_hls_demux_playlist_loader_start (pl);
1540 }
1541
1542 GstFlowReturn
1543 gst_hls_demux_stream_check_current_playlist_uri (GstHLSDemuxStream * stream,
1544 gchar * uri)
1545 {
1546 GstHLSDemuxPlaylistLoader *pl =
1547 gst_hls_demux_stream_get_playlist_loader (stream);
1548
1549 if (!gst_hls_demux_playlist_loader_has_current_uri (pl, uri)) {
1550 GST_LOG_OBJECT (stream, "Target playlist not available yet");
1551 return GST_ADAPTIVE_DEMUX_FLOW_BUSY;
1552 }
1553
1554 return GST_FLOW_OK;
1555
1556 #if 0
1557 /* Check if a redirect happened */
1558 if (g_strcmp0 (*uri, new_playlist->uri)) {
1559 GST_DEBUG_OBJECT (stream, "Playlist URI update : '%s' => '%s'", *uri,
1560 new_playlist->uri);
1561 g_free (*uri);
1562 *uri = g_strdup (new_playlist->uri);
1563 }
1564 #endif
1565 }
1566
1567 static GstFlowReturn
1568 gst_hls_demux_stream_update_fragment_info (GstAdaptiveDemux2Stream * stream)
1569 {
1570 GstFlowReturn ret = GST_FLOW_OK;
1571 GstHLSDemuxStream *hlsdemux_stream = GST_HLS_DEMUX_STREAM_CAST (stream);
1572 GstAdaptiveDemux *demux = stream->demux;
1573 GstHLSDemux *hlsdemux = GST_HLS_DEMUX_CAST (demux);
1574 GstM3U8MediaSegment *file;
1575 GstM3U8PartialSegment *part = NULL;
1576 gboolean discont;
1577
1578 /* Return BUSY if no playlist is loaded yet. Even if
1579 * we switched and another playlist is loading,
1580 * we'll keep trying to load one */
1581 if (!hlsdemux_stream->playlist_fetched) {
1582 gst_hls_demux_stream_start_playlist_loading (hlsdemux_stream);
1583 return GST_ADAPTIVE_DEMUX_FLOW_BUSY;
1584 }
1585 g_assert (hlsdemux_stream->playlist != NULL);
1586 if ((ret =
1587 gst_hls_demux_stream_check_current_playlist_uri (hlsdemux_stream,
1588 NULL)) != GST_FLOW_OK) {
1589 /* The URI of the playlist we have is not the target URI due
1590 * to a bitrate switch - wait for it to load */
1591 GST_DEBUG_OBJECT (hlsdemux_stream,
1592 "Playlist is stale. Waiting for new playlist");
1593 gst_hls_demux_stream_start_playlist_loading (hlsdemux_stream);
1594 return ret;
1595 }
1596 #ifndef GST_DISABLE_GST_DEBUG
1597 GstClockTimeDiff live_edge_dist =
1598 GST_CLOCK_TIME_IS_VALID (stream->current_position) ?
1599 gst_hls_media_playlist_get_end_stream_time (hlsdemux_stream->playlist) -
1600 stream->current_position : GST_CLOCK_TIME_NONE;
1601 GstClockTime playlist_age =
1602 gst_adaptive_demux2_get_monotonic_time (GST_ADAPTIVE_DEMUX (demux)) -
1603 hlsdemux_stream->playlist->playlist_ts;
1604 GST_DEBUG_OBJECT (stream,
1605 "Updating fragment information, current_position:%" GST_TIME_FORMAT
1606 " which is %" GST_STIME_FORMAT " from live edge. Playlist age %"
1607 GST_TIME_FORMAT, GST_TIME_ARGS (stream->current_position),
1608 GST_STIME_ARGS (live_edge_dist), GST_TIME_ARGS (playlist_age));
1609 #endif
1610
1611 /* Find the current segment if we don't already have it */
1612 if (hlsdemux_stream->current_segment == NULL) {
1613 GST_LOG_OBJECT (stream, "No current segment");
1614 if (stream->current_position == GST_CLOCK_TIME_NONE) {
1615 GstM3U8SeekResult seek_result;
1616
1617 GST_DEBUG_OBJECT (stream, "Setting up initial segment");
1618
1619 if (gst_hls_media_playlist_get_starting_segment
1620 (hlsdemux_stream->playlist, &seek_result)) {
1621 hlsdemux_stream->current_segment = seek_result.segment;
1622 hlsdemux_stream->in_partial_segments =
1623 seek_result.found_partial_segment;
1624 hlsdemux_stream->part_idx = seek_result.part_idx;
1625 }
1626 } else {
1627 if (gst_hls_media_playlist_has_lost_sync (hlsdemux_stream->playlist,
1628 stream->current_position)) {
1629 GST_WARNING_OBJECT (stream, "Lost SYNC !");
1630 return GST_ADAPTIVE_DEMUX_FLOW_LOST_SYNC;
1631 }
1632 GST_DEBUG_OBJECT (stream,
1633 "Looking up segment for position %" GST_TIME_FORMAT,
1634 GST_TIME_ARGS (stream->current_position));
1635
1636 GstM3U8SeekResult seek_result;
1637 if (!gst_hls_media_playlist_find_position (hlsdemux_stream->playlist,
1638 stream->current_position, hlsdemux_stream->in_partial_segments,
1639 &seek_result)) {
1640 GST_INFO_OBJECT (stream, "At the end of the current media playlist");
1641 gst_hls_demux_stream_update_preloads (hlsdemux_stream);
1642 return GST_FLOW_EOS;
1643 }
1644
1645 hlsdemux_stream->current_segment = seek_result.segment;
1646 hlsdemux_stream->in_partial_segments = seek_result.found_partial_segment;
1647 hlsdemux_stream->part_idx = seek_result.part_idx;
1648
1649 /* If on a full segment, update time mapping. If it already exists it will be ignored.
1650 * Don't add time mappings for partial segments, wait for a full segment boundary */
1651 if (!hlsdemux_stream->in_partial_segments
1652 || hlsdemux_stream->part_idx == 0) {
1653 gst_hls_demux_add_time_mapping (hlsdemux,
1654 hlsdemux_stream->current_segment->discont_sequence,
1655 hlsdemux_stream->current_segment->stream_time,
1656 hlsdemux_stream->current_segment->datetime);
1657 }
1658 }
1659 }
1660
1661 file = hlsdemux_stream->current_segment;
1662
1663 if (hlsdemux_stream->in_partial_segments) {
1664 if (file->partial_segments == NULL) {
1665 /* I think this can only happen if we reloaded the playlist
1666 * and the segment we were in the middle of playing from
1667 * removed its partial segments because we were playing
1668 * too slowly */
1669 GST_DEBUG_OBJECT (stream,
1670 "Partial segment idx %d is not available in current playlist",
1671 hlsdemux_stream->part_idx);
1672 return GST_ADAPTIVE_DEMUX_FLOW_LOST_SYNC;
1673 }
1674
1675 if (hlsdemux_stream->part_idx >= file->partial_segments->len) {
1676 /* Being beyond the available partial segments in the partial_only
1677 * segment at the end of the playlist in LL-HLS means we've
1678 * hit the live edge and need to wait for a playlist update */
1679 if (file->partial_only) {
1680 GST_INFO_OBJECT (stream, "At the end of the current media playlist");
1681 gst_hls_demux_stream_update_preloads (hlsdemux_stream);
1682 return GST_FLOW_EOS;
1683 }
1684
1685 /* Otherwise, we reloaded the playlist and found that the partial_only segment we
1686 * were playing from became a real segment and we overstepped the end of
1687 * the parts. Reloading the playlist should have synced that up properly,
1688 * so we should never get here. */
1689 g_assert_not_reached ();
1690 }
1691
1692 part =
1693 g_ptr_array_index (file->partial_segments, hlsdemux_stream->part_idx);
1694
1695 GST_DEBUG_OBJECT (stream,
1696 "Current partial segment %d stream_time %" GST_STIME_FORMAT,
1697 hlsdemux_stream->part_idx, GST_STIME_ARGS (part->stream_time));
1698 discont = stream->discont;
1699 /* Use the segment discont flag only on the first partial segment */
1700 if ((hlsdemux_stream->pending_discont || file->discont)
1701 && hlsdemux_stream->part_idx == 0)
1702 discont = TRUE;
1703 } else {
1704 GST_DEBUG_OBJECT (stream, "Current segment stream_time %" GST_STIME_FORMAT,
1705 GST_STIME_ARGS (file->stream_time));
1706 discont = file->discont || stream->discont
1707 || hlsdemux_stream->pending_discont;
1708 }
1709
1710 gboolean need_header = GST_ADAPTIVE_DEMUX2_STREAM_NEED_HEADER (stream);
1711
1712 /* Check if the MAP header file changed and update it */
1713 if (file->init_file != NULL
1714 && !gst_m3u8_init_file_equal (hlsdemux_stream->init_file,
1715 file->init_file)) {
1716 GST_DEBUG_OBJECT (stream, "MAP header info changed. Updating");
1717 if (hlsdemux_stream->init_file != NULL)
1718 gst_m3u8_init_file_unref (hlsdemux_stream->init_file);
1719 hlsdemux_stream->init_file = gst_m3u8_init_file_ref (file->init_file);
1720 need_header = TRUE;
1721 }
1722
1723 if (file->init_file && need_header) {
1724 GstM3U8InitFile *header_file = file->init_file;
1725 g_free (stream->fragment.header_uri);
1726 stream->fragment.header_uri = g_strdup (header_file->uri);
1727 stream->fragment.header_range_start = header_file->offset;
1728 if (header_file->size != -1) {
1729 stream->fragment.header_range_end =
1730 header_file->offset + header_file->size - 1;
1731 } else {
1732 stream->fragment.header_range_end = -1;
1733 }
1734
1735 stream->need_header = TRUE;
1736
1737 GST_DEBUG_OBJECT (stream, "Need header uri: %s %" G_GUINT64_FORMAT " %"
1738 G_GINT64_FORMAT, stream->fragment.header_uri,
1739 stream->fragment.header_range_start, stream->fragment.header_range_end);
1740 }
1741
1742 /* set up our source for download */
1743 stream->fragment.stream_time = GST_CLOCK_STIME_NONE;
1744 g_free (stream->fragment.uri);
1745 stream->fragment.range_start = 0;
1746 stream->fragment.range_end = -1;
1747
1748 /* Encryption params always come from the parent segment */
1749 g_free (hlsdemux_stream->current_key);
1750 hlsdemux_stream->current_key = g_strdup (file->key);
1751 g_free (hlsdemux_stream->current_iv);
1752 hlsdemux_stream->current_iv = g_memdup2 (file->iv, sizeof (file->iv));
1753
1754 /* Other info could come from the part when playing partial segments */
1755
1756 if (part == NULL) {
1757 if (hlsdemux_stream->reset_pts || discont || demux->segment.rate < 0.0) {
1758 stream->fragment.stream_time = file->stream_time;
1759 }
1760 stream->fragment.uri = g_strdup (file->uri);
1761 stream->fragment.range_start = file->offset;
1762 if (file->size != -1)
1763 stream->fragment.range_end = file->offset + file->size - 1;
1764 stream->fragment.duration = file->duration;
1765 } else {
1766 if (hlsdemux_stream->reset_pts || discont || demux->segment.rate < 0.0) {
1767 stream->fragment.stream_time = part->stream_time;
1768 }
1769 stream->fragment.uri = g_strdup (part->uri);
1770 stream->fragment.range_start = part->offset;
1771 if (part->size != -1)
1772 stream->fragment.range_end = part->offset + part->size - 1;
1773 stream->fragment.duration = part->duration;
1774 }
1775
1776 GST_DEBUG_OBJECT (stream, "Stream URI now %s", stream->fragment.uri);
1777
1778 stream->recommended_buffering_threshold =
1779 gst_hls_media_playlist_recommended_buffering_threshold
1780 (hlsdemux_stream->playlist);
1781
1782 if (discont)
1783 stream->discont = TRUE;
1784 hlsdemux_stream->pending_discont = FALSE;
1785
1786 return ret;
1787 }
1788
1789 static gboolean
1790 gst_hls_demux_stream_can_start (GstAdaptiveDemux2Stream * stream)
1791 {
1792 GstHLSDemux *hlsdemux = (GstHLSDemux *) stream->demux;
1793 GstHLSDemuxStream *hls_stream = (GstHLSDemuxStream *) stream;
1794 GList *tmp;
1795
1796 GST_DEBUG_OBJECT (stream, "is_variant:%d mappings:%p", hls_stream->is_variant,
1797 hlsdemux->mappings);
1798
1799 /* Variant streams can always start straight away */
1800 if (hls_stream->is_variant)
1801 return TRUE;
1802
1803 /* Renditions of the exact same type as the variant are pure alternatives,
1804 * they must be started. This can happen for example with audio-only manifests
1805 * where the initial stream selected is a rendition and not a variant */
1806 if (hls_stream->rendition_type == hlsdemux->main_stream->rendition_type)
1807 return TRUE;
1808
1809 /* Rendition streams only require delaying if we don't have time mappings yet */
1810 if (!hlsdemux->mappings)
1811 return FALSE;
1812
1813 /* We can start if we have at least one internal time observation */
1814 for (tmp = hlsdemux->mappings; tmp; tmp = tmp->next) {
1815 GstHLSTimeMap *map = tmp->data;
1816 if (map->internal_time != GST_CLOCK_TIME_NONE)
1817 return TRUE;
1818 }
1819
1820 /* Otherwise we have to wait */
1821 return FALSE;
1822 }
1823
1824 static void
1825 gst_hls_demux_stream_start (GstAdaptiveDemux2Stream * stream)
1826 {
1827 if (!gst_hls_demux_stream_can_start (stream))
1828 return;
1829
1830 /* Start the playlist loader */
1831 GstHLSDemuxStream *hls_stream = GST_HLS_DEMUX_STREAM_CAST (stream);
1832
1833 gst_hls_demux_stream_start_playlist_loading (hls_stream);
1834
1835 /* Chain up, to start the downloading */
1836 GST_ADAPTIVE_DEMUX2_STREAM_CLASS (stream_parent_class)->start (stream);
1837 }
1838
1839 static void
1840 gst_hls_demux_stream_stop (GstAdaptiveDemux2Stream * stream)
1841 {
1842 GstHLSDemuxStream *hls_stream = GST_HLS_DEMUX_STREAM_CAST (stream);
1843
1844 if (hls_stream->playlistloader && !hls_stream->is_variant) {
1845 /* Don't stop the loader for the variant stream, keep it running
1846 * until the scheduler itself is stopped so we keep updating
1847 * the live playlist timeline */
1848 gst_hls_demux_playlist_loader_stop (hls_stream->playlistloader);
1849 }
1850
1851 /* Chain up, to stop the downloading */
1852 GST_ADAPTIVE_DEMUX2_STREAM_CLASS (stream_parent_class)->stop (stream);
1853 }
1854
1855 /* Called when the variant is changed, to set a new rendition
1856 * for this stream to download. Returns TRUE if the rendition
1857 * stream switched group-id */
1858 static gboolean
1859 gst_hls_demux_update_rendition_stream_uri (GstHLSDemux * hlsdemux,
1860 GstHLSDemuxStream * hls_stream, GError ** err)
1861 {
1862 gchar *current_group_id, *requested_group_id;
1863 GstHLSRenditionStream *replacement_media = NULL;
1864 GList *tmp;
1865
1866 /* There always should be a current variant set */
1867 g_assert (hlsdemux->current_variant);
1868 /* There always is a GstHLSRenditionStream set for rendition streams */
1869 g_assert (hls_stream->current_rendition);
1870
1871 requested_group_id =
1872 hlsdemux->current_variant->media_groups[hls_stream->
1873 current_rendition->mtype];
1874 current_group_id = hls_stream->current_rendition->group_id;
1875
1876 GST_DEBUG_OBJECT (hlsdemux,
1877 "Checking playlist change for variant stream %s lang: %s current group-id: %s / requested group-id: %s",
1878 gst_stream_type_get_name (hls_stream->rendition_type), hls_stream->lang,
1879 current_group_id, requested_group_id);
1880
1881
1882 if (!g_strcmp0 (requested_group_id, current_group_id)) {
1883 GST_DEBUG_OBJECT (hlsdemux, "No change needed");
1884 return FALSE;
1885 }
1886
1887 GST_DEBUG_OBJECT (hlsdemux,
1888 "group-id changed, looking for replacement playlist");
1889
1890 /* Need to switch/update */
1891 for (tmp = hlsdemux->master->renditions; tmp; tmp = tmp->next) {
1892 GstHLSRenditionStream *cand = tmp->data;
1893
1894 if (cand->mtype == hls_stream->current_rendition->mtype
1895 && !g_strcmp0 (cand->lang, hls_stream->lang)
1896 && !g_strcmp0 (cand->group_id, requested_group_id)) {
1897 replacement_media = cand;
1898 break;
1899 }
1900 }
1901 if (!replacement_media) {
1902 GST_ERROR_OBJECT (hlsdemux,
1903 "Could not find a replacement playlist. Staying with previous one");
1904 return FALSE;
1905 }
1906
1907 GST_DEBUG_OBJECT (hlsdemux, "Use replacement playlist %s",
1908 replacement_media->name);
1909 if (hls_stream->pending_rendition) {
1910 GST_ERROR_OBJECT (hlsdemux,
1911 "Already had a pending rendition switch to '%s'",
1912 hls_stream->pending_rendition->name);
1913 gst_hls_rendition_stream_unref (hls_stream->pending_rendition);
1914 }
1915 hls_stream->pending_rendition =
1916 gst_hls_rendition_stream_ref (replacement_media);
1917
1918 gst_hls_demux_stream_set_playlist_uri (hls_stream, replacement_media->uri);
1919
1920 return TRUE;
1921 }
1922
1923 static gboolean
1924 gst_hls_demux_stream_select_bitrate (GstAdaptiveDemux2Stream * stream,
1925 guint64 bitrate)
1926 {
1927 GstAdaptiveDemux *demux = GST_ADAPTIVE_DEMUX_CAST (stream->demux);
1928 GstHLSDemux *hlsdemux = GST_HLS_DEMUX_CAST (stream->demux);
1929 GstHLSDemuxStream *hls_stream = GST_HLS_DEMUX_STREAM_CAST (stream);
1930
1931 /* Fast-Path, no changes possible */
1932 if (hlsdemux->master == NULL || hlsdemux->master->is_simple)
1933 return FALSE;
1934
1935 /* Currently playing partial segments, disallow bitrate
1936 * switches and rendition playlist changes - except exactly
1937 * at the first partial segment in a full segment (implying
1938 * we are about to play a partial segment but didn't yet) */
1939 if (hls_stream->in_partial_segments && hls_stream->part_idx > 0)
1940 return FALSE;
1941
1942 if (hls_stream->is_variant) {
1943 gdouble play_rate = gst_adaptive_demux_play_rate (demux);
1944 gboolean changed = FALSE;
1945
1946 /* If not calculated yet, continue using start bitrate */
1947 if (bitrate == 0)
1948 bitrate = hlsdemux->start_bitrate;
1949
1950 /* Handle variant streams */
1951 GST_DEBUG_OBJECT (hlsdemux,
1952 "Checking playlist change for main variant stream");
1953 if (!gst_hls_demux_change_variant_playlist (hlsdemux,
1954 hlsdemux->current_variant->iframe,
1955 bitrate / MAX (1.0, ABS (play_rate)), &changed)) {
1956 GST_ERROR_OBJECT (hlsdemux, "Failed to choose a new variant to play");
1957 }
1958
1959 GST_DEBUG_OBJECT (hlsdemux, "Returning changed: %d", changed);
1960 return changed;
1961 }
1962
1963 /* Handle rendition streams */
1964 return gst_hls_demux_update_rendition_stream_uri (hlsdemux, hls_stream, NULL);
1965 }
1966
1967 #if defined(HAVE_OPENSSL)
1968 static gboolean
1969 gst_hls_demux_stream_decrypt_start (GstHLSDemuxStream * stream,
1970 const guint8 * key_data, const guint8 * iv_data)
1971 {
1972 EVP_CIPHER_CTX *ctx;
1973 #if OPENSSL_VERSION_NUMBER < 0x10100000L
1974 EVP_CIPHER_CTX_init (&stream->aes_ctx);
1975 ctx = &stream->aes_ctx;
1976 #else
1977 stream->aes_ctx = EVP_CIPHER_CTX_new ();
1978 ctx = stream->aes_ctx;
1979 #endif
1980 if (!EVP_DecryptInit_ex (ctx, EVP_aes_128_cbc (), NULL, key_data, iv_data))
1981 return FALSE;
1982 EVP_CIPHER_CTX_set_padding (ctx, 0);
1983 return TRUE;
1984 }
1985
1986 static gboolean
1987 decrypt_fragment (GstHLSDemuxStream * stream, gsize length,
1988 const guint8 * encrypted_data, guint8 * decrypted_data)
1989 {
1990 int len, flen = 0;
1991 EVP_CIPHER_CTX *ctx;
1992
1993 #if OPENSSL_VERSION_NUMBER < 0x10100000L
1994 ctx = &stream->aes_ctx;
1995 #else
1996 ctx = stream->aes_ctx;
1997 #endif
1998
1999 if (G_UNLIKELY (length > G_MAXINT || length % 16 != 0))
2000 return FALSE;
2001
2002 len = (int) length;
2003 if (!EVP_DecryptUpdate (ctx, decrypted_data, &len, encrypted_data, len))
2004 return FALSE;
2005 EVP_DecryptFinal_ex (ctx, decrypted_data + len, &flen);
2006 g_return_val_if_fail (len + flen == length, FALSE);
2007 return TRUE;
2008 }
2009
2010 static void
2011 gst_hls_demux_stream_decrypt_end (GstHLSDemuxStream * stream)
2012 {
2013 #if OPENSSL_VERSION_NUMBER < 0x10100000L
2014 EVP_CIPHER_CTX_cleanup (&stream->aes_ctx);
2015 #else
2016 EVP_CIPHER_CTX_free (stream->aes_ctx);
2017 stream->aes_ctx = NULL;
2018 #endif
2019 }
2020
2021 #elif defined(HAVE_NETTLE)
2022 static gboolean
2023 gst_hls_demux_stream_decrypt_start (GstHLSDemuxStream * stream,
2024 const guint8 * key_data, const guint8 * iv_data)
2025 {
2026 aes128_set_decrypt_key (&stream->aes_ctx.ctx, key_data);
2027 CBC_SET_IV (&stream->aes_ctx, iv_data);
2028
2029 return TRUE;
2030 }
2031
2032 static gboolean
2033 decrypt_fragment (GstHLSDemuxStream * stream, gsize length,
2034 const guint8 * encrypted_data, guint8 * decrypted_data)
2035 {
2036 if (length % 16 != 0)
2037 return FALSE;
2038
2039 CBC_DECRYPT (&stream->aes_ctx, aes128_decrypt, length, decrypted_data,
2040 encrypted_data);
2041
2042 return TRUE;
2043 }
2044
2045 static void
2046 gst_hls_demux_stream_decrypt_end (GstHLSDemuxStream * stream)
2047 {
2048 /* NOP */
2049 }
2050
2051 #elif defined(HAVE_LIBGCRYPT)
2052 static gboolean
2053 gst_hls_demux_stream_decrypt_start (GstHLSDemuxStream * stream,
2054 const guint8 * key_data, const guint8 * iv_data)
2055 {
2056 gcry_error_t err = 0;
2057 gboolean ret = FALSE;
2058
2059 err =
2060 gcry_cipher_open (&stream->aes_ctx, GCRY_CIPHER_AES128,
2061 GCRY_CIPHER_MODE_CBC, 0);
2062 if (err)
2063 goto out;
2064 err = gcry_cipher_setkey (stream->aes_ctx, key_data, 16);
2065 if (err)
2066 goto out;
2067 err = gcry_cipher_setiv (stream->aes_ctx, iv_data, 16);
2068 if (!err)
2069 ret = TRUE;
2070
2071 out:
2072 if (!ret)
2073 if (stream->aes_ctx)
2074 gcry_cipher_close (stream->aes_ctx);
2075
2076 return ret;
2077 }
2078
2079 static gboolean
2080 decrypt_fragment (GstHLSDemuxStream * stream, gsize length,
2081 const guint8 * encrypted_data, guint8 * decrypted_data)
2082 {
2083 gcry_error_t err = 0;
2084
2085 err = gcry_cipher_decrypt (stream->aes_ctx, decrypted_data, length,
2086 encrypted_data, length);
2087
2088 return err == 0;
2089 }
2090
2091 static void
2092 gst_hls_demux_stream_decrypt_end (GstHLSDemuxStream * stream)
2093 {
2094 if (stream->aes_ctx) {
2095 gcry_cipher_close (stream->aes_ctx);
2096 stream->aes_ctx = NULL;
2097 }
2098 }
2099
2100 #else
2101 /* NO crypto available */
2102 static gboolean
2103 gst_hls_demux_stream_decrypt_start (GstHLSDemuxStream * stream,
2104 const guint8 * key_data, const guint8 * iv_data)
2105 {
2106 GST_ERROR ("No crypto available");
2107 return FALSE;
2108 }
2109
2110 static gboolean
2111 decrypt_fragment (GstHLSDemuxStream * stream, gsize length,
2112 const guint8 * encrypted_data, guint8 * decrypted_data)
2113 {
2114 GST_ERROR ("Cannot decrypt fragment, no crypto available");
2115 return FALSE;
2116 }
2117
2118 static void
2119 gst_hls_demux_stream_decrypt_end (GstHLSDemuxStream * stream)
2120 {
2121 return;
2122 }
2123 #endif
2124
2125 static GstBuffer *
2126 gst_hls_demux_decrypt_fragment (GstHLSDemux * demux, GstHLSDemuxStream * stream,
2127 GstBuffer * encrypted_buffer, GError ** err)
2128 {
2129 GstBuffer *decrypted_buffer = NULL;
2130 GstMapInfo encrypted_info, decrypted_info;
2131
2132 decrypted_buffer =
2133 gst_buffer_new_allocate (NULL, gst_buffer_get_size (encrypted_buffer),
2134 NULL);
2135
2136 gst_buffer_map (encrypted_buffer, &encrypted_info, GST_MAP_READ);
2137 gst_buffer_map (decrypted_buffer, &decrypted_info, GST_MAP_WRITE);
2138
2139 if (!decrypt_fragment (stream, encrypted_info.size,
2140 encrypted_info.data, decrypted_info.data))
2141 goto decrypt_error;
2142
2143
2144 gst_buffer_unmap (decrypted_buffer, &decrypted_info);
2145 gst_buffer_unmap (encrypted_buffer, &encrypted_info);
2146
2147 gst_buffer_unref (encrypted_buffer);
2148
2149 return decrypted_buffer;
2150
2151 decrypt_error:
2152 GST_ERROR_OBJECT (demux, "Failed to decrypt fragment");
2153 g_set_error (err, GST_STREAM_ERROR, GST_STREAM_ERROR_DECRYPT,
2154 "Failed to decrypt fragment");
2155
2156 gst_buffer_unmap (decrypted_buffer, &decrypted_info);
2157 gst_buffer_unmap (encrypted_buffer, &encrypted_info);
2158
2159 gst_buffer_unref (encrypted_buffer);
2160 gst_buffer_unref (decrypted_buffer);
2161
2162 return NULL;
2163 }
2164
2165 static GstClockTime
2166 gst_hls_demux_stream_get_presentation_offset (GstAdaptiveDemux2Stream * stream)
2167 {
2168 GstHLSDemux *hlsdemux = (GstHLSDemux *) stream->demux;
2169 GstHLSDemuxStream *hls_stream = (GstHLSDemuxStream *) stream;
2170
2171 GST_DEBUG_OBJECT (stream, "presentation_offset %" GST_TIME_FORMAT,
2172 GST_TIME_ARGS (hls_stream->presentation_offset));
2173
2174 /* If this stream and the variant stream are ISOBMFF, returns the presentation
2175 * offset of the variant stream */
2176 if (hls_stream->parser_type == GST_HLS_PARSER_ISOBMFF
2177 && hlsdemux->main_stream->parser_type == GST_HLS_PARSER_ISOBMFF)
2178 return hlsdemux->main_stream->presentation_offset;
2179 return hls_stream->presentation_offset;
2180 }