
Recherche avancée
Autres articles (27)
-
Les formats acceptés
28 janvier 2010, parLes commandes suivantes permettent d’avoir des informations sur les formats et codecs gérés par l’installation local de ffmpeg :
ffmpeg -codecs ffmpeg -formats
Les format videos acceptés en entrée
Cette liste est non exhaustive, elle met en exergue les principaux formats utilisés : h264 : H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 m4v : raw MPEG-4 video format flv : Flash Video (FLV) / Sorenson Spark / Sorenson H.263 Theora wmv :
Les formats vidéos de sortie possibles
Dans un premier temps on (...) -
Dépôt de média et thèmes par FTP
31 mai 2013, parL’outil MédiaSPIP traite aussi les média transférés par la voie FTP. Si vous préférez déposer par cette voie, récupérez les identifiants d’accès vers votre site MédiaSPIP et utilisez votre client FTP favori.
Vous trouverez dès le départ les dossiers suivants dans votre espace FTP : config/ : dossier de configuration du site IMG/ : dossier des média déjà traités et en ligne sur le site local/ : répertoire cache du site web themes/ : les thèmes ou les feuilles de style personnalisées tmp/ : dossier de travail (...) -
Les thèmes de MediaSpip
4 juin 20133 thèmes sont proposés à l’origine par MédiaSPIP. L’utilisateur MédiaSPIP peut rajouter des thèmes selon ses besoins.
Thèmes MediaSPIP
3 thèmes ont été développés au départ pour MediaSPIP : * SPIPeo : thème par défaut de MédiaSPIP. Il met en avant la présentation du site et les documents média les plus récents ( le type de tri peut être modifié - titre, popularité, date) . * Arscenic : il s’agit du thème utilisé sur le site officiel du projet, constitué notamment d’un bandeau rouge en début de page. La structure (...)
Sur d’autres sites (3771)
-
How to stream synchronized video and audio in real-time from an Android smartphone using HLS while preserving orientation metadata ?
6 mars, par Jérôme LAROSEHello, 
I am working on an Android application where I need to stream video
from one or two cameras on my smartphone, along with audio from the
microphone, in real-time via a link or web page accessible to users.
The stream should be live, allow rewinding (DVR functionality), and be
recorded simultaneously. A latency of 1 to 2 minutes is acceptable,
and the streaming is one-way. 

I have chosen HLS (HTTP Live Streaming) for its browser compatibility
and DVR support. However, I am encountering issues with audio-video
synchronization, managing camera orientation metadata, and format
conversions.



Here are my attempts :


- 

-
MP4 segmentation with
MediaRecorder


- 

- I used
MediaRecorder
withsetNextOutputFile
to generate short MP4 segments, thenffmpeg-kit
to convert them to fMP4 for HLS. - Expected : Well-aligned segments for smooth HLS playback.
- Result : Timestamp issues causing jumps or interruptions in playback.








- I used
-
MPEG2-TS via local socket


- 

- I configured
MediaRecorder
to produce an MPEG2-TS stream sent via a local socket toffmpeg-kit
. - Expected : Stable streaming with preserved metadata.
- Result : Streaming works, but orientation metadata is lost, leading to incorrectly oriented video (e.g., rotated 90°).








- I configured
-
Orientation correction with
ffmpeg


- 

- I tested
-vf transpose=1
inffmpeg
to correct the orientation. - Expected : Correctly oriented video without excessive latency.
- Result : Re-encoding takes too long for real-time streaming, causing unacceptable latency.








- I tested
-
MPEG2-TS to fMP4 conversion


- 

- I converted the MPEG2-TS stream to fMP4 with
ffmpeg
to preserve orientation. - Expected : Perfect audio-video synchronization.
- Result : Slight desynchronization between audio and video, affecting the user experience.








- I converted the MPEG2-TS stream to fMP4 with










I am looking for a solution to :


- 

- Stream an HLS feed from Android with correctly timestamped segments.
- Preserve orientation metadata without heavy re-encoding.
- Ensure perfect audio-video synchronization.








UPDATE


package com.example.angegardien

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.SurfaceTexture
import android.hardware.camera2.*
import android.media.*
import android.os.*
import android.util.Log
import android.view.Surface
import android.view.TextureView
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.core.app.ActivityCompat
import com.arthenica.ffmpegkit.FFmpegKit
import fi.iki.elonen.NanoHTTPD
import kotlinx.coroutines.*
import java.io.File
import java.io.IOException
import java.net.ServerSocket
import android.view.OrientationEventListener

/**
 * MainActivity class:
 * - Manages camera operations using the Camera2 API.
 * - Records video using MediaRecorder.
 * - Pipes data to FFmpeg to generate HLS segments.
 * - Hosts a local HLS server using NanoHTTPD to serve the generated HLS content.
 */
class MainActivity : ComponentActivity() {

 // TextureView used for displaying the camera preview.
 private lateinit var textureView: TextureView
 // Camera device instance.
 private lateinit var cameraDevice: CameraDevice
 // Camera capture session for managing capture requests.
 private lateinit var cameraCaptureSession: CameraCaptureSession
 // CameraManager to access camera devices.
 private lateinit var cameraManager: CameraManager
 // Directory where HLS output files will be stored.
 private lateinit var hlsDir: File
 // Instance of the HLS server.
 private lateinit var hlsServer: HlsServer

 // Camera id ("1" corresponds to the rear camera).
 private val cameraId = "1"
 // Flag indicating whether recording is currently active.
 private var isRecording = false

 // MediaRecorder used for capturing audio and video.
 private lateinit var activeRecorder: MediaRecorder
 // Surface for the camera preview.
 private lateinit var previewSurface: Surface
 // Surface provided by MediaRecorder for recording.
 private lateinit var recorderSurface: Surface

 // Port for the FFmpeg local socket connection.
 private val ffmpegPort = 8080

 // Coroutine scope to manage asynchronous tasks.
 private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())

 // Variables to track current device rotation and listen for orientation changes.
 private var currentRotation = 0
 private lateinit var orientationListener: OrientationEventListener

 override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)

 // Initialize the TextureView and set it as the content view.
 textureView = TextureView(this)
 setContentView(textureView)

 // Get the CameraManager system service.
 cameraManager = getSystemService(CAMERA_SERVICE) as CameraManager
 // Setup the directory for HLS output.
 setupHLSDirectory()

 // Start the local HLS server on port 8081.
 hlsServer = HlsServer(8081, hlsDir, this)
 try {
 hlsServer.start()
 Log.d("HLS_SERVER", "HLS Server started on port 8081")
 } catch (e: IOException) {
 Log.e("HLS_SERVER", "Error starting HLS Server", e)
 }

 // Initialize the current rotation.
 currentRotation = getDeviceRotation()

 // Add a listener to detect orientation changes.
 orientationListener = object : OrientationEventListener(this) {
 override fun onOrientationChanged(orientation: Int) {
 if (orientation == ORIENTATION_UNKNOWN) return // Skip unknown orientations.
 // Determine the new rotation angle.
 val newRotation = when {
 orientation >= 315 || orientation < 45 -> 0
 orientation >= 45 && orientation < 135 -> 90
 orientation >= 135 && orientation < 225 -> 180
 orientation >= 225 && orientation < 315 -> 270
 else -> 0
 }
 // If the rotation has changed and recording is active, update the rotation.
 if (newRotation != currentRotation && isRecording) {
 Log.d("ROTATION", "Orientation change detected: $newRotation")
 currentRotation = newRotation
 }
 }
 }
 orientationListener.enable()

 // Set up the TextureView listener to know when the surface is available.
 textureView.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
 override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
 // Open the camera when the texture becomes available.
 openCamera()
 }
 override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {}
 override fun onSurfaceTextureDestroyed(surface: SurfaceTexture) = false
 override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {}
 }
 }

 /**
 * Sets up the HLS directory in the public Downloads folder.
 * If the directory exists, it deletes it recursively and creates a new one.
 */
 private fun setupHLSDirectory() {
 val downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
 hlsDir = File(downloadsDir, "HLS_Output")

 if (hlsDir.exists()) {
 hlsDir.deleteRecursively()
 }
 hlsDir.mkdirs()

 Log.d("HLS", "📂 HLS folder created: ${hlsDir.absolutePath}")
 }

 /**
 * Opens the camera after checking for necessary permissions.
 */
 private fun openCamera() {
 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
 ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
 // Request permissions if they are not already granted.
 ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO), 101)
 return
 }

 try {
 // Open the specified camera using its cameraId.
 cameraManager.openCamera(cameraId, object : CameraDevice.StateCallback() {
 override fun onOpened(camera: CameraDevice) {
 cameraDevice = camera
 // Start the recording session once the camera is opened.
 startNextRecording()
 }
 override fun onDisconnected(camera: CameraDevice) { camera.close() }
 override fun onError(camera: CameraDevice, error: Int) { camera.close() }
 }, null)
 } catch (e: CameraAccessException) {
 e.printStackTrace()
 }
 }

 /**
 * Starts a new recording session:
 * - Sets up the preview and recorder surfaces.
 * - Creates a pipe for MediaRecorder output.
 * - Creates a capture session for simultaneous preview and recording.
 */
 private fun startNextRecording() {
 // Get the SurfaceTexture from the TextureView and set its default buffer size.
 val texture = textureView.surfaceTexture!!
 texture.setDefaultBufferSize(1920, 1080)
 // Create the preview surface.
 previewSurface = Surface(texture)

 // Create and configure the MediaRecorder.
 activeRecorder = createMediaRecorder()

 // Create a pipe to route MediaRecorder data.
 val pipe = ParcelFileDescriptor.createPipe()
 val pfdWrite = pipe[1] // Write end used by MediaRecorder.
 val pfdRead = pipe[0] // Read end used by the local socket server.

 // Set MediaRecorder output to the file descriptor of the write end.
 activeRecorder.setOutputFile(pfdWrite.fileDescriptor)
 setupMediaRecorder(activeRecorder)
 // Obtain the recorder surface from MediaRecorder.
 recorderSurface = activeRecorder.surface

 // Create a capture request using the RECORD template.
 val captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD)
 captureRequestBuilder.addTarget(previewSurface)
 captureRequestBuilder.addTarget(recorderSurface)

 // Create a capture session including both preview and recorder surfaces.
 cameraDevice.createCaptureSession(
 listOf(previewSurface, recorderSurface),
 object : CameraCaptureSession.StateCallback() {
 override fun onConfigured(session: CameraCaptureSession) {
 cameraCaptureSession = session
 captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO)
 // Start a continuous capture request.
 cameraCaptureSession.setRepeatingRequest(captureRequestBuilder.build(), null, null)

 // Launch a coroutine to start FFmpeg and MediaRecorder with synchronization.
 scope.launch {
 startFFmpeg()
 delay(500) // Wait for FFmpeg to be ready.
 activeRecorder.start()
 isRecording = true
 Log.d("HLS", "🎥 Recording started...")
 }

 // Launch a coroutine to run the local socket server to forward data.
 scope.launch {
 startLocalSocketServer(pfdRead)
 }
 }
 override fun onConfigureFailed(session: CameraCaptureSession) {
 Log.e("Camera2", "❌ Configuration failed")
 }
 },
 null
 )
 }

 /**
 * Coroutine to start a local socket server.
 * It reads from the MediaRecorder pipe and sends the data to FFmpeg.
 */
 private suspend fun startLocalSocketServer(pfdRead: ParcelFileDescriptor) {
 withContext(Dispatchers.IO) {
 val serverSocket = ServerSocket(ffmpegPort)
 Log.d("HLS", "Local socket server started on port $ffmpegPort")

 // Accept connection from FFmpeg.
 val socket = serverSocket.accept()
 Log.d("HLS", "Connection accepted from FFmpeg")

 // Read data from the pipe and forward it through the socket.
 val inputStream = ParcelFileDescriptor.AutoCloseInputStream(pfdRead)
 val outputStream = socket.getOutputStream()
 val buffer = ByteArray(8192)
 var bytesRead: Int
 while (inputStream.read(buffer).also { bytesRead = it } != -1) {
 outputStream.write(buffer, 0, bytesRead)
 }
 outputStream.close()
 inputStream.close()
 socket.close()
 serverSocket.close()
 }
 }

 /**
 * Coroutine to start FFmpeg using a local TCP input.
 * Applies a video rotation filter based on device orientation and generates HLS segments.
 */
 private suspend fun startFFmpeg() {
 withContext(Dispatchers.IO) {
 // Retrieve the appropriate transpose filter based on current rotation.
 val transposeFilter = getTransposeFilter(currentRotation)

 // FFmpeg command to read from the TCP socket and generate an HLS stream.
 // Two alternative commands are commented below.
 // val ffmpegCommand = "-fflags +genpts -i tcp://localhost:$ffmpegPort -c copy -bsf:a aac_adtstoasc -movflags +faststart -f dash -seg_duration 10 -hls_playlist 1 ${hlsDir.absolutePath}/manifest.mpd"
 // val ffmpegCommand = "-fflags +genpts -i tcp://localhost:$ffmpegPort -c copy -bsf:a aac_adtstoasc -movflags +faststart -f hls -hls_time 5 -hls_segment_type fmp4 -hls_flags split_by_time -hls_list_size 0 -hls_playlist_type event -hls_fmp4_init_filename init.mp4 -hls_segment_filename ${hlsDir.absolutePath}/segment_%03d.m4s ${hlsDir.absolutePath}/playlist.m3u8"
 val ffmpegCommand = "-fflags +genpts -i tcp://localhost:$ffmpegPort -vf $transposeFilter -c:v libx264 -preset ultrafast -crf 23 -c:a copy -movflags +faststart -f hls -hls_time 0.1 -hls_segment_type mpegts -hls_flags split_by_time -hls_list_size 0 -hls_playlist_type event -hls_segment_filename ${hlsDir.absolutePath}/segment_%03d.ts ${hlsDir.absolutePath}/playlist.m3u8"

 FFmpegKit.executeAsync(ffmpegCommand) { session ->
 if (session.returnCode.isValueSuccess) {
 Log.d("HLS", "✅ HLS generated successfully")
 } else {
 Log.e("FFmpeg", "❌ Error generating HLS: ${session.allLogsAsString}")
 }
 }
 }
 }

 /**
 * Gets the current device rotation using the WindowManager.
 */
 private fun getDeviceRotation(): Int {
 val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
 return when (windowManager.defaultDisplay.rotation) {
 Surface.ROTATION_0 -> 0
 Surface.ROTATION_90 -> 90
 Surface.ROTATION_180 -> 180
 Surface.ROTATION_270 -> 270
 else -> 0
 }
 }

 /**
 * Returns the FFmpeg transpose filter based on the rotation angle.
 * Used to rotate the video stream accordingly.
 */
 private fun getTransposeFilter(rotation: Int): String {
 return when (rotation) {
 90 -> "transpose=1" // 90° clockwise
 180 -> "transpose=2,transpose=2" // 180° rotation
 270 -> "transpose=2" // 90° counter-clockwise
 else -> "transpose=0" // No rotation
 }
 }

 /**
 * Creates and configures a MediaRecorder instance.
 * Sets up audio and video sources, formats, encoders, and bitrates.
 */
 private fun createMediaRecorder(): MediaRecorder {
 return MediaRecorder().apply {
 setAudioSource(MediaRecorder.AudioSource.MIC)
 setVideoSource(MediaRecorder.VideoSource.SURFACE)
 setOutputFormat(MediaRecorder.OutputFormat.MPEG_2_TS)
 setVideoEncodingBitRate(5000000)
 setVideoFrameRate(24)
 setVideoSize(1080, 720)
 setVideoEncoder(MediaRecorder.VideoEncoder.H264)
 setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
 setAudioSamplingRate(16000)
 setAudioEncodingBitRate(96000) // 96 kbps
 }
 }

 /**
 * Prepares the MediaRecorder and logs the outcome.
 */
 private fun setupMediaRecorder(recorder: MediaRecorder) {
 try {
 recorder.prepare()
 Log.d("HLS", "✅ MediaRecorder prepared")
 } catch (e: IOException) {
 Log.e("HLS", "❌ Error preparing MediaRecorder", e)
 }
 }

 /**
 * Custom HLS server class extending NanoHTTPD.
 * Serves HLS segments and playlists from the designated HLS directory.
 */
 private inner class HlsServer(port: Int, private val hlsDir: File, private val context: Context) : NanoHTTPD(port) {
 override fun serve(session: IHTTPSession): Response {
 val uri = session.uri.trimStart('/')

 // Intercept the request for `init.mp4` and serve it from assets.
 /*
 if (uri == "init.mp4") {
 Log.d("HLS Server", "📡 Intercepting init.mp4, sending file from assets...")
 return try {
 val assetManager = context.assets
 val inputStream = assetManager.open("init.mp4")
 newFixedLengthResponse(Response.Status.OK, "video/mp4", inputStream, inputStream.available().toLong())
 } catch (e: Exception) {
 Log.e("HLS Server", "❌ Error reading init.mp4 from assets: ${e.message}")
 newFixedLengthResponse(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "Server error")
 }
 }
 */

 // Serve all other HLS files normally from the hlsDir.
 val file = File(hlsDir, uri)
 return if (file.exists()) {
 newFixedLengthResponse(Response.Status.OK, getMimeTypeForFile(uri), file.inputStream(), file.length())
 } else {
 newFixedLengthResponse(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "File not found")
 }
 }
 }

 /**
 * Clean up resources when the activity is destroyed.
 * Stops recording, releases the camera, cancels coroutines, and stops the HLS server.
 */
 override fun onDestroy() {
 super.onDestroy()
 if (isRecording) {
 activeRecorder.stop()
 activeRecorder.release()
 }
 cameraDevice.close()
 scope.cancel()
 hlsServer.stop()
 orientationListener.disable()
 Log.d("HLS", "🛑 Activity destroyed")
 }
}



I have three examples of ffmpeg commands.


- 

- One command segments into DASH, but the camera does not have the correct rotation.
- One command segments into HLS without re-encoding with 5-second segments ; it’s fast but does not have the correct rotation.
- One command segments into HLS with re-encoding, which applies a rotation. It’s too slow for 5-second segments, so a 1-second segment was chosen.








Note :


- 

- In the second command ("One command segments into HLS without re-encoding with 5-second segments ; it’s fast but does not have the correct rotation."), it returns fMP4. To achieve the correct rotation, I provide a preconfigured
init.mp4
file during the HTTP request to retrieve it (see comment). - In the third command ("One command segments into HLS with re-encoding, which applies a rotation. It’s too slow for 5-second segments, so a 1-second segment was chosen."), it returns TS.






-
-
A Primer to Ethical Marketing : How to Build Trust in a Privacy-First World
Imagine a marketing landscape where transparency replaces tactics, where consumer privacy is prioritised over exploitation, and where authentic value builds genuine relationships.
This isn’t just an ideal—it’s the future of marketing. And it starts with ethical marketing practices.
76% of consumers refuse to buy from companies they do not trust with their data. Ethical marketing has become essential for business survival. As privacy regulations tighten and third-party cookies phase out, marketers face a critical question : how can they balance effective, personalised campaigns whilst respecting privacy ?
This comprehensive guide explores what ethical marketing is, the key principles behind ethical marketing practices, and practical strategies to implement an ethical approach that builds trust while driving growth.
What is ethical marketing ? A comprehensive definition
Ethical marketing places respect for consumer boundaries at its core whilst delivering genuine value. It prioritises transparent practices, honest communication, and fair value exchange with consumers. This approach represents a significant shift from traditional marketing, which often relied on collecting vast amounts of user data through invasive tracking methods and obscure policies.
The modern approach to ethical marketing creates a foundation built on three key pillars :
- User Control : Giving people genuine choice and agency over their data
- Fair Value : Providing clear benefits in exchange for any data shared
- Transparency : Being honest about how data is collected, used, and protected
Key principles of ethical marketing
Transparency
Transparency means being clear and forthright about your marketing practices, data collection policies, and business operations. It involves :
- Using plain language to explain how you collect and use customer data
- Being upfront about pricing, product limitations, and terms of service
- Disclosing sponsored content and affiliate relationships
- Making privacy policies accessible and understandable
When Matomo surveyed 2,000 consumers, 81% said they believe an organisation’s data practices reflect their overall treatment of customers. Transparency isn’t just about compliance—it’s about demonstrating respect.
Honesty
While similar to transparency, honesty focuses specifically on truthfulness in communications :
- Avoiding misleading claims or exaggerations about products and services
- Not manipulating statistics or research findings to support marketing narratives
- Representing products accurately in advertisements and marketing materials
- Acknowledging mistakes and taking responsibility when things go wrong
Social responsibility
Ethical marketing requires consideration of a brand’s impact on society as a whole :
- Considering environmental impacts of marketing campaigns and business practices
- Promoting diversity and inclusion in marketing representations
- Supporting social causes authentically rather than through “purpose-washing”
- Ensuring marketing activities don’t promote harmful stereotypes or behaviours
Ethical marketing dilemmas : Navigating complex business decisions
Data privacy concerns
The digital marketing landscape has been transformed by increasing awareness of data privacy issues and stricter regulations like GDPR, CCPA, and upcoming legislation. Key challenges include :
- The phase-out of third-party cookies, impacting targeting and measurement
- Growing consumer resistance to invasive tracking technologies
- Balancing personalisation with privacy (71% of consumers expect personalised experiences, yet demand privacy)
- Ensuring compliance across different jurisdictional requirements
Cultural sensitivity
Global brands must navigate complex cultural landscapes :
- Avoiding cultural appropriation in marketing campaigns
- Understanding varied cultural expectations around privacy
- Respecting local customs and values in international marketing
- Adapting messaging appropriately for diverse audiences
Environmental sustainability
The environmental impact of marketing activities is under increasing scrutiny :
- Digital carbon footprints from ad serving and website hosting
- Waste generated from physical marketing materials
- Promoting sustainable products honestly without greenwashing
- Aligning marketing messages with actual business practices
The benefits of ethical marketing
For years, digital marketing has relied on third-party data collection and broad-scale tracking. However, new regulations such as GDPR, CCPA, and the end of third-party cookies are pushing brands to adopt ethical data practices.
Increased customer loyalty
Ethical marketing fosters deeper relationships with customers by building trust. Research consistently shows that consumers are more loyal to brands they trust, with 71% indicating they would stop buying from a brand if trust is broken.
These trust-based relationships are more resilient during business challenges. When customers believe in a company’s integrity, they’re more likely to give the benefit of the doubt during controversies or service issues. They’re also more likely to provide constructive feedback rather than simply leaving for competitors.
Perhaps most importantly, loyal customers become advocates, sharing positive experiences with others and defending the brand against criticism. This organic advocacy is far more powerful than paid promotions and reduces customer acquisition costs significantly over time.
Enhanced brand reputation
A strong ethical stance improves overall brand perception across multiple dimensions. Media outlets are increasingly focused on corporate behaviour, providing positive coverage for ethical practices that extends a brand’s reach organically.
Social conversations about ethical brands tend to be more positive, with consumers sharing experiences and values rather than just discussing products. This creates a halo effect that benefits all aspects of the business.
This enhanced reputation also provides resilience during public relations challenges. Organisations with strong ethical foundations find it easier to navigate controversies because they’ve built a reservoir of goodwill with customers, employees, and other stakeholders.
Competitive advantage
Ethical marketing provides several distinct competitive advantages in modern markets. It helps brands access privacy-conscious consumer segments that actively avoid companies with questionable data practices. These segments often include higher-income, educated consumers who are valuable long-term customers.
Ethical approaches also reduce vulnerability to regulatory changes and potential penalties. As privacy laws continue to evolve globally, organisations with strong ethical foundations find compliance easier and less disruptive than those scrambling to meet minimum requirements.
Perhaps most significantly, ethical marketing supports more sustainable growth trajectories. While manipulative tactics might drive short-term results, they typically lead to higher churn rates and increasing acquisition costs. Ethical approaches build foundations for long-term success and stable growth.
For a detailed roadmap, download the Ethical Marketing Guide.
Case studies : Ethical marketing in action
Patagonia : Purpose-driven marketing
Patagonia integrates sustainability into its marketing, reinforcing its commitment to ethical business practices. By aligning with social causes, the brand strengthens customer loyalty.
Apple : Privacy as a competitive advantage
Apple positions itself as a leader in consumer privacy, ensuring data protection remains central to its marketing strategy. This commitment has become a key differentiator in the tech industry.
Matomo : The ethical analytics tool
Matomo offers privacy-first analytics that prioritise data ownership and compliance. Businesses using Matomo benefit from accurate insights while respecting user privacy.
These companies demonstrate that ethical marketing is not just a compliance requirement—it is a long-term competitive advantage.
Strategies for implementing ethical marketing
Aligning marketing efforts with brand values
Consistency between values and actions is essential for ethical marketing. This alignment starts with a clear understanding of what your organisation truly stands for—not just aspirational statements, but genuine commitments that inform daily decisions.
Implementing this alignment requires cross-functional collaboration. Marketing teams need to work closely with product development, customer service, and leadership to ensure consistency across all touchpoints. When different departments send contradictory messages about company values, trust erodes quickly.
Clear guidelines help marketing teams apply values in practical decisions, from campaign concepts to media placements. Regular ethical reviews of marketing plans can identify potential issues before campaigns launch, avoiding reactive corrections that damage credibility.
Privacy-first data strategies
Developing robust approaches to customer data is fundamental to ethical marketing. This starts with prioritising first-party data (collected directly from your own channels) and zero-party data (actively shared by customers through preference centres, surveys, and similar mechanisms).
Measuring success doesn’t have to come at the expense of privacy. Ethical analytics provide accurate insights while protecting user data, ensuring compliance, and enhancing customer trust.
Ethical personalisation approaches focus on using aggregated or anonymised data rather than individual tracking. This allows for relevant experiences without the invasive feeling that erodes trust when consumers feel watched across the internet.
Most importantly, ethical data strategies create transparent value exchanges where users clearly understand what benefits they receive in return for sharing information. This reciprocity transforms data collection from exploitation to fair exchange.
Measuring success ethically
Traditional marketing measurement often relies on individual-level tracking across sites and platforms. Ethical approaches require adapting these frameworks to respect privacy while still demonstrating impact.
Focusing on aggregate patterns rather than individual behaviour provides valuable insights without privacy invasions. For example, understanding that 30% of visitors to a specific page subsequently make purchases is actionable intelligence that doesn’t require tracking specific people.
Incrementality testing measures campaign impact by comparing outcomes between exposed and control groups at an aggregate level. This provides more accurate attribution than traditional last-click models while respecting privacy boundaries.
Server-side conversion tracking offers another ethical measurement approach, collecting necessary data on your servers rather than through client-side scripts vulnerable to blocking. This improves data accuracy while reducing reliance on cookies and browser storage.
Implementing ethical marketing strategies : A practical framework
1. Align marketing with brand values – Ensure campaigns reflect transparency and trust
2. Leverage first-party data – Collect insights directly from consumers with clear consent
3. Respect privacy and consent – Give users control over their data and clearly communicate its use
4. Create value-driven content – Offer educational and relevant resources instead of relying solely on advertising
5. Use privacy-compliant analytics – Switch to ethical platforms such as Matomo for responsible performance measurement
For a step-by-step guide to implementing ethical marketing strategies, download the full report here.
The future of ethical marketing
With the decline of third-party cookies and the rise of privacy regulations, ethical marketing is no longer optional. Brands that adopt privacy-first practices now will gain a sustainable competitive edge in the long term. The future of marketing belongs to brands that earn consumer trust, not those that exploit it.
Key trends shaping the future of marketing include :
- Privacy-first analytics to replace invasive tracking
- First-party and zero-party data strategies for direct consumer engagement
- Consent-driven personalisation to balance relevance and privacy
- Greater emphasis on corporate social responsibility in marketing initiatives
Companies that proactively address these changes will build stronger customer relationships, enhance brand reputation, and ensure long-term success.
Take the next step
Ready to transform your marketing approach for 2025 and beyond ?
Download Matomo’s comprehensive “2025 Ethical Marketing Field Guide” to get practical frameworks, implementation strategies, and real-world case studies that will help you build trust while driving growth.
With detailed guidance on first-party data activation, consent-based personalisation techniques, and privacy-preserving analytics methods, this guide provides everything you need to future-proof your marketing strategy in a privacy-first world.
Download the ethical marketing guide now to start building stronger, more trusted relationships with your customers through ethical marketing practices.
-
Making Your First-Party Data Work for You and Your Customers
11 mars, par Alex CarmonaAt last count, 162 countries had enacted data privacy policies of one kind or another. These laws or regulations, without exception, intend to eliminate the use of third-party data. That puts marketing under pressure because third-party data has been the foundation of online marketing efforts since the dawn of the Internet.
Marketers need to future-proof their operations by switching to first-party data. This will require considerable adjustment to systems and processes, but the reward will be effective marketing campaigns that satisfy privacy compliance requirements and bring the business closer to its customers.
To do that, you’ll need a coherent first-party data strategy. That’s what this article is all about. We’ll explain the different types of personal data and discuss how to use them in marketing without compromising or breaching data privacy regulations. We’ll also discuss how to build that strategy in your business.
So, let’s dive in.
The different data types
There are four distinct types of personal data used in marketing, each subject to different data privacy regulations.
Before getting into the different types, it’s essential to understand that all four may comprise one or more of the following :
Identifying data Name, email address, phone number, etc. Behavioural data Website activity, app usage, wishlist content, purchase history, etc. Transactional data Orders, payments, subscription details, etc. Account data Communication preferences, product interests, wish lists, etc. Demographic data Age, gender, income level, education, etc. Geographic Data Location-based information, such as zip codes or regional preferences. Psychographic Data Interests, hobbies and lifestyle preferences. First-party data
When businesses communicate directly with customers, any data they exchange is first-party. It doesn’t matter how the interaction occurs : on the telephone, a website, a chat session, or even in person.
Of course, the parties involved aren’t necessarily individuals. They may be companies, but people within those businesses will probably share at least some of the data with colleagues. That’s fine, so long as the data :
- Remains confidential between the original two parties involved, and
- It is handled and stored following applicable data privacy regulations.
The core characteristic of first-party data is that it’s collected directly from customer interactions. This makes it reliable, accurate and inherently compliant with privacy regulations — assuming the collecting party complies with data privacy laws.
A great example of first-party data use is in banking. Data collected from customer interactions is used to provide personalised services, detect fraud, assess credit risk and improve customer retention.
Zero-party data
There’s also a subset of first-party data, sometimes called zero-party data. It’s what users intentionally and proactively share with a business. It can be preferences, intentions, personal information, survey responses, support tickets, etc.
What makes it different is that the collection of this data depends heavily on the user’s trust. Transparency is a critical factor, too ; visitors expect to be informed about how you’ll use their data. Consumers also have the right to withdraw permission to use all or some of their information at any time.
Second-party data
This data is acquired from a separate organisation that collects it firsthand. Second-party data is someone else’s first-party data that’s later shared with or sold to other businesses. The key here is that whoever owns that data must give explicit consent and be informed of who businesses share their data with.
A good example is the cooperation between hotel chains, car rental companies, and airlines. They share joint customers’ flight data, hotel reservations, and car rental bookings, much like travel agents did before the internet undermined that business model.
Third-party data
This type of data is the arch-enemy of lawmakers and regulators trying to protect the personal data of citizens and residents in their country. It’s information collected by entities that have no direct relationship with the individuals whose data it is.
Third-party data is usually gathered, aggregated, and sold by data brokers or companies, often by using third-party cookies on popular websites. It’s an entire business model — these third-party brokers sell data for marketing, analytics, or research purposes.
Most of the time, third-party data subjects are unaware that their data has been gathered and sold. Hence the need for strong data privacy regulations.
Benefits of a first-party data strategy
First-party data is reliable, accurate, and ethically sourced. It’s an essential part of any modern digital marketing strategy.
More personalised experiences
The most important application of first-party data is customising and personalising customers’ interactions based on real behaviours and preferences. Personalised experiences aren’t restricted to websites and can extend to all customer communication.
The result is company communications and marketing messages are far more relevant to customers. It allows businesses to engage more meaningfully with them, building trust and strengthening customer relationships. Inevitably, this also results in stronger customer loyalty and better customer retention.
Greater understanding of customers
Because first-party data is more accurate and reliable, it can be used to derive valuable insights into customer needs and wants. When all the disparate first-party data points are centralised and organised, it’s possible to uncover trends and patterns in customer behaviour that might not be apparent using other data.
This helps businesses predict and respond to customer needs. It also allows marketing teams to be more deliberate when segmenting customers and prospects into like-minded groups. The data can also be used to create more precise personas for future campaigns or reveal how likely a customer would be to purchase in response to a campaign.
Build trust with customers
First-party data is unique to a business and originates from interactions with customers. It’s also data collected with consent and is “owned” by the company — if you can ever own someone else’s data. If treated like the precious resource, it can help businesses build trust with customers.
However, developing that trust requires a transparent, step-by-step approach. This gradually strengthens relationships to the point where customers are more comfortable sharing the information they’re asked for.
However, while building trust is a long and sometimes arduous process, it can be lost in an instant. That’s why first-party data must be protected like the Crown Jewels.
Components of a first-party data strategy
Security is essential to any first-party data strategy, and for good reason. As Gartner puts it, a business must find the optimal balance between business outcomes and data risk mitigation. Once security is baked in, attention can turn to the different aspects of the strategy.
Data collection
There are many ways to collect first-party data ethically, within the law and while complying with data privacy regulations, such as Europe’s General Data Protection Regulation (GDPR). Potential sources include :
Website activity forms and surveys, behavioural tracking, cookies, tracking pixels and chatbots Mobile app interactions in-app analytics, push notifications and in-app forms Email marketing newsletter sign-ups, email engagement tracking, promotions, polls and surveys Events registrations, post-event surveys and virtual event analytics Social media interaction polls and surveys, direct messages and social media analytics Previous transactions purchase history, loyalty programmes and e-receipts Customer service call centre data, live chat, chatbots and feedback forms In-person interactions in-store purchases, customer feedback and Wi-Fi sign-ins Gated content whitepapers, ebooks, podcasts, webinars and video downloads Interactive content quizzes, assessments, calculators and free tools CRM platforms customer profiles and sales data Consent management privacy policies, consent forms, preference setting Consent management
It may be the final item on the list above, but it’s also a key requirement of many data privacy laws and regulations. For example, the GDPR is very clear about consent : “Processing personal data is generally prohibited, unless it is expressly allowed by law, or the data subject has consented to the processing.”
For that reason, your first-party data strategy must incorporate various transparent consent mechanisms, such as cookie banners and opt-in forms. Crucially, you must provide customers with a mechanism to manage their preferences and revoke that consent easily if they wish to.
Data management
Effective first-party data management, mainly its security and storage, is critical. Most data privacy regimes restrict the transfer of personal data to other jurisdictions and even prohibit it in some instances. Many even specify where residents’ data must be stored.
Consider this cautionary tale : The single biggest fine levied for data privacy infringement so far was €1.2 billion. The Irish Data Protection Commission imposed a massive fine on Meta for transferring EU users’ data to the US without adequate data protection mechanisms.
Data security is critical. If first-party data is compromised, it becomes third-party data, and any customer trust developed with the business will evaporate. To add insult to injury, data regulators could come knocking. That’s why the trend is to use encryption and anonymisation techniques alongside standard access controls.
Once security is assured, the focus is on data management. Many businesses use a Customer Data Platform. This software gathers, combines and manages data from many sources to create a complete and central customer profile. Modern CRM systems can also do that job. AI tools could help find patterns and study them. But the most important thing is to keep databases clean and well-organised to make it easier to use and avoid data silos.
Data activation
Once first-party data has been collected and analysed, it needs to be activated, which means a business needs to use it for the intended purpose. This is the implementation phase where a well-constructed first-party strategy pays off.
The activation stage is where businesses use the intelligence they gather to :
- Personalise website and app experiences
- Adapt marketing campaigns
- Improve conversion rates
- Match stated preferences
- Cater to observed behaviours
- Customise recommendations based on purchase history
- Create segmented email campaigns
- Improve retargeting efforts
- Develop more impactful content
Measurement and optimisation
Because first-party data is collected directly from customers or prospects, it’s far more relevant, reliable, and specific. Your analytics and campaign tracking will be more accurate. This gives you direct and actionable insights into your audience’s behaviour, empowering you to optimise your strategies and achieve better results.
The same goes for your collection and activation efforts. An advanced web analytics platform like Matomo lets you identify key user behaviour and optimise your tracking. Heatmaps, marketing attribution tools, user behaviour analytics and custom reports allow you to segment audiences for better traction (and collect even more first-party data).
How to build a first-party data strategy
There are five important and sequential steps to building a first-party data strategy. But this isn’t a one-time process. It must be revisited regularly as operating and regulatory environments change. There are five steps :
- Audit existing data
Chances are that customers already freely provide a lot of first-party data in the normal course of business. The first step is to locate this data, and the easiest way to do that is by mapping the customer journey. This identifies all the touchpoints where first-party data might be found.
- Define objectives
Then, it’s time to step back and figure out the goals of the first-party data strategy. Consider what you’re trying to achieve. For example :
- Reduce churn
- Expand an existing loyalty programme
- Unload excess inventory
- Improve customer experiences
Whatever the objectives are, they should be clear and measurable.
- Implement tools and technology
The first two steps point to data gaps. Now, the focus turns to ethical web analytics with a tool like Matomo.
To further comply with data privacy regulations, it may also be appropriate to implement a Consent Management Platform (CMP) to help manage preferences and consent choices.
- Build trust with transparency
With the tools in place, it’s time to engage customers. To build trust, keep them informed about how their data is used and remind them of their right to withdraw their consent.
Transparency is crucial in such engagement, as outlined in the 7 GDPR principles.
- Continuously improve
Rinse and repeat. The one constant in business and life is change. As things change, they expose weaknesses or flaws in the logic behind systems and processes. That’s why a first-party data strategy needs to be continually reviewed, updated, and revised. It must adapt to changing trends, markets, regulations, etc.
Tools that can help
Looking back at the different types of data, it’s clear that some are harder and more bothersome to get than others. But capturing behaviours and interactions can be easy — especially if you use tools that follow data privacy rules.
But here’s a tip. Google Analytics 4 isn’t compliant by default, especially not with Europe’s GDPR. It may also struggle to comply with some of the newer data privacy regulations planned by different US states and other countries.
Matomo Analytics is compliant with the GDPR and many other data privacy regulations worldwide. Because it’s open source, it can be integrated with any consent manager.
Get started today by trying Matomo for free for 21 days,
no credit card required.