[bbc.co.uk] Fix test_BBCCoUk
[youtube-dl] / youtube_dl / extractor / bbc.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..utils import (
8     ExtractorError,
9     float_or_none,
10     int_or_none,
11     parse_duration,
12     parse_iso8601,
13     remove_end,
14     unescapeHTML,
15 )
16 from ..compat import (
17     compat_etree_fromstring,
18     compat_HTTPError,
19 )
20
21
22 class BBCCoUkIE(InfoExtractor):
23     IE_NAME = 'bbc.co.uk'
24     IE_DESC = 'BBC iPlayer'
25     _ID_REGEX = r'[pb][\da-z]{7}'
26     _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:(?:programmes/(?!articles/)|iplayer(?:/[^/]+)?/(?:episode/|playlist/))|music/clips[/#])(?P<id>%s)' % _ID_REGEX
27
28     _MEDIASELECTOR_URLS = [
29         # Provides HQ HLS streams with even better quality that pc mediaset but fails
30         # with geolocation in some cases when it's even not geo restricted at all (e.g.
31         # http://www.bbc.co.uk/programmes/b06bp7lf). Also may fail with selectionunavailable.
32         'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
33         'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s',
34     ]
35
36     _MEDIASELECTION_NS = 'http://bbc.co.uk/2008/mp/mediaselection'
37     _EMP_PLAYLIST_NS = 'http://bbc.co.uk/2008/emp/playlist'
38
39     _NAMESPACES = (
40         _MEDIASELECTION_NS,
41         _EMP_PLAYLIST_NS,
42     )
43
44     _TESTS = [
45         {
46             'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
47             'info_dict': {
48                 'id': 'b039d07m',
49                 'ext': 'flv',
50                 'title': 'Leonard Cohen, Kaleidoscope - BBC Radio 4',
51                 'description': 'The Canadian poet and songwriter reflects on his musical career.',
52             },
53             'params': {
54                 # rtmp download
55                 'skip_download': True,
56             }
57         },
58         {
59             'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
60             'info_dict': {
61                 'id': 'b00yng1d',
62                 'ext': 'flv',
63                 'title': 'The Man in Black: Series 3: The Printed Name',
64                 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
65                 'duration': 1800,
66             },
67             'params': {
68                 # rtmp download
69                 'skip_download': True,
70             },
71             'skip': 'Episode is no longer available on BBC iPlayer Radio',
72         },
73         {
74             'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
75             'info_dict': {
76                 'id': 'b00yng1d',
77                 'ext': 'flv',
78                 'title': 'The Voice UK: Series 3: Blind Auditions 5',
79                 'description': "Emma Willis and Marvin Humes present the fifth set of blind auditions in the singing competition, as the coaches continue to build their teams based on voice alone.",
80                 'duration': 5100,
81             },
82             'params': {
83                 # rtmp download
84                 'skip_download': True,
85             },
86             'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
87         },
88         {
89             'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
90             'info_dict': {
91                 'id': 'b03k3pb7',
92                 'ext': 'flv',
93                 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
94                 'description': '2. Invasion',
95                 'duration': 3600,
96             },
97             'params': {
98                 # rtmp download
99                 'skip_download': True,
100             },
101             'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
102         }, {
103             'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
104             'info_dict': {
105                 'id': 'b04v209v',
106                 'ext': 'flv',
107                 'title': 'Pete Tong, The Essential New Tune Special',
108                 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
109                 'duration': 10800,
110             },
111             'params': {
112                 # rtmp download
113                 'skip_download': True,
114             }
115         }, {
116             'url': 'http://www.bbc.co.uk/music/clips/p02frcc3',
117             'note': 'Audio',
118             'info_dict': {
119                 'id': 'p02frcch',
120                 'ext': 'flv',
121                 'title': 'Pete Tong, Past, Present and Future Special, Madeon - After Hours mix',
122                 'description': 'French house superstar Madeon takes us out of the club and onto the after party.',
123                 'duration': 3507,
124             },
125             'params': {
126                 # rtmp download
127                 'skip_download': True,
128             }
129         }, {
130             'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
131             'note': 'Video',
132             'info_dict': {
133                 'id': 'p025c103',
134                 'ext': 'flv',
135                 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
136                 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
137                 'duration': 226,
138             },
139             'params': {
140                 # rtmp download
141                 'skip_download': True,
142             }
143         }, {
144             'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
145             'info_dict': {
146                 'id': 'p02n76xf',
147                 'ext': 'flv',
148                 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
149                 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
150                 'duration': 3540,
151             },
152             'params': {
153                 # rtmp download
154                 'skip_download': True,
155             },
156             'skip': 'geolocation',
157         }, {
158             'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
159             'info_dict': {
160                 'id': 'b05zmgw1',
161                 'ext': 'flv',
162                 'description': 'Kirsty Wark and Morgan Quaintance visit the Royal Academy as it prepares for its annual artistic extravaganza, meeting people who have come together to make the show unique.',
163                 'title': 'Royal Academy Summer Exhibition',
164                 'duration': 3540,
165             },
166             'params': {
167                 # rtmp download
168                 'skip_download': True,
169             },
170             'skip': 'geolocation',
171         }, {
172             # iptv-all mediaset fails with geolocation however there is no geo restriction
173             # for this programme at all
174             'url': 'http://www.bbc.co.uk/programmes/b06bp7lf',
175             'info_dict': {
176                 'id': 'b06bp7kf',
177                 'ext': 'flv',
178                 'title': "Annie Mac's Friday Night, B.Traits sits in for Annie",
179                 'description': 'B.Traits sits in for Annie Mac with a Mini-Mix from Disclosure.',
180                 'duration': 10800,
181             },
182             'params': {
183                 # rtmp download
184                 'skip_download': True,
185             },
186         }, {
187             'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
188             'only_matching': True,
189         }, {
190             'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
191             'only_matching': True,
192         }, {
193             'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
194             'only_matching': True,
195         }
196     ]
197
198     class MediaSelectionError(Exception):
199         def __init__(self, id):
200             self.id = id
201
202     def _extract_asx_playlist(self, connection, programme_id):
203         asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
204         return [ref.get('href') for ref in asx.findall('./Entry/ref')]
205
206     def _extract_connection(self, connection, programme_id):
207         formats = []
208         kind = connection.get('kind')
209         protocol = connection.get('protocol')
210         supplier = connection.get('supplier')
211         if protocol == 'http':
212             href = connection.get('href')
213             transfer_format = connection.get('transferFormat')
214             # ASX playlist
215             if supplier == 'asx':
216                 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
217                     formats.append({
218                         'url': ref,
219                         'format_id': 'ref%s_%s' % (i, supplier),
220                     })
221             # Skip DASH until supported
222             elif transfer_format == 'dash':
223                 pass
224             elif transfer_format == 'hls':
225                 m3u8_formats = self._extract_m3u8_formats(
226                     href, programme_id, ext='mp4', entry_protocol='m3u8_native',
227                     m3u8_id=supplier, fatal=False)
228                 if m3u8_formats:
229                     formats.extend(m3u8_formats)
230             # Direct link
231             else:
232                 formats.append({
233                     'url': href,
234                     'format_id': supplier or kind or protocol,
235                 })
236         elif protocol == 'rtmp':
237             application = connection.get('application', 'ondemand')
238             auth_string = connection.get('authString')
239             identifier = connection.get('identifier')
240             server = connection.get('server')
241             formats.append({
242                 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
243                 'play_path': identifier,
244                 'app': '%s?%s' % (application, auth_string),
245                 'page_url': 'http://www.bbc.co.uk',
246                 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
247                 'rtmp_live': False,
248                 'ext': 'flv',
249                 'format_id': supplier,
250             })
251         return formats
252
253     def _extract_items(self, playlist):
254         return playlist.findall('./{%s}item' % self._EMP_PLAYLIST_NS)
255
256     def _findall_ns(self, element, xpath):
257         elements = []
258         for ns in self._NAMESPACES:
259             elements.extend(element.findall(xpath % ns))
260         return elements
261
262     def _extract_medias(self, media_selection):
263         error = media_selection.find('./{%s}error' % self._MEDIASELECTION_NS)
264         if error is None:
265             media_selection.find('./{%s}error' % self._EMP_PLAYLIST_NS)
266         if error is not None:
267             raise BBCCoUkIE.MediaSelectionError(error.get('id'))
268         return self._findall_ns(media_selection, './{%s}media')
269
270     def _extract_connections(self, media):
271         return self._findall_ns(media, './{%s}connection')
272
273     def _extract_video(self, media, programme_id):
274         formats = []
275         vbr = int_or_none(media.get('bitrate'))
276         vcodec = media.get('encoding')
277         service = media.get('service')
278         width = int_or_none(media.get('width'))
279         height = int_or_none(media.get('height'))
280         file_size = int_or_none(media.get('media_file_size'))
281         for connection in self._extract_connections(media):
282             conn_formats = self._extract_connection(connection, programme_id)
283             for format in conn_formats:
284                 format.update({
285                     'width': width,
286                     'height': height,
287                     'vbr': vbr,
288                     'vcodec': vcodec,
289                     'filesize': file_size,
290                 })
291                 if service:
292                     format['format_id'] = '%s_%s' % (service, format['format_id'])
293             formats.extend(conn_formats)
294         return formats
295
296     def _extract_audio(self, media, programme_id):
297         formats = []
298         abr = int_or_none(media.get('bitrate'))
299         acodec = media.get('encoding')
300         service = media.get('service')
301         for connection in self._extract_connections(media):
302             conn_formats = self._extract_connection(connection, programme_id)
303             for format in conn_formats:
304                 format.update({
305                     'format_id': '%s_%s' % (service, format['format_id']),
306                     'abr': abr,
307                     'acodec': acodec,
308                 })
309             formats.extend(conn_formats)
310         return formats
311
312     def _get_subtitles(self, media, programme_id):
313         subtitles = {}
314         for connection in self._extract_connections(media):
315             captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
316             lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
317             subtitles[lang] = [
318                 {
319                     'url': connection.get('href'),
320                     'ext': 'ttml',
321                 },
322             ]
323         return subtitles
324
325     def _raise_extractor_error(self, media_selection_error):
326         raise ExtractorError(
327             '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
328             expected=True)
329
330     def _download_media_selector(self, programme_id):
331         last_exception = None
332         for mediaselector_url in self._MEDIASELECTOR_URLS:
333             try:
334                 return self._download_media_selector_url(
335                     mediaselector_url % programme_id, programme_id)
336             except BBCCoUkIE.MediaSelectionError as e:
337                 if e.id in ('notukerror', 'geolocation', 'selectionunavailable'):
338                     last_exception = e
339                     continue
340                 self._raise_extractor_error(e)
341         self._raise_extractor_error(last_exception)
342
343     def _download_media_selector_url(self, url, programme_id=None):
344         try:
345             media_selection = self._download_xml(
346                 url, programme_id, 'Downloading media selection XML')
347         except ExtractorError as ee:
348             if isinstance(ee.cause, compat_HTTPError) and ee.cause.code in (403, 404):
349                 media_selection = compat_etree_fromstring(ee.cause.read().decode('utf-8'))
350             else:
351                 raise
352         return self._process_media_selector(media_selection, programme_id)
353
354     def _process_media_selector(self, media_selection, programme_id):
355         formats = []
356         subtitles = None
357
358         for media in self._extract_medias(media_selection):
359             kind = media.get('kind')
360             if kind == 'audio':
361                 formats.extend(self._extract_audio(media, programme_id))
362             elif kind == 'video':
363                 formats.extend(self._extract_video(media, programme_id))
364             elif kind == 'captions':
365                 subtitles = self.extract_subtitles(media, programme_id)
366         return formats, subtitles
367
368     def _download_playlist(self, playlist_id):
369         try:
370             playlist = self._download_json(
371                 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
372                 playlist_id, 'Downloading playlist JSON')
373
374             version = playlist.get('defaultAvailableVersion')
375             if version:
376                 smp_config = version['smpConfig']
377                 title = smp_config['title']
378                 description = smp_config['summary']
379                 for item in smp_config['items']:
380                     kind = item['kind']
381                     if kind != 'programme' and kind != 'radioProgramme':
382                         continue
383                     programme_id = item.get('vpid')
384                     duration = int_or_none(item.get('duration'))
385                     formats, subtitles = self._download_media_selector(programme_id)
386                 return programme_id, title, description, duration, formats, subtitles
387         except ExtractorError as ee:
388             if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
389                 raise
390
391         # fallback to legacy playlist
392         return self._process_legacy_playlist(playlist_id)
393
394     def _process_legacy_playlist_url(self, url, display_id):
395         playlist = self._download_legacy_playlist_url(url, display_id)
396         return self._extract_from_legacy_playlist(playlist, display_id)
397
398     def _process_legacy_playlist(self, playlist_id):
399         return self._process_legacy_playlist_url(
400             'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
401
402     def _download_legacy_playlist_url(self, url, playlist_id=None):
403         return self._download_xml(
404             url, playlist_id, 'Downloading legacy playlist XML')
405
406     def _extract_from_legacy_playlist(self, playlist, playlist_id):
407         no_items = playlist.find('./{%s}noItems' % self._EMP_PLAYLIST_NS)
408         if no_items is not None:
409             reason = no_items.get('reason')
410             if reason == 'preAvailability':
411                 msg = 'Episode %s is not yet available' % playlist_id
412             elif reason == 'postAvailability':
413                 msg = 'Episode %s is no longer available' % playlist_id
414             elif reason == 'noMedia':
415                 msg = 'Episode %s is not currently available' % playlist_id
416             else:
417                 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
418             raise ExtractorError(msg, expected=True)
419
420         for item in self._extract_items(playlist):
421             kind = item.get('kind')
422             if kind != 'programme' and kind != 'radioProgramme':
423                 continue
424             title = playlist.find('./{%s}title' % self._EMP_PLAYLIST_NS).text
425             description_el = playlist.find('./{%s}summary' % self._EMP_PLAYLIST_NS)
426             description = description_el.text if description_el is not None else None
427
428             def get_programme_id(item):
429                 def get_from_attributes(item):
430                     for p in('identifier', 'group'):
431                         value = item.get(p)
432                         if value and re.match(r'^[pb][\da-z]{7}$', value):
433                             return value
434                 get_from_attributes(item)
435                 mediator = item.find('./{%s}mediator' % self._EMP_PLAYLIST_NS)
436                 if mediator is not None:
437                     return get_from_attributes(mediator)
438
439             programme_id = get_programme_id(item)
440             duration = int_or_none(item.get('duration'))
441
442             if programme_id:
443                 formats, subtitles = self._download_media_selector(programme_id)
444             else:
445                 formats, subtitles = self._process_media_selector(item, playlist_id)
446                 programme_id = playlist_id
447
448         return programme_id, title, description, duration, formats, subtitles
449
450     def _real_extract(self, url):
451         group_id = self._match_id(url)
452
453         webpage = self._download_webpage(url, group_id, 'Downloading video page')
454
455         programme_id = None
456         duration = None
457
458         tviplayer = self._search_regex(
459             r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
460             webpage, 'player', default=None)
461
462         if tviplayer:
463             player = self._parse_json(tviplayer, group_id).get('player', {})
464             duration = int_or_none(player.get('duration'))
465             programme_id = player.get('vpid')
466
467         if not programme_id:
468             programme_id = self._search_regex(
469                 r'"vpid"\s*:\s*"(%s)"' % self._ID_REGEX, webpage, 'vpid', fatal=False, default=None)
470
471         if programme_id:
472             formats, subtitles = self._download_media_selector(programme_id)
473             title = self._og_search_title(webpage)
474             description = self._search_regex(
475                 r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
476                 webpage, 'description', default=None)
477             if not description:
478                 description = self._html_search_meta('description', webpage)
479         else:
480             programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
481
482         self._sort_formats(formats)
483
484         return {
485             'id': programme_id,
486             'title': title,
487             'description': description,
488             'thumbnail': self._og_search_thumbnail(webpage, default=None),
489             'duration': duration,
490             'formats': formats,
491             'subtitles': subtitles,
492         }
493
494
495 class BBCIE(BBCCoUkIE):
496     IE_NAME = 'bbc'
497     IE_DESC = 'BBC'
498     _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
499
500     _MEDIASELECTOR_URLS = [
501         # Provides HQ HLS streams but fails with geolocation in some cases when it's
502         # even not geo restricted at all
503         'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
504         # Provides more formats, namely direct mp4 links, but fails on some videos with
505         # notukerror for non UK (?) users (e.g.
506         # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
507         'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
508         # Provides fewer formats, but works everywhere for everybody (hopefully)
509         'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
510     ]
511
512     _TESTS = [{
513         # article with multiple videos embedded with data-playable containing vpids
514         'url': 'http://www.bbc.com/news/world-europe-32668511',
515         'info_dict': {
516             'id': 'world-europe-32668511',
517             'title': 'Russia stages massive WW2 parade despite Western boycott',
518             'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
519         },
520         'playlist_count': 2,
521     }, {
522         # article with multiple videos embedded with data-playable (more videos)
523         'url': 'http://www.bbc.com/news/business-28299555',
524         'info_dict': {
525             'id': 'business-28299555',
526             'title': 'Farnborough Airshow: Video highlights',
527             'description': 'BBC reports and video highlights at the Farnborough Airshow.',
528         },
529         'playlist_count': 9,
530         'skip': 'Save time',
531     }, {
532         # article with multiple videos embedded with `new SMP()`
533         # broken
534         'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
535         'info_dict': {
536             'id': '3662a707-0af9-3149-963f-47bea720b460',
537             'title': 'BBC Blogs - Adam Curtis - BUGGER',
538         },
539         'playlist_count': 18,
540     }, {
541         # single video embedded with data-playable containing vpid
542         'url': 'http://www.bbc.com/news/world-europe-32041533',
543         'info_dict': {
544             'id': 'p02mprgb',
545             'ext': 'mp4',
546             'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
547             'description': 'md5:2868290467291b37feda7863f7a83f54',
548             'duration': 47,
549             'timestamp': 1427219242,
550             'upload_date': '20150324',
551         },
552         'params': {
553             # rtmp download
554             'skip_download': True,
555         }
556     }, {
557         # article with single video embedded with data-playable containing XML playlist
558         # with direct video links as progressiveDownloadUrl (for now these are extracted)
559         # and playlist with f4m and m3u8 as streamingUrl
560         'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
561         'info_dict': {
562             'id': '150615_telabyad_kentin_cogu',
563             'ext': 'mp4',
564             'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
565             'timestamp': 1434397334,
566             'upload_date': '20150615',
567         },
568         'params': {
569             'skip_download': True,
570         }
571     }, {
572         # single video embedded with data-playable containing XML playlists (regional section)
573         'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
574         'info_dict': {
575             'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
576             'ext': 'mp4',
577             'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
578             'timestamp': 1434713142,
579             'upload_date': '20150619',
580         },
581         'params': {
582             'skip_download': True,
583         }
584     }, {
585         # single video from video playlist embedded with vxp-playlist-data JSON
586         'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
587         'info_dict': {
588             'id': 'p02w6qjc',
589             'ext': 'mp4',
590             'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
591             'duration': 56,
592         },
593         'params': {
594             'skip_download': True,
595         }
596     }, {
597         # single video story with digitalData
598         'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
599         'info_dict': {
600             'id': 'p02q6gc4',
601             'ext': 'flv',
602             'title': 'Sri Lanka’s spicy secret',
603             'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
604             'timestamp': 1437674293,
605             'upload_date': '20150723',
606         },
607         'params': {
608             # rtmp download
609             'skip_download': True,
610         }
611     }, {
612         # single video story without digitalData
613         'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
614         'info_dict': {
615             'id': 'p018zqqg',
616             'ext': 'mp4',
617             'title': 'Hyundai Santa Fe Sport: Rock star',
618             'description': 'md5:b042a26142c4154a6e472933cf20793d',
619             'timestamp': 1415867444,
620             'upload_date': '20141113',
621         },
622         'params': {
623             # rtmp download
624             'skip_download': True,
625         }
626     }, {
627         # single video with playlist.sxml URL in playlist param
628         'url': 'http://www.bbc.com/sport/0/football/33653409',
629         'info_dict': {
630             'id': 'p02xycnp',
631             'ext': 'mp4',
632             'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
633             'description': 'BBC Sport\'s David Ornstein has the latest transfer gossip, including rumours of a Manchester United return for Cristiano Ronaldo.',
634             'duration': 140,
635         },
636         'params': {
637             # rtmp download
638             'skip_download': True,
639         }
640     }, {
641         # article with multiple videos embedded with playlist.sxml in playlist param
642         'url': 'http://www.bbc.com/sport/0/football/34475836',
643         'info_dict': {
644             'id': '34475836',
645             'title': 'What Liverpool can expect from Klopp',
646         },
647         'playlist_count': 3,
648     }, {
649         # single video with playlist URL from weather section
650         'url': 'http://www.bbc.com/weather/features/33601775',
651         'only_matching': True,
652     }, {
653         # custom redirection to www.bbc.com
654         'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
655         'only_matching': True,
656     }]
657
658     @classmethod
659     def suitable(cls, url):
660         return False if BBCCoUkIE.suitable(url) or BBCCoUkArticleIE.suitable(url) else super(BBCIE, cls).suitable(url)
661
662     def _extract_from_media_meta(self, media_meta, video_id):
663         # Direct links to media in media metadata (e.g.
664         # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
665         # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
666         source_files = media_meta.get('sourceFiles')
667         if source_files:
668             return [{
669                 'url': f['url'],
670                 'format_id': format_id,
671                 'ext': f.get('encoding'),
672                 'tbr': float_or_none(f.get('bitrate'), 1000),
673                 'filesize': int_or_none(f.get('filesize')),
674             } for format_id, f in source_files.items() if f.get('url')], []
675
676         programme_id = media_meta.get('externalId')
677         if programme_id:
678             return self._download_media_selector(programme_id)
679
680         # Process playlist.sxml as legacy playlist
681         href = media_meta.get('href')
682         if href:
683             playlist = self._download_legacy_playlist_url(href)
684             _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
685             return formats, subtitles
686
687         return [], []
688
689     def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
690         programme_id, title, description, duration, formats, subtitles = \
691             self._process_legacy_playlist_url(url, playlist_id)
692         self._sort_formats(formats)
693         return {
694             'id': programme_id,
695             'title': title,
696             'description': description,
697             'duration': duration,
698             'timestamp': timestamp,
699             'formats': formats,
700             'subtitles': subtitles,
701         }
702
703     def _real_extract(self, url):
704         playlist_id = self._match_id(url)
705
706         webpage = self._download_webpage(url, playlist_id)
707
708         timestamp = None
709         playlist_title = None
710         playlist_description = None
711
712         ld = self._parse_json(
713             self._search_regex(
714                 r'(?s)<script type="application/ld\+json">(.+?)</script>',
715                 webpage, 'ld json', default='{}'),
716             playlist_id, fatal=False)
717         if ld:
718             timestamp = parse_iso8601(ld.get('datePublished'))
719             playlist_title = ld.get('headline')
720             playlist_description = ld.get('articleBody')
721
722         if not timestamp:
723             timestamp = parse_iso8601(self._search_regex(
724                 [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
725                  r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
726                  r'"datePublished":\s*"([^"]+)'],
727                 webpage, 'date', default=None))
728
729         entries = []
730
731         # article with multiple videos embedded with playlist.sxml (e.g.
732         # http://www.bbc.com/sport/0/football/34475836)
733         playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
734         if playlists:
735             entries = [
736                 self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
737                 for playlist_url in playlists]
738
739         # news article with multiple videos embedded with data-playable
740         data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
741         if data_playables:
742             for _, data_playable_json in data_playables:
743                 data_playable = self._parse_json(
744                     unescapeHTML(data_playable_json), playlist_id, fatal=False)
745                 if not data_playable:
746                     continue
747                 settings = data_playable.get('settings', {})
748                 if settings:
749                     # data-playable with video vpid in settings.playlistObject.items (e.g.
750                     # http://www.bbc.com/news/world-us-canada-34473351)
751                     playlist_object = settings.get('playlistObject', {})
752                     if playlist_object:
753                         items = playlist_object.get('items')
754                         if items and isinstance(items, list):
755                             title = playlist_object['title']
756                             description = playlist_object.get('summary')
757                             duration = int_or_none(items[0].get('duration'))
758                             programme_id = items[0].get('vpid')
759                             formats, subtitles = self._download_media_selector(programme_id)
760                             self._sort_formats(formats)
761                             entries.append({
762                                 'id': programme_id,
763                                 'title': title,
764                                 'description': description,
765                                 'timestamp': timestamp,
766                                 'duration': duration,
767                                 'formats': formats,
768                                 'subtitles': subtitles,
769                             })
770                     else:
771                         # data-playable without vpid but with a playlist.sxml URLs
772                         # in otherSettings.playlist (e.g.
773                         # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
774                         playlist = data_playable.get('otherSettings', {}).get('playlist', {})
775                         if playlist:
776                             entries.append(self._extract_from_playlist_sxml(
777                                 playlist.get('progressiveDownloadUrl'), playlist_id, timestamp))
778
779         if entries:
780             playlist_title = playlist_title or remove_end(self._og_search_title(webpage), ' - BBC News')
781             playlist_description = playlist_description or self._og_search_description(webpage, default=None)
782             return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
783
784         # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
785         programme_id = self._search_regex(
786             [r'data-video-player-vpid="(%s)"' % self._ID_REGEX,
787              r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
788              r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
789             webpage, 'vpid', default=None)
790
791         if programme_id:
792             formats, subtitles = self._download_media_selector(programme_id)
793             self._sort_formats(formats)
794             # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
795             digital_data = self._parse_json(
796                 self._search_regex(
797                     r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
798                 programme_id, fatal=False)
799             page_info = digital_data.get('page', {}).get('pageInfo', {})
800             title = page_info.get('pageName') or self._og_search_title(webpage)
801             description = page_info.get('description') or self._og_search_description(webpage)
802             timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
803             return {
804                 'id': programme_id,
805                 'title': title,
806                 'description': description,
807                 'timestamp': timestamp,
808                 'formats': formats,
809                 'subtitles': subtitles,
810             }
811
812         playlist_title = self._html_search_regex(
813             r'<title>(.*?)(?:\s*-\s*BBC [^ ]+)?</title>', webpage, 'playlist title')
814         playlist_description = self._og_search_description(webpage, default=None)
815
816         def extract_all(pattern):
817             return list(filter(None, map(
818                 lambda s: self._parse_json(s, playlist_id, fatal=False),
819                 re.findall(pattern, webpage))))
820
821         # Multiple video article (e.g.
822         # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
823         EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
824         entries = []
825         for match in extract_all(r'new\s+SMP\(({.+?})\)'):
826             embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
827             if embed_url and re.match(EMBED_URL, embed_url):
828                 entries.append(embed_url)
829         entries.extend(re.findall(
830             r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
831         if entries:
832             return self.playlist_result(
833                 [self.url_result(entry, 'BBCCoUk') for entry in entries],
834                 playlist_id, playlist_title, playlist_description)
835
836         # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
837         medias = extract_all(r"data-media-meta='({[^']+})'")
838
839         if not medias:
840             # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
841             media_asset = self._search_regex(
842                 r'mediaAssetPage\.init\(\s*({.+?}), "/',
843                 webpage, 'media asset', default=None)
844             if media_asset:
845                 media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
846                 medias = []
847                 for video in media_asset_page.get('videos', {}).values():
848                     medias.extend(video.values())
849
850         if not medias:
851             # Multiple video playlist with single `now playing` entry (e.g.
852             # http://www.bbc.com/news/video_and_audio/must_see/33767813)
853             vxp_playlist = self._parse_json(
854                 self._search_regex(
855                     r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
856                     webpage, 'playlist data'),
857                 playlist_id)
858             playlist_medias = []
859             for item in vxp_playlist:
860                 media = item.get('media')
861                 if not media:
862                     continue
863                 playlist_medias.append(media)
864                 # Download single video if found media with asset id matching the video id from URL
865                 if item.get('advert', {}).get('assetId') == playlist_id:
866                     medias = [media]
867                     break
868             # Fallback to the whole playlist
869             if not medias:
870                 medias = playlist_medias
871
872         entries = []
873         for num, media_meta in enumerate(medias, start=1):
874             formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
875             if not formats:
876                 continue
877             self._sort_formats(formats)
878
879             video_id = media_meta.get('externalId')
880             if not video_id:
881                 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
882
883             title = media_meta.get('caption')
884             if not title:
885                 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
886
887             duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
888
889             images = []
890             for image in media_meta.get('images', {}).values():
891                 images.extend(image.values())
892             if 'image' in media_meta:
893                 images.append(media_meta['image'])
894
895             thumbnails = [{
896                 'url': image.get('href'),
897                 'width': int_or_none(image.get('width')),
898                 'height': int_or_none(image.get('height')),
899             } for image in images]
900
901             entries.append({
902                 'id': video_id,
903                 'title': title,
904                 'thumbnails': thumbnails,
905                 'duration': duration,
906                 'timestamp': timestamp,
907                 'formats': formats,
908                 'subtitles': subtitles,
909             })
910
911         return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
912
913
914 class BBCCoUkArticleIE(InfoExtractor):
915     _VALID_URL = 'http://www.bbc.co.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
916     IE_NAME = 'bbc.co.uk:article'
917     IE_DESC = 'BBC articles'
918
919     _TEST = {
920         'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
921         'info_dict': {
922             'id': '3jNQLTMrPlYGTBn0WV6M2MS',
923             'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
924             'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
925         },
926         'playlist_count': 4,
927         'add_ie': ['BBCCoUk'],
928     }
929
930     def _real_extract(self, url):
931         playlist_id = self._match_id(url)
932
933         webpage = self._download_webpage(url, playlist_id)
934
935         title = self._og_search_title(webpage)
936         description = self._og_search_description(webpage).strip()
937
938         entries = [self.url_result(programme_url) for programme_url in re.findall(
939             r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
940
941         return self.playlist_result(entries, playlist_id, title, description)