%% PDCCH Blind Search and DCI Decoding
% The example aids understanding of the control region used in an LTE
% downlink subframe and its channel structure by showing how a Downlink
% Control Information (DCI) message is generated and transmitted over a
% Physical Downlink Control Channel (PDCCH) and recovered by performing
% blind decoding using the LTE Toolbox(TM).

% Copyright 2009-2018 The MathWorks, Inc.

%% Introduction
% To support the transmission of downlink and uplink transport channels
% Downlink Shared Channel(DL-SCH) and Uplink Shared Channel (UL-SCH)
% control signaling is required. This control signaling enables a UE to
% successfully receive, demodulate, and decode the DL-SCH. The Downlink
% Control Information (DCI) is transmitted through the Physical Downlink
% Control Channel (PDCCH) and includes information about the DL-SCH
% resource allocation (the set of resource blocks containing the DL-SCH),
% transport format and information related to the DL-SCH Hybrid Automatic
% Repeat reQuest (ARQ).
% 
% To form the PDCCH payload the DCI undergoes channel coding: addition of a
% CRC attachment followed by convolutional coding and rate matching
% according to PDCCH format capacity. The coded DCI bits i.e. PDCCH
% payload, are then mapped to Control Channel Elements (CCEs) according to
% the PDCCH format. These coded bits are then converted to complex
% modulated symbols after performing operations including scrambling, QPSK
% modulation, layer mapping and precoding. Finally, the modulated symbols
% are interleaved and mapped to physical Resource Elements (REs).
% 
% After performing deinterleaving, deprecoding, symbol combining, symbol
% demodulation and descrambling at the receiver, the UE is required to
% perform blind decoding of the PDCCH payload as it is not aware of the
% detailed control channel structure, including the number of control
% channels and the number of CCEs to which each control channel is mapped.
% Multiple PDCCHs can be transmitted in a single subframe which may and may
% not be all relevant to a particular UE. The UE finds the PDCCH specific
% to it by monitoring a set of PDCCH candidates (a set of consecutive CCEs
% on which a PDCCH could be mapped) in every subframe. The UE uses its
% Radio Network Temporary Identifier (RNTI) to try and decode candidates.
% The RNTI is used to demask a PDCCH candidate's CRC. If no CRC error is
% detected the UE determines that PDCCH carries its own control
% information.

%% Control Region
% Downlink control signaling is located at the start of each downlink
% subframe (up to the first three OFDM symbols). One of the advantages of
% transmitting control channel at the start of every subframe is if the UE
% is not scheduled it may turn off its receiver circuitry for larger part
% of the subframe which results in reduced power consumption. Downlink
% control signaling is carried by three physical channels. The Physical
% Control Format Indicator Channel (PCFICH) to indicate the number of OFDM
% symbols used for control signaling in this subframe, Physical Hybrid-ARQ
% Indicator Channel (PHICH) which carries downlink Acknowledgment
% (ACK)/Negative Acknowledgment (NACK) for uplink data transmission and
% Physical Downlink Common Control Channel (PDCCH) which carries the
% downlink scheduling assignment and uplink scheduling grants.
% 
% The PDCCH carries scheduling assignments and other control information in
% the form of DCI messages. A PDCCH is transmitted on one CCE or an
% aggregation of several consecutive CCEs, where a CCE corresponds to 9
% Resource Element Groups (REGs). In PDCCH transmission, only those REGs
% are used which are not assigned to PCFICH or PHICH. Each REG contains 4
% Resource Elements (REs). Thus, REGs are used for defining the mapping of
% control channels to resource elements.
% 
% The control region of a downlink subframe comprises the multiplexing of
% all PDCCHs bits into a single block of data which is subsequently
% processed to form complex modulated symbols. These symbols are then
% divided to form blocks of complex-valued symbols quadruplets. These
% quadruplets are then interleaved and cyclically shifted prior to PDCCH
% resource mapping.

%% PDCCH and DCI Formats
% The number of CCEs in a PDCCH transmission depends upon the PDCCH format,
% which can be 0, 1, 2, and 3 depending upon number of bits to be
% transmitted. The PDCCH bits are created from a DCI message after
% performing CRC attachment, channel coding and rate matching. Multiple
% PDCCHs can be transmitted in a subframe thus the UE must monitor all
% PDCCH in given subframe control region.
% 
% The DCI message transmits uplink or downlink scheduling information or an
% uplink Transmit Power Control (TPC) command. Depending on the purpose of
% control message, different DCI formats are defined. The information
% provided contains everything necessary for the UE to be able to identify
% the resources required to receive the Physical Downlink Data Channel
% (PDSCH) in that subframe and to decode it. The DCI formats are:
%
% * Format 0 for transmission of Uplink Shared Channel (UL-SCH) allocation
% * Format 1 for transmission of DL-SCH allocation for Single Input
%   Multiple Output (SIMO) operation
% * Format 1A for compact transmission of DL-SCH allocation for SIMO
%   operation or allocating a dedicated preamble signature to a UE for 
%   random access
% * Format 1B for transmission control information of Multiple Input
%   Multiple Output (MIMO) rank 1 based compact resource assignment
% * Format 1C for very compact transmission of PDSCH assignment
% * Format 1D same as format1B with additional information of power offset
% * Format 2 and Format 2A for transmission of DL-SCH allocation for closed
%   and open loop MIMO operation, respectively
% * Format 2B for the scheduling of dual layer transmission (antenna 
%   ports 7 & 8)
% * Format 2C for the scheduling of up to 8 layer transmission (antenna 
%   ports 7 to 14) using TM9
% * Format 2D for the scheduling of up to 8 layer transmission (antenna 
%   ports 7 to 14) using TM10
% * Format 3 and Format 3A for transmission of TPC command for an uplink
%   channel
% * Format 4 for the scheduling of PUSCH with multi-antenna port 
%   transmission mode

%% Search Space and PDCCH Candidates
% Once the DCI message is generated and channel coded according to the
% required DCI and PDCCH format, PDCCH multiplexing, scrambling,
% modulation, precoding, interleaving and layer mapping are performed to
% form complex symbols. These complex symbols are now ready to be mapped
% onto REs. The REs are defined in terms of REGs/CCEs allocated to a
% transmission. The number of CCEs allocated is given by the PDCCH format.
% The control region of a subframe is a collection of CCEs and can contain
% PDCCHs for multiple UEs thus the UE has to monitor a large area to
% extract its own control information. As the UE is not explicitly informed
% of the detailed control channel structure it has to blindly attempt to
% decode the control region. Unfortunately, this may impose a substantial
% burden on the UE as at large bandwidths the control region may be very
% large. This may exceed practical hardware limitations and lead to
% increased cost and/or reduced performance of the UE.
% 
% To simplify the decoding task at the UE, the whole control region is
% sub-divided into common and UE-specific search spaces which the UE should
% monitor (attempt to decode each of the PDCCHs). Each space comprises 2, 4
% or 6 PDCCH candidates whose data length depends on the PDCCH format; each
% PDCCH must be transmitted on 1, 2, 4 or 8 CCE(s) (1 CCE = 9 REGs = 9*4
% REs = 72 bits).
% 
% The PDCCH candidates consist of consecutive CCEs. The candidates within
% the PDCCH candidate set do not have to be unique, especially for smaller
% bandwidths. The common and UE-specific search spaces can overlap with
% each other. The size of search space is determined by the number of PDCCH
% candidates and the size of CCE aggregation level. That is, the size of
% the search space is integer times the size of CCE aggregation level or
% the number of PDCCH candidates.

%% Common Search Space
% The common search space carries the common control information and is
% monitored by all UEs in a cell. The number of CCE aggregation levels
% supported by the common search space is limited to two i.e. 4 and 8 as
% compared to the UE-specific search space where four CCE aggregation levels
% are possible. This reduces the burden on UE for decoding common control
% information compared to decoding UE-specific control information. The
% common control space is used to carry important initial information
% including paging information, system information and random access
% procedures.
% 
% When searching the common control space the decoder always starts
% decoding from the first CCE. This restriction further simplifies the
% common search. The decoding is done on every possible PDCCH candidate set
% for given PDCCH format until it successfully decodes the PDCCH present in
% common search space.

%% UE-Specific Search Space
% The UE-specific search space carries control information specific to a
% particular UE and is monitored by at least one UE in a cell. Unlike the
% common space search, the starting location of the UE-specific search
% space may be varied for each subframe or UE. The starting location of the
% UE-specific search space is determined in every subframe using a hash
% function, as specified in TS36.213, Clause 9 [ <#17 1> ].
% 
% In the UE-specific search space the UE finds its PDCCH by monitoring a
% set of PDCCH candidates (a set of consecutive CCEs on which PDCCH could
% be mapped) in every subframe. If no CRC error is detected when the UE
% uses its RNTI to demask the CRC (16-bit value also refers as C-RNTI) on
% a PDCCH, the UE determines that PDCCH carries its own control
% information. The PDCCH candidate sets correspond to different PDCCH
% formats. There are 4 PDCCH formats: 0, 1, 2 or 3. If the UE fails to
% decode any PDCCH candidates for a given PDCCH format it tries to decode
% candidates for other PDCCH formats. This process is repeated for all
% possible PDCCH formats until all directed PDCCHs are successfully decoded
% in UE-specific search space.

%% Example DCI Generation, Transmission and Recovery
% In this example, a control channel containing a downlink control
% information (DCI) message is generated and transmitted over a physical
% downlink control channel (PDCCH). Once the PDCCH payload is generated,
% this example demonstrates how blind decoding is performed to decode the
% PDCCH in a given subframe.

%% Cell-Wide Settings
% A structure |enbConfig| is used to configure the eNodeB.

enbConfig.NDLRB = 6;                % No of Downlink RBs in total BW
enbConfig.CyclicPrefix = 'Normal';  % CP length
enbConfig.CFI = 3;                  % 4 PDCCH symbols as NDLRB <= 10
enbConfig.Ng = 'Sixth';             % HICH groups
enbConfig.CellRefP = 1;             % 1-antenna ports
enbConfig.NCellID = 10;             % Physical layer cell identity
enbConfig.NSubframe = 0;            % Subframe number 0
enbConfig.DuplexMode = 'FDD';       % Frame structure

%% DCI Message Generation
% Generate a DCI message to be mapped to the PDCCH.

dciConfig.DCIFormat = 'Format1A';   % DCI message format
dciConfig.Allocation.RIV = 26;      % Resource indication value

% Create DCI message for given configuration
[dciMessage, dciMessageBits] = lteDCI(enbConfig, dciConfig);

%% DCI Channel Coding
% DCI message channel coding includes the following operations: CRC
% insertion, tail-biting convolutional coding and rate matching. The field
% |PDCCHFormat| indicates that one control channel element (CCE) is used
% for the transmission of PDCCH, where a CCE is composed of 36 useful
% resource elements.

C_RNTI = 100;                         % 16-bit UE-specific mask
pdcchConfig.RNTI = C_RNTI;            % Radio network temporary identifier
pdcchConfig.PDCCHFormat = 0;          % PDCCH format

% DCI message bits coding to form coded DCI bits
codedDciBits = lteDCIEncode(pdcchConfig, dciMessageBits);

%% PDCCH Bits Generation
% The capacity of the control region depends on the bandwidth, the Control
% Format Indicator (CFI), the number of antenna ports and the HICH groups.
% The total number of resources available for PDCCH can be calculated using
% <matlab:doc('ltePDCCHInfo') ltePDCCHInfo>.
%
% Not all the available bits in the PDCCH region are necessarily used.
% Therefore the convention adopted is to set unused bits to -1, while bit
% locations with values 0 or 1 are used. Initially, all elements are
% initialized with -1 to indicate that all the bits are unused.

pdcchDims = ltePDCCHInfo(enbConfig);

% Initialize elements with -1 to indicate that all the bits are unused
pdcchBits = -1*ones(pdcchDims.MTot, 1);

% Perform search space for UE-specific control channel candidates.
candidates = ltePDCCHSpace(enbConfig, pdcchConfig, {'bits', '1based'});

% Map PDCCH payload on available UE-specific candidate. In this example the
% first available candidate is used to map the coded DCI bits.
pdcchBits ( candidates(1, 1) : candidates(1, 2) ) = codedDciBits;

%% PDCCH Complex-Valued Modulated Symbol Generation
% From the set of bits used in |pdcchBits| (values not set to -1) the PDCCH
% complex symbols are generated. The following operations are required:
% scrambling, QPSK modulation, layer mapping, precoding and interleaving.

pdcchSymbols = ltePDCCH(enbConfig, pdcchBits);

%% Noise Addition
% The PDCCH complex symbols are then passed through an AWGN channel. The
% channel is generated using <matlab:doc('randn') randn>; its variance can
% be configured by |nVariance|. The variation in number of retransmissions
% can be simulated using wide range of |nVariance| parameter.

nVariance = 0.01; % Noise power
noise = complex(randn(size(pdcchSymbols))*sqrt(nVariance/2), ...
        randn(size(pdcchSymbols))*sqrt(nVariance/2));  % Generate noise
pdcchSymbolsNoisy = pdcchSymbols + noise;    % Add noise to PDSCH symbols

%% PDCCH Decoding
% Perform PDCCH receiver processing including deinterleaving, cyclic
% shifting, deprecoding, layer demapping, QPSK soft demodulation and
% descrambling.

recPdcchBits = ltePDCCHDecode(enbConfig, pdcchSymbolsNoisy);

%% Blind Decoding Using DCI Search
% The UE is only informed of the number of OFDM symbols within the control
% region of a subframe and is not provided with the location of its
% corresponding PDCCH. The UE finds its PDCCH by monitoring a set of PDCCH
% candidates in every subframe. This is referred to as blind decoding. The
% UE demasks each control candidate's CRC using its Radio Network
% Temporary Identifier (RNTI). If no CRC error is detected, the UE
% considers it as a successful decoding attempt and reads the control
% information within the successful candidate.
% 
% The eNodeB determines a PDCCH format to be transmitted to the UE, creates
% an appropriate DCI and attaches a CRC. The CRC is then masked with an
% RNTI according to the owner or usage of PDCCH. If the PDCCH is for a
% specific UE, the CRC will be masked with a UE unique identifier, for
% example a Cell-RNTI (C-RNTI). If the PDCCH contains paging information,
% the CRC will be masked with a paging indication identifier i.e.
% Paging-RNTI (P-RNTI). If the PDCCH contains system information, a system
% information identifier i.e. a system information-RNTI (SI-RNTI) will be
% used to mask the CRC.
% 
% With the possibilities of different RNTIs, PDCCH candidates, DCI and
% PDCCH formats, a significant number of attempts may be required to
% successfully decode the PDCCH. To overcome this complexity the UE first
% tries to blindly decode the first CCE in the control channel candidate
% set of a subframe. If the blind decoding fails, the UE tries to blindly
% decode the first 2, 4 then 8 CCEs sequentially, where the starting
% location is fixed for common search case and is given by hash function,
% as defined in TS36.213, Clause 9 [ <#17 1> ], for UE-specific case.
%
% <matlab:doc('ltePDCCHSearch') ltePDCCHSearch> first tries to decode
% PDCCHs in the common search space before trying in UE-specific search
% space. When searching the common search space it iterates for only two
% aggregation levels i.e. 4 and 8 and tries decode all PDDCH candidates for
% all possible common space DCI formats. The UE-specific search is carried
% out on four aggregation levels i.e. 1, 2, 4 and 8. The PDCCH candidates
% are generated using <matlab:doc('ltePDCCHSpace') ltePDCCHSpace>. If no
% CRC error is detected during a decoding attempt, the UE considers it a
% successful decoding and reads decoded DCI message.
%
% |decDCI| is a cell array of structures containing the fields associated
% with one or more decoded DCI message(s). As multiple PDCCHs can be 
% transmitted in a subframe thus UE has to monitor all possible PDCCHs
% directed at it.
%   
% |decDCIBits| is a cell array containing one or more vectors of bit values
% corresponding to successfully decoded DCI messages.

ueConfig.RNTI = C_RNTI;
ueConfig.ControlChannelType = 'PDCCH';
ueConfig.EnableCarrierIndication = 'Off';
ueConfig.SearchSpace = 'UESpecific';
ueConfig.EnableMultipleCSIRequest = 'Off';
ueConfig.EnableSRSRequest = 'Off';
ueConfig.NTxAnts = 1;
[rxDCI, rxDCIBits] = ltePDCCHSearch(enbConfig, ueConfig, recPdcchBits);
decDCI = rxDCI{1};          % Decoded DCI information
decDCIBits = rxDCIBits{1};  % Decoded DCI bits

%% Display the Recovered RIV

fprintf(['\n\n Blind Decoding successful, the recovered resource '...
       'allocation is ' num2str(decDCI.Allocation.RIV) ' \n\n']);

%% Selected Bibliography
% # 3GPP TS 36.213 "Physical layer procedures"
